Docsity

Linear Regression Lecture Slide, Slides of Advanced Data Analysis

Toggle sidebar
bg1
AA037015 Lecture 2
Linear regression
The MASS library contains the Boston data set, which records medv (median house value)
for 506 neighborhoods around Boston. We will seek to predict medv using 13 predictors
such as rm (average number of rooms per house), age (average age of houses), and lstat
(percent of households with low socioeconomic status).
Use names() function to print all the variable name and attach() so the dataset Boston is
searched by R when evaluating a variable, and objects in the dataset can be accessed by
simply giving their names.
library(MASS)
library(ISLR)
names(Boston)
## [1] "crim" "zn" "indus" "chas" "nox" "rm" "age"
## [8] "dis" "rad" "tax" "ptratio" "black" "lstat" "medv"
attach(Boston)
We will start by using the lm() function to fit a simple linear regression model, with medv
as the response and lstat as the predictor. The basic syntax is lm(y~x,data) , where y is the
response, x is the predictor, and data is the data set in which these two variables are kept.
We can use the names() function in order to find out what other pieces of information are
stored in lm.fit. In order to obtain a confidence interval for the coefficient estimates, we can
use the confint() command.
lm.fit=lm(medv~lstat ,data=Boston)
lm.fit
##
## Call:
## lm(formula = medv ~ lstat, data = Boston)
##
## Coefficients:
## (Intercept) lstat
## 34.55 -0.95
names(lm.fit)
## [1] "coefficients" "residuals" "effects" "rank"
## [5] "fitted.values" "assign" "qr" "df.residual"
## [9] "xlevels" "call" "terms" "model"
coef(lm.fit)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Linear Regression Lecture Slide and more Slides Advanced Data Analysis in PDF only on Docsity!

AA037015 Lecture 2

Linear regression

The MASS library contains the Boston data set, which records medv (median house value)

for 506 neighborhoods around Boston. We will seek to predict medv using 13 predictors

such as rm (average number of rooms per house), age (average age of houses), and lstat

(percent of households with low socioeconomic status).

Use names() function to print all the variable name and attach() so the dataset Boston is

searched by R when evaluating a variable, and objects in the dataset can be accessed by

simply giving their names.

library(MASS) library(ISLR) names(Boston)

[1] "crim" "zn" "indus" "chas" "nox" "rm" "age"

[8] "dis" "rad" "tax" "ptratio" "black" "lstat" "medv"

attach(Boston)

We will start by using the lm() function to fit a simple linear regression model, with medv

as the response and lstat as the predictor. The basic syntax is lm(y~x,data) , where y is the

response, x is the predictor, and data is the data set in which these two variables are kept.

We can use the names() function in order to find out what other pieces of information are

stored in lm.fit. In order to obtain a confidence interval for the coefficient estimates, we can

use the confint() command.

lm.fit=lm(medv~lstat ,data=Boston) lm.fit

Call:

lm(formula = medv ~ lstat, data = Boston)

Coefficients:

(Intercept) lstat

34.55 - 0.

names(lm.fit)

[1] "coefficients" "residuals" "effects" "rank"

[5] "fitted.values" "assign" "qr" "df.residual"

[9] "xlevels" "call" "terms" "model"

coef(lm.fit)

(Intercept) lstat

34.5538409 - 0.

confint(lm.fit)

2.5 % 97.5 %

(Intercept) 33.448457 35.

lstat - 1.026148 - 0.

The predict() function can be used to produce confidence intervals and prediction intervals

for the prediction of medv for a given value of lstat.

predict(lm.fit,data.frame(lstat=c( 5 , 10 , 15 )),interval ="confidence")

fit lwr upr

1 29.80359 29.00741 30.

2 25.05335 24.47413 25.

3 20.30310 19.73159 20.

predict(lm.fit,data.frame(lstat=c( 5 , 10 , 15 )),interval ="prediction")

fit lwr upr

1 29.80359 17.565675 42. 04151

2 25.05335 12.827626 37.

3 20.30310 8.077742 32.

For instance, the 95% confidence interval associated with a lstat value of 10 is

(24.47,25.63), and the 95% prediction interval is (12.828,37.28). As expected, the

confidence and prediction intervals are centered around the same point (a predicted value

of 25.05 for medv when lstat equals 10), but the latter are substantially wider.

