edX assignment link: http://bit.ly/2KE2g00
The Programme for International Student Assessment (PISA) is a test given every three years to 15-year-old students from around the world to evaluate their performance in mathematics, reading, and science. This test provides a quantitative way to compare the performance of students from different parts of the world. In this homework assignment, we will predict the reading scores of students from the United States of America on the 2009 PISA exam.
The datasets pisa2009train.csv and pisa2009test.csv contain information about the demographics and schools for American students taking the exam, derived from 2009 PISA Public-Use Data Files distributed by the United States National Center for Education Statistics (NCES). While the datasets are not supposed to contain identifying information about students taking the test, by using the data you are bound by the NCES data use agreement, which prohibits any attempt to determine the identity of any student in the datasets.
Each row in the datasets pisa2009train.csv and pisa2009test.csv represents one student taking the exam. The datasets have the following variables:
grade: The grade in school of the student (most 15-year-olds in America are in 10th grade)
male: Whether the student is male (1/0)
raceeth: The race/ethnicity composite(種族) of the student
preschool: Whether the student attended preschool (1/0)
expectBachelors: Whether the student expects to obtain a bachelor’s degree (1/0)
motherHS: Whether the student’s mother completed high school (1/0)
motherBachelors: Whether the student’s mother obtained a bachelor’s degree (1/0)
motherWork: Whether the student’s mother has part-time or full-time work (1/0)
fatherHS: Whether the student’s father completed high school (1/0)
fatherBachelors: Whether the student’s father obtained a bachelor’s degree (1/0)
fatherWork: Whether the student’s father has part-time or full-time work (1/0)
selfBornUS: Whether the student was born in the United States of America (1/0)
motherBornUS: Whether the student’s mother was born in the United States of America (1/0)
fatherBornUS: Whether the student’s father was born in the United States of America (1/0)
englishAtHome: Whether the student speaks English at home (1/0)
computerForSchoolwork: Whether the student has access to a computer for schoolwork (1/0)
read30MinsADay: Whether the student reads for pleasure for 30 minutes/day (1/0)
minutesPerWeekEnglish: The number of minutes per week the student spend in English class
studentsInEnglish: The number of students in this student’s English class at school
schoolHasLibrary: Whether this student’s school has a library (1/0)
publicSchool: Whether this student attends a public school (1/0)
urban: Whether this student’s school is in an urban area (1/0)
schoolSize: The number of students in this student’s school
readingScore: The student’s reading score, on a 1000-point scale
Load the training and testing sets using the read.csv() function, and save them as variables with the names pisaTrain and pisaTest.
How many students are there in the training set?
TR = read.csv("data/pisa2009train.csv")
TS = read.csv("data/pisa2009test.csv")
nrow(TR)
[1] 3663
Using tapply() on pisaTrain, what is the average reading test score of males?
tapply(TR$readingScore,TR$male,mean) #ans: 483.5
0 1
512.9 483.5
Of females?
#ans: 512.9
Which variables are missing data in at least one observation in the training set? Select all that apply.
#summary(pisaTrain)
#or
is.na(TR) %>% colSums %>% {names(.)[. > 0]} #name?
[1] "raceeth" "preschool" "expectBachelors"
[4] "motherHS" "motherBachelors" "motherWork"
[7] "fatherHS" "fatherBachelors" "fatherWork"
[10] "selfBornUS" "motherBornUS" "fatherBornUS"
[13] "englishAtHome" "computerForSchoolwork" "read30MinsADay"
[16] "minutesPerWeekEnglish" "studentsInEnglish" "schoolHasLibrary"
[19] "schoolSize"
Linear regression discards observations with missing data, so we will remove all such observations from the training and testing sets. Later in the course, we will learn about imputation, which deals with missing data by filling in missing values with plausible information.
Type the following commands into your R console to remove observations with any missing value from pisaTrain and pisaTest:
pisaTrain = na.omit(pisaTrain)
pisaTest = na.omit(pisaTest)
How many observations are now in the training set?
TR = na.omit(TR)
TS = na.omit(TS)
nrow(TR)
[1] 2414
How many observations are now in the testing set?
nrow(TR)
[1] 2414
Factor variables are variables that take on a discrete set of values, like the “Region” variable in the WHO dataset from the second lecture of Unit 1. This is an unordered factor because there isn’t any natural ordering between the levels. An ordered factor has a natural ordering between the levels (an example would be the classifications “large,” “medium,” and “small”).
Which of the following variables is an unordered factor with at least 3 levels? (Select all that apply.)
levels(TR$raceeth)
[1] "American Indian/Alaska Native" "Asian"
[3] "Black" "Hispanic"
[5] "More than one race" "Native Hawaiian/Other Pacific Islander"
[7] "White"
Which of the following variables is an ordered factor with at least 3 levels? (Select all that apply.)
TR$grade %<>% as.factor()
levels(TR$grade)
[1] "8" "9" "10" "11" "12"
#grade
To include unordered factors in a linear regression model, we define one level as the “reference level” and add a binary variable for each of the remaining levels. In this way, a factor with n levels is replaced by n-1 binary variables. The reference level is typically selected to be the most frequently occurring level in the dataset.
As an example, consider the unordered factor variable “color”, with levels “red”, “green”, and “blue”. If “green” were the reference level, then we would add binary variables “colorred” and “colorblue” to a linear regression problem. All red examples would have colorred=1 and colorblue=0. All blue examples would have colorred=0 and colorblue=1. All green examples would have colorred=0 and colorblue=0.
Now, consider the variable “raceeth” in our problem, which has levels “American Indian/Alaska Native”, “Asian”, “Black”, “Hispanic”, “More than one race”, “Native Hawaiian/Other Pacific Islander”, and “White”. Because it is the most common in our population, we will select White as the reference level.
Which binary variables will be included in the regression model? (Select all that apply.)
#除了receethWhite以外的全部
Consider again adding our unordered factor race to the regression model with reference level “White”.
For a student who is Asian, which binary variables would be set to 0? All remaining variables will be set to 1. (Select all that apply.)
For a student who is white, which binary variables would be set to 0? All remaining variables will be set to 1. (Select all that apply.)
Because the race variable takes on text values, it was loaded as a factor variable when we read in the dataset with read.csv() – you can see this when you run str(pisaTrain) or str(pisaTest). However, by default R selects the first level alphabetically (“American Indian/Alaska Native”) as the reference level of our factor instead of the most common level (“White”). Set the reference level of the factor by typing the following two lines in your R console:
pisaTrain$raceeth = relevel(pisaTrain$raceeth, "White")
pisaTest$raceeth = relevel(pisaTest$raceeth, "White")
Now, build a linear regression model (call it lmScore) using the training set to predict readingScore using all the remaining variables.
It would be time-consuming to type all the variables, but R provides the shorthand notation “readingScore ~ .” to mean “predict readingScore using all the other variables in the data frame.” The period is used to replace listing out all of the independent variables. As an example, if your dependent variable is called “Y”, your independent variables are called “X1”, “X2”, and “X3”, and your training data set is called “Train”, instead of the regular notation:
LinReg = lm(Y ~ X1 + X2 + X3, data = Train)
You would use the following command to build your model:
LinReg = lm(Y ~ ., data = Train)
What is the Multiple R-squared value of lmScore on the training set?
TR$raceeth = relevel(TR$raceeth, "White")
TS$raceeth = relevel(TS$raceeth, "White")
lmScore = lm(readingScore~.,TR)
summary(lmScore)
Call:
lm(formula = readingScore ~ ., data = TR)
Residuals:
Min 1Q Median 3Q Max
-247.44 -48.86 1.86 49.77 217.18
Coefficients:
Estimate Std. Error t value
(Intercept) 143.76633 33.84123 4.25
grade 29.54271 2.93740 10.06
male -14.52165 3.15593 -4.60
raceethAmerican Indian/Alaska Native -67.27733 16.78693 -4.01
raceethAsian -4.11033 9.22007 -0.45
raceethBlack -67.01235 5.46088 -12.27
raceethHispanic -38.97549 5.17774 -7.53
raceethMore than one race -16.92252 8.49627 -1.99
raceethNative Hawaiian/Other Pacific Islander -5.10160 17.00570 -0.30
preschool -4.46367 3.48606 -1.28
expectBachelors 55.26708 4.29389 12.87
motherHS 6.05877 6.09142 0.99
motherBachelors 12.63807 3.86146 3.27
motherWork -2.80910 3.52183 -0.80
fatherHS 4.01821 5.57927 0.72
fatherBachelors 16.92975 3.99525 4.24
fatherWork 5.84280 4.39598 1.33
selfBornUS -3.80628 7.32372 -0.52
motherBornUS -8.79815 6.58762 -1.34
fatherBornUS 4.30699 6.26387 0.69
englishAtHome 8.03569 6.85949 1.17
computerForSchoolwork 22.50023 5.70256 3.95
read30MinsADay 34.87192 3.40845 10.23
minutesPerWeekEnglish 0.01279 0.01071 1.19
studentsInEnglish -0.28663 0.22782 -1.26
schoolHasLibrary 12.21509 9.26488 1.32
publicSchool -16.85748 6.72561 -2.51
urban -0.11013 3.96272 -0.03
schoolSize 0.00654 0.00220 2.98
Pr(>|t|)
(Intercept) 0.000022370704602 ***
grade < 2e-16 ***
male 0.000004416601017 ***
raceethAmerican Indian/Alaska Native 0.000063188108554 ***
raceethAsian 0.6558
raceethBlack < 2e-16 ***
raceethHispanic 0.000000000000073 ***
raceethMore than one race 0.0465 *
raceethNative Hawaiian/Other Pacific Islander 0.7642
preschool 0.2005
expectBachelors < 2e-16 ***
motherHS 0.3200
motherBachelors 0.0011 **
motherWork 0.4252
fatherHS 0.4715
fatherBachelors 0.000023464767187 ***
fatherWork 0.1839
selfBornUS 0.6033
motherBornUS 0.1818
fatherBornUS 0.4918
englishAtHome 0.2415
computerForSchoolwork 0.000081887761607 ***
read30MinsADay < 2e-16 ***
minutesPerWeekEnglish 0.2326
studentsInEnglish 0.2085
schoolHasLibrary 0.1875
publicSchool 0.0123 *
urban 0.9778
schoolSize 0.0029 **
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 73.8 on 2385 degrees of freedom
Multiple R-squared: 0.325, Adjusted R-squared: 0.317
F-statistic: 41 on 28 and 2385 DF, p-value: <2e-16
#R2 = 0.325
Note that this R-squared is lower than the ones for the models we saw in the lectures and recitation. This does not necessarily imply that the model is of poor quality. More often than not, it simply means that the prediction problem at hand (predicting a student’s test score based on demographic and school-related variables) is more difficult than other prediction problems (like predicting a team’s number of wins from their runs scored and allowed, or predicting the quality of wine from weather conditions).
What is the training-set root-mean squared error (RMSE) of lmScore?
pred = predict(lmScore)
SSE = sum((pred - TR$readingScore)^2) #sigma_sum((原本值-預測值)^2)
SST = sum((mean(TR$readingScore) - TR$readingScore)^2)
R2 = 1 - SSE/SST
R2
[1] 0.3251
RMSE = sqrt(SSE/nrow(TR))
RMSE
[1] 73.37
Consider two students A and B. They have all variable values the same, except that student A is in grade 11 and student B is in grade 9. What is the predicted reading score of student A minus the predicted reading score of student B?
#從前面model的summary得知,grade的estimate是29.54271,也就是每差一個grade,socre會增加29.54271
29.54271 *2
[1] 59.09
What is the meaning of the coefficient associated with variable raceethAsian?
Based on the significance codes, which variables are candidates for removal from the model? Select all that apply. (We’ll assume that the factor variable raceeth should only be removed if none of its levels are significant.)
Using the “predict” function and supplying the “newdata” argument, use the lmScore model to predict the reading scores of students in pisaTest. Call this vector of predictions “predTest”. Do not change the variables in the model (for example, do not remove variables that we found were not significant in the previous part of this problem). Use the summary function to describe the test set predictions.
What is the range between the maximum and minimum predicted reading score on the test set?
predTS = predict(lmScore,TS)
summary(predTS)
Min. 1st Qu. Median Mean 3rd Qu. Max.
353 482 524 517 556 638
What is the sum of squared errors (SSE) of lmScore on the testing set?
SSE = sum((TS$readingScore - predTS)^2)
SSE
[1] 5762082
SST = sum(TS$readingScore - mean(TS$readingScore)^2)
What is the root-mean squared error (RMSE) of lmScore on the testing set?
RMSE
[1] 76.29
What is the predicted test score used in the baseline model? Remember to compute this value using the training set and not the test set.
baseline
[1] 518
What is the sum of squared errors of the baseline model on the testing set? HINT: We call the sum of squared errors for the baseline model the total sum of squares (SST).
SSE = sum((baseline - TS$readingScore)^2)
SSE
[1] 7802354
What is the test-set R-squared value of lmScore?
R2
[1] 0.2612