library(ISLR2)
library(splines)
library(mgcv)
library(car)
library(strucchange)
library(ggplot2)
data(Wage)
data("mcycle", package = "MASS")
cv_mse <- function(formula, data, K = 10, seed = 1) {
set.seed(seed)
folds <- sample(rep(1:K, length.out = nrow(data)))
y <- eval(formula[[2]], data)
errs <- sapply(1:K, function(k) {
fit <- lm(formula, data = data[folds != k, ])
pred <- predict(fit, newdata = data[folds == k, ])
mean((y[folds == k] - pred)^2)
})
mean(errs)
}
pred_band <- function(fit, newdata) {
p <- predict(fit, newdata, se.fit = TRUE)
data.frame(newdata, fit = p$fit,
lwr = p$fit - 2 * p$se.fit, upr = p$fit + 2 * p$se.fit)
}
plot_band <- function(df, titulo, color = "darkred") {
ggplot(df, aes(age, fit)) +
geom_point(data = Wage, aes(age, wage), inherit.aes = FALSE,
alpha = 0.15, color = "grey40") +
geom_ribbon(aes(ymin = lwr, ymax = upr), alpha = 0.25, fill = color) +
geom_line(color = color, linewidth = 1) +
labs(title = titulo, x = "age", y = "wage") +
theme_minimal()
}
age_grid <- data.frame(age = seq(min(Wage$age), max(Wage$age), length.out = 200))