We will now plot medv and lstat along with the least squares regression line using the

plot() and abline() functions. The abline() function add a straight line through the current

plot. In the second line we widen the line using lwd=3 and changed the color to red.

plot(lstat ,medv) abline(lm.fit) abline(lm.fit,lwd= 3 ,col="red")

You can see here we can also use the symbol + in the graph. The second graph shows all the

values for pch from 1 to 20.

plot(lstat ,medv ,pch="+") plot( 1 : 20 , 1 : 20 ,pch= 1 : 20 ) # These are the values for pch

Next we examine some diagnostic plots. Four diagnostic plots are automatically produced

by applying the plot() function directly to the output from lm().

par(mfrow=c( 2 , 2 )) plot(lm.fit)

plot(predict(lm.fit), rstudent (lm.fit))

Leverage statistics can be computed for any number of predictors using the hatvalues()

function.

plot(hatvalues (lm.fit)) which.max(hatvalues (lm.fit))

375

375

MULTIPLE LINEAR REGRESSION lm.fit=lm(medv~lstat+age ,data=Boston) summary(lm.fit)

Call:

lm(formula = medv ~ lstat + age, data = Boston)

Residuals:

Min 1Q Median 3Q Max

- 15.981 - 3.978 - 1.283 1.968 23.

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) 33.22276 0.73085 45.458 < 2e-16 ***

lstat - 1.03207 0.04819 - 21.416 < 2e-16 ***

age 0.03454 0.01223 2.826 0.00491 **

crim zn indus chas nox rm age dis

1.792192 2.298758 3.991596 1.073995 4.393720 1.933744 3.100826 3.

rad tax ptratio black lstat

7.484496 9.008554 1.799084 1.348521 2.

What if we would like to perform a regression using all of the variables but one? For

example, in the above regression output, age has a high p-value. So we may wish to run a

regression excluding this predictor. The following syntax results in a regression using all

predictors except age.

lm.fit1=lm(medv~.-age,data=Boston) summary(lm.fit1)

Call:

lm(formula = medv ~. - age, data = Boston)

Residuals:

Min 1Q Median 3Q Max

- 15.6054 - 2.7313 - 0.5188 1.7601 26. 2243

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) 36.436927 5.080119 7.172 2.72e-12 ***

crim - 0.108006 0.032832 - 3.290 0.001075 **

zn 0.046334 0.013613 3.404 0.000719 ***

indus 0.020562 0.061433 0.335 0.

chas 2.689026 0.859598 3.128 0.001863 **

nox - 17.713540 3.679308 - 4.814 1.97e-06 ***

rm 3.814394 0.408480 9.338 < 2e-16 ***

dis - 1.47 8612 0.190611 - 7.757 5.03e-14 ***

rad 0.305786 0.066089 4.627 4.75e-06 ***

tax - 0.012329 0.003755 - 3.283 0.001099 **

ptratio - 0.952211 0.130294 - 7.308 1.10e-12 ***

black 0.009321 0.002678 3.481 0.000544 ***

lstat - 0.523852 0.047625 - 10.999 < 2e-16 ***

---

Signif. codes: 0 '' 0.001 '' 0.01 '' 0.05 '.' 0.1 ' ' 1

Residual standard error: 4.74 on 493 degrees of freedom

Multiple R-squared: 0.7406, Adjusted R-squared: 0.

F-statistic: 117.3 on 12 and 493 DF, p-value: < 2.2e- 16

Interaction term

It is easy to include interaction terms in a linear model using the lm() function. The syntax

lstat:black tells R to include an interaction term between lstat and black. The syntax

lstat*age simultaneously includes lstat , age , and the interaction term lstat x age as

predictors; it is a shorthand for lstat+age+lstat:age

summary(lm(medv~lstat*age,data=Boston))

Call:

lm(formula = medv ~ lstat * age, data = Boston)

Residuals:

Min 1Q Median 3Q Max

- 15.806 - 4.045 - 1.333 2.085 27.

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) 36.0885359 1.4698355 24.553 < 2e-16 ***

lstat - 1.3921168 0.1674555 - 8.313 8.78e-16 ***

age - 0.0007209 0.0198792 - 0.036 0.

lstat:age 0.0041560 0.0018518 2. 244 0.0252 *

---

Signif. codes: 0 '' 0.001 '' 0.01 '' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.149 on 502 degrees of freedom

