We will use the Wage data set throughout the lab.
library(ISLR)
head(Wage)## year age maritl race education region
## 231655 2006 18 1. Never Married 1. White 1. < HS Grad 2. Middle Atlantic
## 86582 2004 24 1. Never Married 1. White 4. College Grad 2. Middle Atlantic
## 161300 2003 45 2. Married 1. White 3. Some College 2. Middle Atlantic
## 155159 2003 43 2. Married 3. Asian 4. College Grad 2. Middle Atlantic
## 11443 2005 50 4. Divorced 1. White 2. HS Grad 2. Middle Atlantic
## 376662 2008 54 2. Married 1. White 4. College Grad 2. Middle Atlantic
## jobclass health health_ins logwage wage
## 231655 1. Industrial 1. <=Good 2. No 4.318063 75.04315
## 86582 2. Information 2. >=Very Good 2. No 4.255273 70.47602
## 161300 1. Industrial 1. <=Good 1. Yes 4.875061 130.98218
## 155159 2. Information 2. >=Very Good 1. Yes 5.041393 154.68529
## 11443 2. Information 1. <=Good 1. Yes 4.318063 75.04315
## 376662 2. Information 2. >=Very Good 1. Yes 4.845098 127.11574
levels(Wage$education)## [1] "1. < HS Grad" "2. HS Grad" "3. Some College"
## [4] "4. College Grad" "5. Advanced Degree"
The following code chunk can be used to estimate the polynomial regression:
fit <- lm(wage ~ poly(age, 4), data = Wage)
coef(summary(fit))## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 111.70361 0.7287409 153.283015 0.000000e+00
## poly(age, 4)1 447.06785 39.9147851 11.200558 1.484604e-28
## poly(age, 4)2 -478.31581 39.9147851 -11.983424 2.355831e-32
## poly(age, 4)3 125.52169 39.9147851 3.144742 1.678622e-03
## poly(age, 4)4 -77.91118 39.9147851 -1.951938 5.103865e-02
The poly() function uses orthogonal polynomials which are essentially linear combinations of the variables age,age^2,age^3,age^4.
The function poly() can also be used directly without orthogonal polynomials using the raw option:
fit2 <- lm(wage ~ poly(age, 4, raw=T), data = Wage)
coef(summary(fit2))## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.841542e+02 6.004038e+01 -3.067172 0.0021802539
## poly(age, 4, raw = T)1 2.124552e+01 5.886748e+00 3.609042 0.0003123618
## poly(age, 4, raw = T)2 -5.638593e-01 2.061083e-01 -2.735743 0.0062606446
## poly(age, 4, raw = T)3 6.810688e-03 3.065931e-03 2.221409 0.0263977518
## poly(age, 4, raw = T)4 -3.203830e-05 1.641359e-05 -1.951938 0.0510386498
While this does not affect the predictions, the coefficient estimates will change.
Another option to estimate polynomial regression is to use
fit2a <- lm(wage ~ age + I(age^2) + I(age^3) + I(age^4), data = Wage)
coef(fit2a)## (Intercept) age I(age^2) I(age^3) I(age^4)
## -1.841542e+02 2.124552e+01 -5.638593e-01 6.810688e-03 -3.203830e-05
or
fit2b <- lm(wage ~ cbind(age, age^2, age^3, age^4), data = Wage)Create a grid of values for the variable age and then use the generic predict() function to obtain predictions along with standard errors.
# set range of age
agelims <- range(Wage$age)
age.grid <- seq(from=agelims[1], to=agelims[2])
# obtain predictions
preds <- predict(fit, newdata=list(age=age.grid), se=TRUE)
# confidence bands:
se.bands <- cbind(preds$fit+2*preds$se.fit, preds$fit-2*preds$se.fit)Plot to produce Figure 7.1 (left panel)
#par(mfrow=c(1,2), mar=c(4.5,4.5,1,1), oma=c(0,0,4,0))
plot(Wage$age, Wage$wage, xlim=agelims, cex=.5, col="darkgrey",
xlab = "Age", ylab = "Wage")
title("Degree-4 Polynomial", outer=T)
lines(age.grid, preds$fit, lwd=2, col="blue")
matlines(age.grid, se.bands, lwd=1, col="blue", lty=3)How do we choose the degree of the polynomial? One way is to use the ANOVA approach in which we conduct sequential F tests to evaluate nested models. Consider a sequence of polynomials from degree 1 to 5. The degree 1 will be nested in the degree 2, the degree 2 will be nested in degree 3, etc.
So, let’s estimate sequential models of polynomials with increasing complexity and apply F tests using anova() function.
fit.1 <- lm(wage ~ age, data=Wage)
fit.2 <- lm(wage ~ poly(age,2),data=Wage)
fit.3 <- lm(wage ~ poly(age,3),data=Wage)
fit.4 <- lm(wage ~ poly(age,4),data=Wage)
fit.5 <- lm(wage ~ poly(age,5),data=Wage)
anova(fit.1, fit.2, fit.3, fit.4, fit.5) ## Analysis of Variance Table
##
## Model 1: wage ~ age
## Model 2: wage ~ poly(age, 2)
## Model 3: wage ~ poly(age, 3)
## Model 4: wage ~ poly(age, 4)
## Model 5: wage ~ poly(age, 5)
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 2998 5022216
## 2 2997 4793430 1 228786 143.5931 < 2.2e-16 ***
## 3 2996 4777674 1 15756 9.8888 0.001679 **
## 4 2995 4771604 1 6070 3.8098 0.051046 .
## 5 2994 4770322 1 1283 0.8050 0.369682
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Compare linear Model 1 to quadratic Model-2: p-value is practically zero (< 2.2e-16) so we reject Model-1, i.e., linear model is not adequate.
Compare the quadratic Model-2 to the cubic Model 3: p-value = 0.0017, we reject Model-2, so the quadratic model is not sufficient.
Compare the cubic and degree-4 polynomials, Model 3 and Model 4: the p-value is approximately 5% while the degree-5 polynomial Model-5 seems unnecessary because its p-value is 0.37. Hence, either a cubic or a quartic (4th degree) polynomial appear to provide a reasonable fit to the data, but lower- or higher-order models are not justified.
coef(summary(fit.5))## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 111.70361 0.7287647 153.2780243 0.000000e+00
## poly(age, 5)1 447.06785 39.9160847 11.2001930 1.491111e-28
## poly(age, 5)2 -478.31581 39.9160847 -11.9830341 2.367734e-32
## poly(age, 5)3 125.52169 39.9160847 3.1446392 1.679213e-03
## poly(age, 5)4 -77.91118 39.9160847 -1.9518743 5.104623e-02
## poly(age, 5)5 -35.81289 39.9160847 -0.8972045 3.696820e-01
Exercise: Try cross-validation to choose the polynomial degree.
Now, let’s fit a logistic regression with polynomial terms using glm():
fit <- glm( I(wage>250) ~ poly(age, 4), data=Wage, family=binomial)
preds <- predict(fit, newdata=list(age=age.grid), se=T)
# obtain standard error bands
pfit <- exp(preds$fit)/(1+exp(preds$fit))
se.bands.logit <- cbind(preds$fit+2*preds$se.fit, preds$fit-2*preds$se.fit)
se.bands <- exp(se.bands.logit)/(1+exp(se.bands.logit))Plot the predicted probabilities and confidence bands (figure 7.1 right panel):
plot(Wage$age, I(Wage$wage>250), xlim=agelims, type="n", ylim=c(0,.2),
xlab = "Age", ylab = "Pr(wage>250)")
points(jitter(Wage$age), I((Wage$wage>250)/5),cex=.5,pch="|",col="darkgrey")
lines(age.grid,pfit,lwd=2, col="blue")
matlines(age.grid,se.bands,lwd=1,col="blue",lty=3)In the graphs above, the jitter() function is used to prevent the same age observations from overlapping each other.
Put both graphs together as in Figure 7.1:
par(mfrow=c(1,2), mar=c(4.5,4.5,1,1), oma=c(0,0,4,0))
plot(Wage$age, Wage$wage, xlim=agelims, cex=.5, col="darkgrey",
xlab = "Age", ylab = "Wage")
title("Degree-4 Polynomial", outer=T)
lines(age.grid, preds$fit, lwd=2, col="blue")
matlines(age.grid, se.bands, lwd=1, col="blue", lty=3)
plot(Wage$age, I(Wage$wage>250), xlim=agelims, type="n", ylim=c(0,.2),
xlab = "Age", ylab = "Pr(wage>250)")
points(jitter(Wage$age), I((Wage$wage>250)/5),cex=.5,pch="|",col="darkgrey")
lines(age.grid,pfit,lwd=2, col="blue")
matlines(age.grid,se.bands,lwd=1,col="blue",lty=3)The cut() function creates cutpoints in the observations, which are then used as predictors for the linear model to fit a step function.
table(cut(Wage$age, 4))##
## (17.9,33.5] (33.5,49] (49,64.5] (64.5,80.1]
## 750 1399 779 72
fit <- lm(wage ~ cut(age, 4), data = Wage)
coef(summary(fit))## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 94.158392 1.476069 63.789970 0.000000e+00
## cut(age, 4)(33.5,49] 24.053491 1.829431 13.148074 1.982315e-38
## cut(age, 4)(49,64.5] 23.664559 2.067958 11.443444 1.040750e-29
## cut(age, 4)(64.5,80.1] 7.640592 4.987424 1.531972 1.256350e-01
In R we can use splines library to fit spline models. The bs() function is used to specify basis functions. The default is the cubic splines. For example,
library(splines)
fit <- lm(wage ~ bs(age, knots=c(25,40,60)), data=Wage)
pred <- predict(fit, newdata=list(age=age.grid), se=T)
plot(Wage$age, Wage$wage, col="gray",
xlab = "Age", ylab = "Wage")
lines(age.grid, pred$fit, lwd=2)
lines(age.grid, pred$fit+2*pred$se, lty="dashed")
lines(age.grid, pred$fit-2*pred$se, lty="dashed")
abline(v=c(25,40,60), lty=2, col="darkgreen")The knots are specified at ages 25, 40, and 60. This produces a spline with 6 basis functions (a cubic spline with 3 knots has a 7 (=3+3+1) degrees of freedom).
Alternatively, the df() function can be used to produce a spline fit with knots at uniform intervals.
dim(bs(Wage$age, knots=c(25,40,60)))## [1] 3000 6
dim(bs(Wage$age, df=6))## [1] 3000 6
attr(bs(Wage$age, df=6), "knots")## 25% 50% 75%
## 33.75 42.00 51.00
R chooses knots at ages 33.8, 42.0, and 51.0, which correspond to the 25th, 50th, and 75th percentiles of age. The function bs() also has a degree argument, so we can fit splines of any degree, rather than the default degree of 3 (which yields a cubic spline).
To fit a natural spline we use ns() function.
fit2 <- lm(wage ~ ns(age, df=4), data=Wage)
pred2 <- predict(fit2, newdata=list(age=age.grid), se=T)
plot(Wage$age, Wage$wage, col="grey",
xlab = "Age", ylab = "Wage")
lines(age.grid, pred2$fit, col="red",lwd=2) We can fit a smoothing spline using smooth.spline()
plot(Wage$age, Wage$wage, xlim = agelims, cex = 0.5, col="darkgrey",
xlab = "Age", ylab = "Wage")
title(" Smoothing Spline ")
# fit a smoothing spline with degree 16
fit <- smooth.spline(Wage$age, Wage$wage, df = 16)
# chose df using cross-validation
fit2 <- smooth.spline(Wage$age, Wage$wage, cv = TRUE)
# cv yields df=6.8
fit2$df## [1] 6.794596
lines(fit, col="red",lwd=2)
lines(fit2, col="blue",lwd=2)
legend("topright",legend=c("16 DF","6.8 DF"),col=c("red","blue"),lty=1,lwd=2,cex=.8)Consider the following data set
# simulate data
set.seed(12345)
n <- 100
x <- seq(0,1,length=n)
fx <- 5*x*sin(2*pi*x) + 4*cos(3*pi*x)
y <- rnorm(n,fx,1)
data = data.frame(y,x)Visualize the data
library(ggplot2)
p1 <- ggplot(data,aes(x,y)) +
geom_point()
p1 + geom_line(aes(x,fx,col="Truth")) +
scale_colour_manual(" ", values=c("Truth"="black")) Let’s define two knots:
# we have knots
k1 <- 0.33
k2 <- 0.62
p1 + geom_line(aes(x,fx,col="Truth")) +
scale_colour_manual(" ", values=c("Truth"="black")) +
geom_vline(xintercept=c(k1,k2),
linetype="dotted", color = "blue", size=1)data$k1dummy <- ifelse(data$x>k1,1,0)
data$k1diff <- data$x - k1
data$xk1 <- data$k1diff*data$k1dummy
#
data$k2dummy <- ifelse(data$x>k2,1,0)
data$k2diff <- data$x - k2
data$xk2 <- data$k2diff*data$k2dummyggplot(data, aes(x,xk1)) +
geom_line() +
geom_line(aes(x,xk2,col="red")) +
theme(legend.position = "none")Visualization using bs() function
library(splines)
B = bs(x,knots=c(k1,k2),degre=1)
matplot(x,B,type="l",lty=1,lwd=2)Quadratic spline:
B = bs(x,knots=c(k1,k2),degre=2)
matplot(x,B,type="l",lty=1,lwd=2)Cubic spline:
B = bs(x,knots=c(k1,k2),degre=3)
matplot(x,B,type="l",lty=1,lwd=2)We can easily fit a spline using least squares:
# least squares estimation
model1 <- lm(y ~ x + xk1 +xk2, data=data)
summary(model1)##
## Call:
## lm(formula = y ~ x + xk1 + xk2, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.8855 -0.6839 0.1047 0.7506 3.0441
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.5385 0.3803 11.93 <2e-16 ***
## x -21.7928 1.6927 -12.88 <2e-16 ***
## xk1 37.5643 2.9413 12.77 <2e-16 ***
## xk2 -36.2132 2.6795 -13.52 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.194 on 96 degrees of freedom
## Multiple R-squared: 0.8025, Adjusted R-squared: 0.7963
## F-statistic: 130 on 3 and 96 DF, p-value: < 2.2e-16
yhat <- model1$fitted.values
p1 + geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,yhat,col="Linear spline")) +
scale_colour_manual(" ", values=c("Truth"="black","Linear spline"="red")) +
geom_vline(xintercept=c(k1,k2),
linetype="dotted", color = "blue", size=1)
Question What kind of fit would you expect if we used a single knot at k1 and a linear spline?
Here’s the answer
# least squares estimation
model1.a <- lm(y ~ x + xk1, data=data)
summary(model1.a)##
## Call:
## lm(formula = y ~ x + xk1, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.650 -1.578 0.045 1.265 4.830
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.4476 0.6299 5.473 3.46e-07 ***
## x -11.5667 2.5663 -4.507 1.84e-05 ***
## xk1 7.9507 3.3256 2.391 0.0187 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.024 on 97 degrees of freedom
## Multiple R-squared: 0.4268, Adjusted R-squared: 0.4149
## F-statistic: 36.11 on 2 and 97 DF, p-value: 1.902e-12
yhat.a <- model1.a$fitted.values
p1 + geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,yhat.a,col="Linear spline")) +
scale_colour_manual(" ", values=c("Truth"="black","Linear spline"="red")) Or using the splines library:
library(splines)
model1.bs <- lm(y ~ bs(x, knots = c(k1,k2), degree=1), data=data)
summary(model1.bs)##
## Call:
## lm(formula = y ~ bs(x, knots = c(k1, k2), degree = 1), data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.8855 -0.6839 0.1047 0.7506 3.0441
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.5385 0.3803 11.933 < 2e-16 ***
## bs(x, knots = c(k1, k2), degree = 1)1 -7.1916 0.5586 -12.875 < 2e-16 ***
## bs(x, knots = c(k1, k2), degree = 1)2 -2.6179 0.4519 -5.793 8.73e-08 ***
## bs(x, knots = c(k1, k2), degree = 1)3 -10.3858 0.5313 -19.548 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.194 on 96 degrees of freedom
## Multiple R-squared: 0.8025, Adjusted R-squared: 0.7963
## F-statistic: 130 on 3 and 96 DF, p-value: < 2.2e-16
yhat.bs <- model1.bs$fitted.values
# compare predictions
plot(yhat, yhat.bs)sum(yhat-yhat.bs)## [1] 2.858824e-15
Note that predictions from the first regression and the one in which we used bs() function are the same:
sum(yhat-yhat.bs)## [1] 2.858824e-15
Let’s fit a quadratic spline:
# quadratic fit
model2.bs <- lm(y ~ bs(x, knots = c(k1,k2), degree=2), data=data)
summary(model2.bs)##
## Call:
## lm(formula = y ~ bs(x, knots = c(k1, k2), degree = 2), data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.6924 -1.0746 -0.0456 0.9951 3.5613
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 5.8581 0.6292 9.310 4.93e-15 ***
## bs(x, knots = c(k1, k2), degree = 2)1 -8.1851 1.0806 -7.575 2.34e-11 ***
## bs(x, knots = c(k1, k2), degree = 2)2 -5.8493 0.6956 -8.409 4.10e-13 ***
## bs(x, knots = c(k1, k2), degree = 2)3 -5.2319 0.9367 -5.586 2.21e-07 ***
## bs(x, knots = c(k1, k2), degree = 2)4 -12.5679 0.8427 -14.915 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.451 on 95 degrees of freedom
## Multiple R-squared: 0.7116, Adjusted R-squared: 0.6994
## F-statistic: 58.6 on 4 and 95 DF, p-value: < 2.2e-16
yhat2.bs <- model2.bs$fitted.values
p1 + geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,yhat.bs,col="Linear spline")) +
geom_line(aes(x,yhat2.bs,col="Quadratic spline")) +
scale_colour_manual(" ", values=c("Truth"="black",
"Linear spline"="red",
"Quadratic spline"="blue")) +
theme(legend.position = "right")Cubic spline:
# Cubic spline fit
model3.bs <- lm(y ~ bs(x, knots = c(k1,k2), degree=3), data=data)
summary(model3.bs)##
## Call:
## lm(formula = y ~ bs(x, knots = c(k1, k2), degree = 3), data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.7179 -0.7895 0.1075 0.6046 2.3590
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.1560 0.5980 6.950 4.75e-10 ***
## bs(x, knots = c(k1, k2), degree = 3)1 -0.3666 1.1643 -0.315 0.75353
## bs(x, knots = c(k1, k2), degree = 3)2 -11.2863 0.7670 -14.716 < 2e-16 ***
## bs(x, knots = c(k1, k2), degree = 3)3 3.0505 1.0501 2.905 0.00458 **
## bs(x, knots = c(k1, k2), degree = 3)4 -10.5098 0.8795 -11.950 < 2e-16 ***
## bs(x, knots = c(k1, k2), degree = 3)5 -8.6936 0.8509 -10.217 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.126 on 94 degrees of freedom
## Multiple R-squared: 0.8281, Adjusted R-squared: 0.819
## F-statistic: 90.57 on 5 and 94 DF, p-value: < 2.2e-16
yhat3.bs <- model3.bs$fitted.values
p1 + geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,yhat.bs,col="Linear spline")) +
geom_line(aes(x,yhat2.bs,col="Quadratic spline")) +
geom_line(aes(x,yhat3.bs,col="Cubic spline")) +
scale_colour_manual(" ", values=c("Truth"="black",
"Linear spline"="red",
"Quadratic spline"="blue",
"Cubic spline"="darkgreen")) +
theme(legend.position = "right")Alternatively, we can set the degrees of freedom (df - model complexity) and let the knots be set automatically:
modeldf10 <- lm(y ~ bs(x, 10), data=data)
yhatdf10.bs <- modeldf10$fitted.values
summary(modeldf10)##
## Call:
## lm(formula = y ~ bs(x, 10), data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.6700 -0.7664 0.0501 0.7061 2.2627
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.5761 0.8645 5.294 8.56e-07 ***
## bs(x, 10)1 -1.2005 1.6567 -0.725 0.470589
## bs(x, 10)2 -2.0115 1.1429 -1.760 0.081828 .
## bs(x, 10)3 -6.4113 1.2708 -5.045 2.38e-06 ***
## bs(x, 10)4 -7.1879 1.0948 -6.566 3.36e-09 ***
## bs(x, 10)5 -4.3783 1.1626 -3.766 0.000297 ***
## bs(x, 10)6 -2.1992 1.1299 -1.946 0.054780 .
## bs(x, 10)7 -4.8896 1.1910 -4.105 8.94e-05 ***
## bs(x, 10)8 -8.6678 1.3303 -6.516 4.21e-09 ***
## bs(x, 10)9 -10.4482 1.3673 -7.642 2.35e-11 ***
## bs(x, 10)10 -8.4925 1.2214 -6.953 5.75e-10 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.144 on 89 degrees of freedom
## Multiple R-squared: 0.832, Adjusted R-squared: 0.8131
## F-statistic: 44.08 on 10 and 89 DF, p-value: < 2.2e-16
p1 + geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,yhatdf10.bs,col="df=10 spline")) +
scale_colour_manual(" ", values=c("Truth"="black","df=10 spline"="red")) Fitting a smoothing spline with df=10:
ssfit <- smooth.spline(x, y, df = 10)
p1 + geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,ssfit$y,col="Smooth spline df=10")) +
scale_colour_manual(" ", values=c("Truth"="black","Smooth spline df=10"="red")) Choose the df using cross-validation
ssfitcv <- smooth.spline(x, y, cv=TRUE)
ssfitcv$df## [1] 8.847658
p1 + geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,ssfit$y,col="Smooth spline df=10")) +
geom_line(aes(x,ssfitcv$y,col="Smooth spline df=8.85")) +
scale_colour_manual(" ", values=c("Truth"="black",
"Smooth spline df=10"="red",
"Smooth spline df=8.85"="blue"))
Exercise What happens if you set df=20 or even df=30? Which df would you prefer? Why?
In order to perform local regression, we use the loess() function.
plot(Wage$age, Wage$wage, xlim = agelims, cex = 0.5, col="darkgrey",
xlab = "Age", ylab = "Wage")
title("Local Regression")
fit <- loess(wage ~ age, span=.2, data=Wage)
fit2 <- loess(wage ~ age, span=.5, data=Wage)
lines(age.grid, predict(fit, data.frame(age=age.grid)), col="red", lwd=2)
lines(age.grid, predict(fit2, data.frame(age=age.grid)), col="blue", lwd=2)
legend("topright", legend=c("Span=0.2","Span=0.5"),
col=c("red","blue"), lty=1, lwd=2, cex=.8)Here we have performed local linear regression using spans of 0.2 and 0.5: that is, each neighborhood consists of 20% or 50% of the observations. The larger the span, the smoother the fit. The locfit library can also be used for fitting local regression models in R.
Example: Using simulated data:
library(tidyverse)
data_fit <- loess(y ~ x, span = 0.1, data = data)
y_hat <- predict(data_fit, data$x)
data_fit2 <- loess(y ~ x, span = 0.3, data = data)
y_hat2 <- predict(data_fit2, data$x)
df <- tibble(y = data$y,
x = data$x,
pred = y_hat,
pred2 = y_hat2)
head(df)## # A tibble: 6 x 4
## y x pred pred2
## <dbl> <dbl> <dbl> <dbl>
## 1 4.59 0 4.75 4.31
## 2 4.69 0.0101 4.34 4.18
## 3 3.83 0.0202 3.97 4.03
## 4 3.41 0.0303 3.66 3.88
## 5 4.37 0.0404 3.46 3.72
## 6 1.82 0.0505 3.31 3.56
ggplot(df, aes(x,y)) + geom_point() +
geom_line(aes(x,fx,col="Truth")) +
geom_line(aes(x,pred, col="Span=0.1")) +
geom_line(aes(x,pred2, col="Span=0.3"))LOESS using ggplot2::geom_smooth():
ggplot(data, aes(x,y)) +
geom_point() +
geom_line(aes(x,fx,col="Truth")) +
geom_smooth(method = "loess", span=0.1, se = FALSE, aes(col="span=0.1")) +
geom_smooth(method = "loess", span=0.3, se = FALSE, aes(col="span=0.3"))A GAM model can be fit using the lm() function. For example, to fit a GAM to predict wage using natural spline functions of year and age, treating education as a qualitative predictor, we can use
gam1 <- lm(wage ~ ns(year,4) + ns(age,5) + education, data=Wage)
summary(gam1)##
## Call:
## lm(formula = wage ~ ns(year, 4) + ns(age, 5) + education, data = Wage)
##
## Residuals:
## Min 1Q Median 3Q Max
## -120.513 -19.608 -3.583 14.112 214.535
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 46.949 4.704 9.980 < 2e-16 ***
## ns(year, 4)1 8.625 3.466 2.488 0.01289 *
## ns(year, 4)2 3.762 2.959 1.271 0.20369
## ns(year, 4)3 8.127 4.211 1.930 0.05375 .
## ns(year, 4)4 6.806 2.397 2.840 0.00455 **
## ns(age, 5)1 45.170 4.193 10.771 < 2e-16 ***
## ns(age, 5)2 38.450 5.076 7.575 4.78e-14 ***
## ns(age, 5)3 34.239 4.383 7.813 7.69e-15 ***
## ns(age, 5)4 48.678 10.572 4.605 4.31e-06 ***
## ns(age, 5)5 6.557 8.367 0.784 0.43328
## education2. HS Grad 10.983 2.430 4.520 6.43e-06 ***
## education3. Some College 23.473 2.562 9.163 < 2e-16 ***
## education4. College Grad 38.314 2.547 15.042 < 2e-16 ***
## education5. Advanced Degree 62.554 2.761 22.654 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 35.16 on 2986 degrees of freedom
## Multiple R-squared: 0.293, Adjusted R-squared: 0.2899
## F-statistic: 95.2 on 13 and 2986 DF, p-value: < 2.2e-16
But the function lm() cannot be used to estimate a GAM with smoothing splines. For this we can use gam library.
library(gam)
gam.m3 <- gam(wage ~ s(year,4) + s(age,5) + education, data=Wage)In the chunk above, the gam::s() function is used to indicate that we would like to use a smoothing spline. The variable year is set to have 4 degrees of freedom (df) and the function of the variable will have 5 df. Because the education variable is qualitative, it is left as is, resulting in the presence of four dummy variables.
The plot function after the GAM estimation is particularly useful to see the shapes of estimated functions:
par(mfrow=c(1,3))
plot(gam.m3, se=TRUE,col="blue")plot.Gam(gam1 , se=TRUE , col ="red ")We can perfom a series of anova() tests to find the best model. In the following
m1: GAM excludes year m2: GAM uses a linear function of year m3: GAM uses a spline function of year (estimated previously)
gam.m1 <- gam(wage ~ s(age,5) + education, data=Wage)
gam.m2 <- gam(wage ~ year + s(age,5) + education, data=Wage)
anova(gam.m1, gam.m2, gam.m3, test="F") ## Analysis of Deviance Table
##
## Model 1: wage ~ s(age, 5) + education
## Model 2: wage ~ year + s(age, 5) + education
## Model 3: wage ~ s(year, 4) + s(age, 5) + education
## Resid. Df Resid. Dev Df Deviance F Pr(>F)
## 1 2990 3711731
## 2 2989 3693842 1 17889.2 14.4771 0.0001447 ***
## 3 2986 3689770 3 4071.1 1.0982 0.3485661
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Based on these result, m2 is preferred to m1, that is, a model that includes a linear function of year is better than a model without year. But nonlinear function of year is not needed as we do not reject the null for comparing m2 vs. m3. So we prefer a model with a linear function of year.
We can use summary() function after the GAM estimation to generate a summary of the fitted model.
summary(gam.m3)##
## Call: gam(formula = wage ~ s(year, 4) + s(age, 5) + education, data = Wage)
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -119.43 -19.70 -3.33 14.17 213.48
##
## (Dispersion Parameter for gaussian family taken to be 1235.69)
##
## Null Deviance: 5222086 on 2999 degrees of freedom
## Residual Deviance: 3689770 on 2986 degrees of freedom
## AIC: 29887.75
##
## Number of Local Scoring Iterations: NA
##
## Anova for Parametric Effects
## Df Sum Sq Mean Sq F value Pr(>F)
## s(year, 4) 1 27162 27162 21.981 2.877e-06 ***
## s(age, 5) 1 195338 195338 158.081 < 2.2e-16 ***
## education 4 1069726 267432 216.423 < 2.2e-16 ***
## Residuals 2986 3689770 1236
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Anova for Nonparametric Effects
## Npar Df Npar F Pr(F)
## (Intercept)
## s(year, 4) 3 1.086 0.3537
## s(age, 5) 4 32.380 <2e-16 ***
## education
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
The p-values for year and age correspond to a null hypothesis of a linear relationship versus the alternative of a non-linear relationship. For the variable year, a linear relationship is preferred as indicated by large p-value (0.35). But a nonlinear relationship is required for age.
Making predictions:
preds <- predict(gam.m2, newdata=Wage)We can use a loess fit as a smoothing term in a GAM formula using the lo()
gam.lo <- gam(wage ~ s(year, df = 4) + lo(age, span = 0.7) + education, data = Wage)
plot.Gam(gam.lo, se = TRUE, col = "green")In the code chunk above, we used local regression for the age term, with a span of 0.7. We can also use the lo() function to create interactions before calling the gam() function. For example,
gam.lo.i <- gam(wage ~ lo(year, age, span = 0.5) + education, data = Wage)We can plot the resulting two-dimensional surface if we first install the akima package.
library(akima)
plot(gam.lo.i)In order to fit a logistic regression GAM, we use the I() function in constructing the binary response variable, and set family=binomial.
gam.lr <- gam(I(wage > 250) ~ year + s(age, df = 5) + education, family = binomial, data = Wage)
par(mfrow = c(1, 3))
plot(gam.lr, se = T, col = "green")Notice the large confidence band in the “<HS” category. This is because there are no high earners in the “<HS” category:
table(Wage$education, I(Wage$wage > 250))##
## FALSE TRUE
## 1. < HS Grad 268 0
## 2. HS Grad 966 5
## 3. Some College 643 7
## 4. College Grad 663 22
## 5. Advanced Degree 381 45
We fit a logistic regression GAM using all but this category. This provides more sensible results. Notice how we set the subset option below:
gam.lr.s <- gam(I(wage > 250) ~ year + s(age, df = 5) + education, family = binomial, data = Wage, subset = (education != "1. < HS Grad"))
plot(gam.lr.s, se = T, col = "green")