if (!require(ISLR2)) install.packages(“ISLR2”) library(ISLR2)
data(Auto) head(Auto)
lm_fit <- lm(mpg ~ horsepower, data = Auto) summary(lm_fit)
par(mfrow = c(1, 2)) # side-by-side plots
plot(lm_fit\(fitted.values, lm_fit\)residuals, main = “Linear Modelvs. Fitted”, xlab = “Fitted Values”, ylab = “Residuals”, pch = 20, col = “steelblue”) abline(h = 0, col = “red”, lwd = 2, lty = 2) lines(lowess(lm_fit\(fitted.values, lm_fit\)residuals), col = “orange”, lwd = 2)
poly_fit <- lm(mpg ~ poly(horsepower, 2), data = Auto) summary(poly_fit)
plot(poly_fit\(fitted.values, poly_fit\)residuals, main = “Polynomial (Degree 2) Modelvs. Fitted”, xlab = “Fitted Values”, ylab = “Residuals”, pch = 20, col = “darkgreen”) abline(h = 0, col = “red”, lwd = 2, lty = 2) lines(lowess(poly_fit\(fitted.values, poly_fit\)residuals), col = “orange”, lwd = 2)
par(mfrow = c(1, 1)) # reset layout
par(mfrow = c(1, 2)) plot(lm_fit, which = 1, main = “Linear: Residuals vs Fitted”) plot(poly_fit, which = 1, main = “Poly: Residuals vs Fitted”) par(mfrow = c(1, 1))
plot(Auto\(horsepower, Auto\)mpg, main = “MPG vs Horsepower with Regression Fits”, xlab = “Horsepower”, ylab = “MPG”, pch = 20, col = “gray60”)
abline(lm_fit, col = “steelblue”, lwd = 2)
hp_range <- seq(min(Auto\(horsepower), max(Auto\)horsepower), length.out = 300) poly_pred <- predict(poly_fit, newdata = data.frame(horsepower = hp_range)) lines(hp_range, poly_pred, col = “darkgreen”, lwd = 2)
legend(“topright”, legend = c(“Linear Fit”, “Polynomial Fit (degree 2)”), col = c(“steelblue”, “darkgreen”), lwd = 2)