Multiple R-squared: 0.5557, Adjusted R-squared: 0.

F-statistic: 209.3 on 3 and 502 DF, p-value: < 2.2e- 16

Non-linear Transformations of the Predictors

The lm() function can also accommodate non-linear transformations of the predictors. For

instance, given a predictor X, we can create a predictor X2 using I(X^2). The function I() is

needed since the ^ has a special meaning in a formula; wrapping as we do allows the

standard usage in R, which is to raise X to the power 2. We now perform a regression of

medv onto lstat and lstat^2.

lm.fit2=lm(medv~lstat+I(lstat^ 2 )) summary(lm.fit2)

Call:

lm(formula = medv ~ lstat + I(lstat^2))

Residuals:

Min 1Q Median 3Q Max

- 15.2834 - 3.8313 - 0.5295 2.3095 25.

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) 42.8 62007 0.872084 49.15 <2e-16 ***

lstat - 2.332821 0.123803 - 18.84 <2e-16 ***

I(lstat^2) 0.043547 0.003745 11.63 <2e-16 ***

---

Signif. codes: 0 '' 0.001 '' 0.01 '' 0.05 '.' 0.1 ' ' 1

In order to create a cubic fit, we can include a predictor of the form I(X^3). However, this

approach can start to get cumbersome for higher-order polynomials. A better approach

involves using the poly() function to create the polynomial within lm(). For example, the

following command produces a fifth-order polynomial fit:

lm.fit5=lm(medv~poly(lstat , 5 )) summary(lm.fit5)

Call:

lm(formula = medv ~ poly(lstat, 5))

Residuals:

Min 1Q Median 3Q Max

- 13.5433 - 3.1039 - 0.7052 2.0844 27.

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) 22.5328 0.2318 97.197 < 2e-16 ***

poly(lstat, 5)1 - 152.4595 5.2148 - 29.236 < 2e-16 ***

poly(lstat, 5)2 64.2272 5.2148 12.316 < 2e-16 ***

poly(lstat, 5)3 - 27.0511 5.2148 - 5.187 3.10e-07 ***

poly(lstat, 5)4 25.4517 5.2148 4.881 1.42e-06 ***

poly(lstat, 5)5 - 19.252 4 5.2148 - 3.692 0.000247 ***

---

Signif. codes: 0 '' 0.001 '' 0.01 '' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.215 on 500 degrees of freedom

Multiple R-squared: 0.6817, Adjusted R-squared: 0.

F-statistic: 214.2 on 5 and 500 DF, p-value: < 2.2e- 16

This suggests that including additional polynomial terms, up to fifth order, leads to an

improvement in the model fit! However, further investigation of the data reveals that no

polynomial terms beyond fifth order have significant p-values in a regression fit.

Of course, we are in no way restricted to using polynomial transformations of the

predictors. Here we try a log transformation.

summary(lm(medv~log(rm),data=Boston))

Call:

lm(formula = medv ~ log(rm), data = Boston)

Residuals:

Min 1Q Median 3Q Max

- 19.487 - 2.875 - 0.104 2.837 39.

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) - 76.488 5.028 - 15.21 <2e-16 ***

log(rm) 54.055 2.739 19.73 <2e-16 ***

---

Signif. codes: 0 '' 0.001 '' 0.01 '' 0.05 '.' 0.1 ' ' 1

Residual standard error: 6.915 on 504 degrees of freedom

Multiple R-squared: 0.4358, Adjusted R-squared: 0.

F-statistic: 389.3 on 1 and 504 DF, p-value: < 2.2e- 16

Qualitative Predictor

The Carseats data includes qualitative predictors such as Shelveloc, an indicator of the

quality of the shelving location - that is, the space within a store in which the car seat is

displayed - at each location. The predictor Shelveloc takes on three possible values, Bad,

Medium, and Good. Given a qualitative variable such as Shelveloc, R generates dummy

variables automatically. Below we fit a multiple regression model that includes some

interaction terms.

fix(Carseats) names(Carseats)

[1] "Sales" "CompPrice" "Income" "Advertising" "Population"

[6] "Price" "ShelveLoc" "Age" "Education" "Urban"

[11] "US"

lm.fit=lm(Sales~.+Income:Advertising +Price:Age,data=Carseats) summary(lm.fit)