Chapter 13 Generalized Additive Models

To overcome Spline Regression’s requirements for specifying the knots, we can use Generalized Additive Models or GAM.

library(mgcv)
## Loading required package: nlme
## 
## Attaching package: 'nlme'
## The following object is masked from 'package:dplyr':
## 
##     collapse
## This is mgcv 1.8-34. For overview type 'help("mgcv-package")'.
# Build the model
model <- gam(medv ~ s(lstat), data = train.data)
plot(model)

# Make predictions
# predictions <- model %>% predict(test.data)
# Model performance
data.frame(
  RMSE = RMSE(predictions, test.data$medv),
  R2 = R2(predictions, test.data$medv)
)
##       RMSE        R2
## 1 5.317372 0.6786367
ggplot(train.data, aes(lstat, medv) ) +
  geom_point() +
  stat_smooth(method = gam, formula = y ~ s(x))

detach(train.data)