2. Carefully explain the differences between the KNN classifier and KNN regression methods.
We use the KNN classifier whenever we’re dealing with categorical variables, while we use regression methods when we have quantitative variables.
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.1 ✔ purrr 1.0.1
## ✔ tibble 3.1.8 ✔ dplyr 1.1.0
## ✔ tidyr 1.3.0 ✔ stringr 1.5.0
## ✔ readr 2.1.4 ✔ forcats 1.0.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(ISLR)
library(tinytex)
9. This question involves the use of multiple linear regression on the Auto data set. (a) Produce a scatterplot matrix which includes all of the variables in the data set.
pairs(Auto)
(b) Compute the matrix of correlations between the variables using the function cor(). You will need to exclude the name variable, which is qualitative.
cor(Auto[,-9])
## mpg cylinders displacement horsepower weight
## mpg 1.0000000 -0.7776175 -0.8051269 -0.7784268 -0.8322442
## cylinders -0.7776175 1.0000000 0.9508233 0.8429834 0.8975273
## displacement -0.8051269 0.9508233 1.0000000 0.8972570 0.9329944
## horsepower -0.7784268 0.8429834 0.8972570 1.0000000 0.8645377
## weight -0.8322442 0.8975273 0.9329944 0.8645377 1.0000000
## acceleration 0.4233285 -0.5046834 -0.5438005 -0.6891955 -0.4168392
## year 0.5805410 -0.3456474 -0.3698552 -0.4163615 -0.3091199
## origin 0.5652088 -0.5689316 -0.6145351 -0.4551715 -0.5850054
## acceleration year origin
## mpg 0.4233285 0.5805410 0.5652088
## cylinders -0.5046834 -0.3456474 -0.5689316
## displacement -0.5438005 -0.3698552 -0.6145351
## horsepower -0.6891955 -0.4163615 -0.4551715
## weight -0.4168392 -0.3091199 -0.5850054
## acceleration 1.0000000 0.2903161 0.2127458
## year 0.2903161 1.0000000 0.1815277
## origin 0.2127458 0.1815277 1.0000000
(c) Use the lm() function to perform a multiple linear regression with mpg as the response and all other variables except name as the predictors. Use the summary() function to print the results. Comment on the output. For instance: i. Is there a relationship between the predictors and the response? ii. Which predictors appear to have a statistically significant relationship to the response? iii. What does the coefficient for the year variable suggest?
Auto$origin <-factor(Auto$origin)
cars <- lm(mpg ~ . - name, data = Auto)
summary(cars)
##
## Call:
## lm(formula = mpg ~ . - name, data = Auto)
##
## Residuals:
## Min 1Q Median 3Q Max
## -9.0095 -2.0785 -0.0982 1.9856 13.3608
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.795e+01 4.677e+00 -3.839 0.000145 ***
## cylinders -4.897e-01 3.212e-01 -1.524 0.128215
## displacement 2.398e-02 7.653e-03 3.133 0.001863 **
## horsepower -1.818e-02 1.371e-02 -1.326 0.185488
## weight -6.710e-03 6.551e-04 -10.243 < 2e-16 ***
## acceleration 7.910e-02 9.822e-02 0.805 0.421101
## year 7.770e-01 5.178e-02 15.005 < 2e-16 ***
## origin2 2.630e+00 5.664e-01 4.643 4.72e-06 ***
## origin3 2.853e+00 5.527e-01 5.162 3.93e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.307 on 383 degrees of freedom
## Multiple R-squared: 0.8242, Adjusted R-squared: 0.8205
## F-statistic: 224.5 on 8 and 383 DF, p-value: < 2.2e-16
Because our overall p-value is less than < 2.2e-16, we reject the null hypothesis that all of the regression coefficients are 0.
All of the variables except for acceleration, cylinders, and horsepower are significant.
The coefficient is .7770, which means that for every .777 increase in year, the mpg increase by 1.
(d) Use the plot() function to produce diagnostic plots of the linear regression fit. Comment on any problems you see with the fit. Do the residual plots suggest any unusually large outliers? Does the leverage plot identify any observations with unusually high leverage?
par(mfrow=c(2,2))
plot(cars)
carsdiagnostics <- broom::augment(cars) %>%
select(.rownames, .fitted, .hat, .resid, .std.resid, .cooksd) %>%
arrange(desc(.cooksd))
carsdiagnostics
'I found this code online to help identify large Cooks D points and leverage points'
## [1] "I found this code online to help identify large Cooks D points and leverage points"
carsdiagnostics$cooksd_cutoff <- factor(ifelse(carsdiagnostics$.cooksd >= 4 /
nrow(Auto), "True", "False"))
ggplot(carsdiagnostics, aes(x = .hat, y = .std.resid, col = cooksd_cutoff)) +
geom_point(alpha = 0.8) +
scale_color_manual(values = c("mediumseagreen", "#BB8FCE")) +
theme_light() +
theme(legend.position = "bottom") +
labs(title = "Residuals vs Leverage",
x = "Leverage",
y = "Standardized Residuals",
col = "Cooks Distance >= 4/n")
As you can see, we do have a couple problems with our model. The first
is that our residuals seem to not be linearly distributed. We also have
one extremely high leverage point that seems to be influncing our fit.
We do have an R-squared of.82, so we our model does fit the data
relatively well.
(e) Use the * and : symbols to fit linear regression models with interaction effects. Do any interactions appear to be statistically significant?
summary(lm(formula = mpg ~ . * ., data = Auto[, -9]))
##
## Call:
## lm(formula = mpg ~ . * ., data = Auto[, -9])
##
## Residuals:
## Min 1Q Median 3Q Max
## -7.6008 -1.2863 0.0813 1.2082 12.0382
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.401e+01 5.147e+01 0.855 0.393048
## cylinders 3.302e+00 8.187e+00 0.403 0.686976
## displacement -3.529e-01 1.974e-01 -1.788 0.074638 .
## horsepower 5.312e-01 3.390e-01 1.567 0.117970
## weight -3.259e-03 1.820e-02 -0.179 0.857980
## acceleration -6.048e+00 2.147e+00 -2.818 0.005109 **
## year 4.833e-01 5.923e-01 0.816 0.415119
## origin2 -3.517e+01 1.260e+01 -2.790 0.005547 **
## origin3 -3.765e+01 1.426e+01 -2.640 0.008661 **
## cylinders:displacement -6.316e-03 7.106e-03 -0.889 0.374707
## cylinders:horsepower 1.452e-02 2.457e-02 0.591 0.555109
## cylinders:weight 5.703e-04 9.044e-04 0.631 0.528709
## cylinders:acceleration 3.658e-01 1.671e-01 2.189 0.029261 *
## cylinders:year -1.447e-01 9.652e-02 -1.499 0.134846
## cylinders:origin2 -7.210e-01 1.088e+00 -0.662 0.508100
## cylinders:origin3 1.226e+00 1.007e+00 1.217 0.224379
## displacement:horsepower -5.407e-05 2.861e-04 -0.189 0.850212
## displacement:weight 2.659e-05 1.455e-05 1.828 0.068435 .
## displacement:acceleration -2.547e-03 3.356e-03 -0.759 0.448415
## displacement:year 4.547e-03 2.446e-03 1.859 0.063842 .
## displacement:origin2 -3.364e-02 4.220e-02 -0.797 0.425902
## displacement:origin3 5.375e-02 4.145e-02 1.297 0.195527
## horsepower:weight -3.407e-05 2.955e-05 -1.153 0.249743
## horsepower:acceleration -3.445e-03 3.937e-03 -0.875 0.382122
## horsepower:year -6.427e-03 3.891e-03 -1.652 0.099487 .
## horsepower:origin2 -4.869e-03 5.061e-02 -0.096 0.923408
## horsepower:origin3 2.289e-02 6.252e-02 0.366 0.714533
## weight:acceleration -6.851e-05 2.385e-04 -0.287 0.774061
## weight:year -8.065e-05 2.184e-04 -0.369 0.712223
## weight:origin2 2.277e-03 2.685e-03 0.848 0.397037
## weight:origin3 -4.498e-03 3.481e-03 -1.292 0.197101
## acceleration:year 6.141e-02 2.547e-02 2.412 0.016390 *
## acceleration:origin2 9.234e-01 2.641e-01 3.496 0.000531 ***
## acceleration:origin3 7.159e-01 3.258e-01 2.198 0.028614 *
## year:origin2 2.932e-01 1.444e-01 2.031 0.043005 *
## year:origin3 3.139e-01 1.483e-01 2.116 0.035034 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.628 on 356 degrees of freedom
## Multiple R-squared: 0.8967, Adjusted R-squared: 0.8866
## F-statistic: 88.34 on 35 and 356 DF, p-value: < 2.2e-16
It looks like cylinders:acceleration, acceleration:year, acceleration:origin2, acceleration:origin3, year:origin2, and year:origin3 are all significant.
(f) Try a few different transformations of the variables, such as log(X), √ X, X2. Comment on your findings.
' I added a quadratic term for weight and displacement. I also took the log of mpg'
## [1] " I added a quadratic term for weight and displacement. I also took the log of mpg"
cars2 <- lm(log(mpg) ~ . - name + I(weight^2) + I(displacement^2), data = Auto)
summary(cars2)
##
## Call:
## lm(formula = log(mpg) ~ . - name + I(weight^2) + I(displacement^2),
## data = Auto)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.41393 -0.06782 0.00447 0.06595 0.38941
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.006e+00 1.772e-01 11.321 < 2e-16 ***
## cylinders -7.343e-04 1.278e-02 -0.057 0.954210
## displacement -1.985e-03 8.154e-04 -2.435 0.015355 *
## horsepower -2.438e-03 5.170e-04 -4.717 3.37e-06 ***
## weight -3.038e-04 9.911e-05 -3.066 0.002325 **
## acceleration -3.716e-03 3.389e-03 -1.097 0.273492
## year 3.066e-02 1.790e-03 17.122 < 2e-16 ***
## origin2 3.771e-02 2.142e-02 1.761 0.079082 .
## origin3 2.854e-02 2.063e-02 1.383 0.167442
## I(weight^2) 1.472e-08 1.349e-08 1.091 0.275892
## I(displacement^2) 4.456e-06 1.309e-06 3.403 0.000738 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.1124 on 381 degrees of freedom
## Multiple R-squared: 0.8936, Adjusted R-squared: 0.8908
## F-statistic: 320 on 10 and 381 DF, p-value: < 2.2e-16
This increased the Adjusted R-Squared from 0.8205 to .0898.
10. This question should be answered using the Carseats data set. (a) Fit a multiple regression model to predict Sales using Price, Urban, and US.
seats <- lm(Sales ~ Price + Urban + US, data = Carseats)
summary(seats)
##
## Call:
## lm(formula = Sales ~ Price + Urban + US, data = Carseats)
##
## Residuals:
## Min 1Q Median 3Q Max
## -6.9206 -1.6220 -0.0564 1.5786 7.0581
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 13.043469 0.651012 20.036 < 2e-16 ***
## Price -0.054459 0.005242 -10.389 < 2e-16 ***
## UrbanYes -0.021916 0.271650 -0.081 0.936
## USYes 1.200573 0.259042 4.635 4.86e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.472 on 396 degrees of freedom
## Multiple R-squared: 0.2393, Adjusted R-squared: 0.2335
## F-statistic: 41.52 on 3 and 396 DF, p-value: < 2.2e-16
(b) Provide an interpretation of each coefficient in the model. Be careful—some of the variables in the model are qualitative!
For every .0545 decrease in price, the sales increases by 1. There is a difference of 22 sales between urban and rural. There is also an difference of 1200 sales between US and foreign stores.
(c) Write out the model in equation form, being careful to handle the qualitative variables properly.
Sales = 13.043469 - 0.054459(Price) - 0.021916(UrbanYes) +1.200573(USYes)
d) For which of the predictors can you reject the null hypothesis H0 : βj = 0?
We can reject the null hypothesis for Price and USYes. It seems that we have insignificant evidence to reject the null hypothesis for UrbanYes.
(e) On the basis of your response to the previous question, fit a smaller model that only uses the predictors for which there is evidence of association with the outcome.
seats2 <- lm(Sales ~ Price + US, data = Carseats)
summary(seats2)
##
## Call:
## lm(formula = Sales ~ Price + US, data = Carseats)
##
## Residuals:
## Min 1Q Median 3Q Max
## -6.9269 -1.6286 -0.0574 1.5766 7.0515
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 13.03079 0.63098 20.652 < 2e-16 ***
## Price -0.05448 0.00523 -10.416 < 2e-16 ***
## USYes 1.19964 0.25846 4.641 4.71e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2.469 on 397 degrees of freedom
## Multiple R-squared: 0.2393, Adjusted R-squared: 0.2354
## F-statistic: 62.43 on 2 and 397 DF, p-value: < 2.2e-16
(f) How well do the models in (a) and (e) fit the data?
These models don’t fit the data very well. They both have an extremely low R-squared.
(g) Using the model from (e), obtain 95 % confidence intervals for the coefficient(s).
confint(seats2, level = .95)
## 2.5 % 97.5 %
## (Intercept) 11.79032020 14.27126531
## Price -0.06475984 -0.04419543
## USYes 0.69151957 1.70776632
(h) Is there evidence of outliers or high leverage observations in the model from (e)?
'Other code I found online'
## [1] "Other code I found online"
round(((2 + 1) / nrow(Carseats)), 10) == round(mean(hatvalues(seats2)), 10)
## [1] TRUE
broom::augment(seats2) %>%
select(.hat, .std.resid) %>%
ggplot(aes(x = .hat, y = .std.resid)) +
geom_point() +
geom_hline(yintercept = -2, col = "deepskyblue3", size = 1) +
geom_hline(yintercept = 2, col = "deepskyblue3", size = 1) +
geom_vline(xintercept = 3 / nrow(Carseats), col = "mediumseagreen", size = 1) +
theme_light() +
labs(x = "Leverage",
y = "Standardized Residual",
title = "Residuals vs Leverage")
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
As you can see, we have some problem values in the top right and bottom
right corner. However for such a big data set, we would expect around 10
problem observations.
12. This problem involves simple linear regression without an intercept. (a) Recall that the coefficient estimate βˆ for the linear regression of Y onto X without an intercept is given by (3.38). Under what circumstance is the coefficient estimate for the regression of X onto Y the same as the coefficient estimate for the regression of Y onto X?
I couldn’t get the latex to work for this problem.The estimates are the same if B(a)=(Sum(xy)/Sum(x^2)) and B(b) = (Sum(yx)/Sum(y^2)), where
yhat = B(a)x and xhat= B(b)y
(b) Generate an example in R with n = 100 observations in which the coefficient estimate for the regression of X onto Y is different from the coefficient estimate for the regression of Y onto X.
x <- rnorm(100)
y <- 10*x + rnorm(100)
data <- data.frame(x, y)
lm_a <- lm(y ~ x + 0)
lm_b <- lm(x ~ y + 0)
ggplot(data, aes(x, y)) +
geom_point(color="blue") +
geom_abline(intercept = 0, slope = coef(lm_a), size = 1, col = "black") +
geom_abline(intercept = 0, slope = 1 / coef(lm_b), size = 1, col = "green")
(c) Generate an example in R with n = 100 observations in which the coefficient estimate for the regression of X onto Y is the same as the coefficient estimate for the regression of Y onto X.
x <- rnorm(100)
y <- x
data <- data.frame(x, y)
lm_a <- lm(y ~ x + 0)
lm_b <- lm(x ~ y + 0)
ggplot(data, aes(x, y)) +
geom_point(color="blue") +
geom_abline(intercept = 0, slope = coef(lm_a), size = 1, col = "black") +
geom_abline(intercept = 0, slope = 1 / coef(lm_b), size = 1, col = "green")