Question 2

Carefully explain the differences between the KNN classifier and KNN regression methods.

The difference between KNN Classification and KNN Regression lies in the type of target variable being predicted and the method used to generate the prediction. While both techniques use the same underlying approach of calculating distances between observations to identify the k nearest neighbors, they differ in how the final output is determined.

KNN Classification is used when the response variable is categorical. After identifying the k nearest neighbors, the algorithm predicts the class of a new observation based on the majority class among those neighbors. In contrast, KNN Regression is used when the response variable is continuous and numerical. Rather than predicting a class, it estimates the output value by taking the average of the response values of the k nearest neighbors.

Question 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()

cor(Auto[1:8])
##                     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.

model <- lm(mpg ~ cylinders + displacement + horsepower + weight + acceleration + year +
            origin, data = Auto )
summary(model)
## 
## Call:
## lm(formula = mpg ~ cylinders + displacement + horsepower + weight + 
##     acceleration + year + origin, data = Auto)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -9.5903 -2.1565 -0.1169  1.8690 13.0604 
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -17.218435   4.644294  -3.707  0.00024 ***
## cylinders     -0.493376   0.323282  -1.526  0.12780    
## displacement   0.019896   0.007515   2.647  0.00844 ** 
## horsepower    -0.016951   0.013787  -1.230  0.21963    
## weight        -0.006474   0.000652  -9.929  < 2e-16 ***
## acceleration   0.080576   0.098845   0.815  0.41548    
## year           0.750773   0.050973  14.729  < 2e-16 ***
## origin         1.426141   0.278136   5.127 4.67e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3.328 on 384 degrees of freedom
## Multiple R-squared:  0.8215, Adjusted R-squared:  0.8182 
## F-statistic: 252.4 on 7 and 384 DF,  p-value: < 2.2e-16

For instance: i. Is there a relationship between the predictors and the response?

Based on the regression model summary for the Auto dataset, several variables appear to be significantly related to a vehicle’s miles per gallon mpg.

ii. Which predictors appear to have a statistically significant relationship to the response?

In particular, displacement, weight, year, and origin have statistically significant relationships with mpg.

iii. What does the coefficient for the year variable suggest?

Holding all other variables constant, a one-year increase in a vehicle’s model year is associated with an average increase of approximately 0.75 miles per gallon (mpg).

(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?

plot(model)

# Leverage values
min(hatvalues(model))
## [1] 0.005334609
# Leverage values
max(hatvalues(model))
## [1] 0.1899129

Based on the diagnostic plots, several observations appear to be potential outliers. The leverage values range from 0.0053 to 0.1899, and the maximum leverage exceeds the common cutoff value of 0.041 (2(p+1)/n). This suggests that one or more observations have unusual predictor values and may exert substantial influence on the regression model.

(e) Use the * and : symbols to fit linear regression models with interaction effects. Do any interactions appear to be statistically significant?

interaction_model <- lm(mpg ~ horsepower * weight + year * origin + displacement * weight, 
                        data = Auto )
summary(interaction_model)
## 
## Call:
## lm(formula = mpg ~ horsepower * weight + year * origin + displacement * 
##     weight, data = Auto)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -8.4474 -1.6780 -0.0525  1.4634 11.8047 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          1.841e+01  7.914e+00   2.326  0.02056 *  
## horsepower          -1.357e-01  4.204e-02  -3.229  0.00135 ** 
## weight              -1.094e-02  6.996e-04 -15.641  < 2e-16 ***
## year                 5.288e-01  1.021e-01   5.177 3.65e-07 ***
## origin              -1.091e+01  4.319e+00  -2.525  0.01198 *  
## displacement        -3.282e-02  1.798e-02  -1.825  0.06874 .  
## horsepower:weight    2.936e-05  1.216e-05   2.415  0.01622 *  
## year:origin          1.491e-01  5.528e-02   2.698  0.00729 ** 
## weight:displacement  1.102e-05  5.187e-06   2.125  0.03421 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.899 on 383 degrees of freedom
## Multiple R-squared:  0.8648, Adjusted R-squared:  0.862 
## F-statistic: 306.3 on 8 and 383 DF,  p-value: < 2.2e-16

The interaction terms horsepower:weight, year:origin, and weight:displacement are all statistically significant, with p-values less than 0.05.

interaction_model <- lm(mpg ~ horsepower:weight + year:origin + displacement:weight, 
                        data = Auto )
summary(interaction_model)
## 
## Call:
## lm(formula = mpg ~ horsepower:weight + year:origin + displacement:weight, 
##     data = Auto)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -12.4144  -3.0707  -0.3628   2.2426  14.6139 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)          2.728e+01  8.180e-01  33.354  < 2e-16 ***
## horsepower:weight   -1.815e-05  3.924e-06  -4.625 5.10e-06 ***
## year:origin          3.167e-02  4.479e-03   7.071 7.19e-12 ***
## weight:displacement -2.252e-06  1.744e-06  -1.291    0.197    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.447 on 388 degrees of freedom
## Multiple R-squared:  0.6779, Adjusted R-squared:  0.6754 
## F-statistic: 272.2 on 3 and 388 DF,  p-value: < 2.2e-16

A regression model containing only the interaction terms horsepower:weight, year:origin, and weight:displacement was fit to predict mpg. The interactions horsepower:weight (p=5.10×10 −6) and year:origin (p=7.19×10 −12) are statistically significant, indicating that the combined effects of these variables are associated with fuel efficiency. However, the interaction weight:displacement is not statistically significant (p=0.197), suggesting insufficient evidence that the combined effect of weight and displacement is related to mpg after accounting for the other interaction terms.

(f) Try a few different transformations of the variables, such as log(X), √X, X2. Comment on your findings.

fit_log <- lm(mpg ~ log(horsepower) + log(weight), data = Auto)
summary(fit_log)
## 
## Call:
## lm(formula = mpg ~ log(horsepower) + log(weight), data = Auto)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -10.6665  -2.4028  -0.3842   2.1558  15.3359 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      179.973      7.420   24.25  < 2e-16 ***
## log(horsepower)   -7.672      1.210   -6.34 6.36e-10 ***
## log(weight)      -15.244      1.478  -10.32  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3.993 on 389 degrees of freedom
## Multiple R-squared:  0.7396, Adjusted R-squared:  0.7382 
## F-statistic: 552.4 on 2 and 389 DF,  p-value: < 2.2e-16

A linear regression model was fit using the log-transformed predictors horsepower and weight. Both log(horsepower) and log(weight) were highly statistically significant predictors of mpg (p < 0.001), indicating that horsepower and vehicle weight have strong nonlinear relationships with fuel efficiency. The negative coefficients suggest that increases in horsepower and weight are associated with decreases in miles per gallon.

fit_sqrt <- lm(mpg ~ sqrt(horsepower) + sqrt(weight), data = Auto)
summary(fit_sqrt)
## 
## Call:
## lm(formula = mpg ~ sqrt(horsepower) + sqrt(weight), data = Auto)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -10.9211  -2.6240  -0.3587   2.2098  15.7776 
## 
## Coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      68.49726    1.49097  45.941  < 2e-16 ***
## sqrt(horsepower) -1.27083    0.23678  -5.367 1.38e-07 ***
## sqrt(weight)     -0.59713    0.05522 -10.813  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.096 on 389 degrees of freedom
## Multiple R-squared:  0.726,  Adjusted R-squared:  0.7246 
## F-statistic: 515.5 on 2 and 389 DF,  p-value: < 2.2e-16

A linear regression model was fit using sqrt(horsepower) and sqrt(weight) as predictors of mpg. Both transformed variables were highly statistically significant (p < 0.001), indicating that horsepower and vehicle weight remain important predictors of fuel efficiency after transformation. The negative coefficients suggest that increases in horsepower and weight are associated with lower miles per gallon.

fit_quad <- lm(mpg ~ horsepower + I(horsepower^2), data = Auto)
summary(fit_quad)
## 
## Call:
## lm(formula = mpg ~ horsepower + I(horsepower^2), data = Auto)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -14.7135  -2.5943  -0.0859   2.2868  15.8961 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)     56.9000997  1.8004268   31.60   <2e-16 ***
## horsepower      -0.4661896  0.0311246  -14.98   <2e-16 ***
## I(horsepower^2)  0.0012305  0.0001221   10.08   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.374 on 389 degrees of freedom
## Multiple R-squared:  0.6876, Adjusted R-squared:  0.686 
## F-statistic:   428 on 2 and 389 DF,  p-value: < 2.2e-16

A quadratic regression model was fit using horsepower and horsepower² as predictors of mpg. Both the linear term (horsepower) and the quadratic term (horsepower²) were highly statistically significant (p < 0.001). The significance of the squared term provides strong evidence that the relationship between horsepower and fuel efficiency is nonlinear rather than purely linear.

The model explains approximately 68.8% of the variation in mpg (\(R^2 = 0.6876\)), with an adjusted \(R^2\) of 0.6860. Although the quadratic term is statistically significant, the model explains less variation than the logarithmic transformation model (\(R^2 = 0.7396\)) and substantially less than the interaction model (\(R^2 = 0.8648\)). The residual standard error of 4.374 is also larger than that of the other transformed models, indicating a poorer overall fit.

Question 10

This question should be answered using the Carseats data set.

library(ISLR)
attach(Carseats)

(a) Fit a multiple regression model to predict Sales using Price, Urban, and US.

fit <- lm(Sales ~ Price + Urban + US, data = Carseats)
summary(fit)
## 
## 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!

From the summary from the linear regression model Price and US are significant predictors of Sales. While holding all other variable fixed, every $1.00 increase in Price, sales decrease by 54 units sold. Additionally, Sales inside the US sale 1.2 thousand more units than stores outside the US.

However, the model \(R^2\) = 0.2393 means that 24% of the variation in Sales is explained by the predictors Price, Urban, and US, suggesting that other factors not included in the model also influence sales.

(c) Write out the model in equation form, being careful to handle the qualitative variables properly.

\(Sales = 13.043469 - 0.054459(\text{Price}) - 0.021916(\text{UrbanYes})+ 1.200573(\text{USYes})\)

(d) For which of the predictors can you reject the null hypothesis H0 : βj = 0?

We reject the null hypothesis for Price and US

(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.

fit <- lm(Sales ~ Price + US, data = Carseats)
summary(fit)
## 
## 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?

Models in (A) and (E) only explain on 23% of the variance in Sales.

(g) Using the model from (e), obtain 95 % confidence intervals for the coefficient(s).

confint(fit)
##                   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)?

plot(fit)

Based of the above graphs there are several outliers. Using the common cutoff of \(\frac{(p+1)}{n}\) or \(\frac{(2+1)}{400}=0.0075\), where p=2 predictors and n=400 observations, several observations exceed the threshold for high leverage.

par(mfrow=c(2,2))
summary(influence.measures(fit))
## Potentially influential observations of
##   lm(formula = Sales ~ Price + US, data = Carseats) :
## 
##     dfb.1_ dfb.Pric dfb.USYs dffit   cov.r   cook.d hat    
## 26   0.24  -0.18    -0.17     0.28_*  0.97_*  0.03   0.01  
## 29  -0.10   0.10    -0.10    -0.18    0.97_*  0.01   0.01  
## 43  -0.11   0.10     0.03    -0.11    1.05_*  0.00   0.04_*
## 50  -0.10   0.17    -0.17     0.26_*  0.98    0.02   0.01  
## 51  -0.05   0.05    -0.11    -0.18    0.95_*  0.01   0.00  
## 58  -0.05  -0.02     0.16    -0.20    0.97_*  0.01   0.01  
## 69  -0.09   0.10     0.09     0.19    0.96_*  0.01   0.01  
## 126 -0.07   0.06     0.03    -0.07    1.03_*  0.00   0.03_*
## 160  0.00   0.00     0.00     0.01    1.02_*  0.00   0.02  
## 166  0.21  -0.23    -0.04    -0.24    1.02    0.02   0.03_*
## 172  0.06  -0.07     0.02     0.08    1.03_*  0.00   0.02  
## 175  0.14  -0.19     0.09    -0.21    1.03_*  0.02   0.03_*
## 210 -0.14   0.15    -0.10    -0.22    0.97_*  0.02   0.01  
## 270 -0.03   0.05    -0.03     0.06    1.03_*  0.00   0.02  
## 298 -0.06   0.06    -0.09    -0.15    0.97_*  0.01   0.00  
## 314 -0.05   0.04     0.02    -0.05    1.03_*  0.00   0.02_*
## 353 -0.02   0.03     0.09     0.15    0.97_*  0.01   0.00  
## 357  0.02  -0.02     0.02    -0.03    1.03_*  0.00   0.02  
## 368  0.26  -0.23    -0.11     0.27_*  1.01    0.02   0.02_*
## 377  0.14  -0.15     0.12     0.24    0.95_*  0.02   0.01  
## 384  0.00   0.00     0.00     0.00    1.02_*  0.00   0.02  
## 387 -0.03   0.04    -0.03     0.05    1.02_*  0.00   0.02  
## 396 -0.05   0.05     0.08     0.14    0.98_*  0.01   0.00
outlying_obs <- c(26, 29, 43, 50, 51, 58, 69, 126, 160, 166, 172, 175, 210, 270, 298, 314, 353, 357, 368, 377, 384, 387, 396)

model_removed <- lm(Sales ~ Price + US, data = Carseats[-outlying_obs, ])

summary(model_removed)
## 
## Call:
## lm(formula = Sales ~ Price + US, data = Carseats[-outlying_obs, 
##     ])
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -5.263 -1.605 -0.039  1.590  5.428 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 12.925232   0.665259  19.429  < 2e-16 ***
## Price       -0.053973   0.005511  -9.794  < 2e-16 ***
## USYes        1.255018   0.248856   5.043 7.15e-07 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.29 on 374 degrees of freedom
## Multiple R-squared:  0.2387, Adjusted R-squared:  0.2347 
## F-statistic: 58.64 on 2 and 374 DF,  p-value: < 2.2e-16

Removing the potentially influential observations resulted in only minor changes to the coefficient estimates and model fit statistics. The coefficients for Price and US remained highly significant and retained similar magnitudes. The model’s \(R^2\) value remained virtually unchanged (0.2393 versus 0.2387), while the residual standard error decreased slightly from 2.469 to 2.290. Therefore, there is little evidence that the identified observations substantially influenced the overall conclusions of the regression model.

Question 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?

The coefficient estimates are the same when the sum of squares of X equals the sum of squares of 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.

set.seed(123)

n <- 100

# Generate X
X <- rnorm(n, mean = 0, sd = 1)

# Generate Y with a different scale
Y <- 2 * X + rnorm(n, mean = 0, sd = 1)

# Regression of Y onto X (no intercept)
fit_yx <- lm(Y ~ X - 1)

# Regression of X onto Y (no intercept)
fit_xy <- lm(X ~ Y - 1)

coef(fit_yx)
##        X 
## 1.936372
coef(fit_xy)
##         Y 
## 0.3975655

(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.

set.seed(123)

n <- 100

# Generate X
X <- rnorm(n, mean = 0, sd = 1)

# Set Y equal to X
Y <- X

# Regression of Y onto X (no intercept)
fit_yx <- lm(Y ~ X + 0)

# Regression of X onto Y (no intercept)
fit_xy <- lm(X ~ Y + 0)

coef(fit_yx)
## X 
## 1
coef(fit_xy)
## Y 
## 1