Default Dataset (Validation Set Approach)Default Dataset (Bootstrap Standard Errors)Weekly Dataset (Leave-One-Out Cross-Validation)Boston Dataset - Bootstrapping (Standard Errors, Confidence Intervals)medv Population Mean - \(\hat{\mu}\)medv Population Median - \(\hat{\mu}_{med}\)medv Population 10th Percentile - \(\hat{\mu}_{0.1}\)NOTE: There are no official solutions for these questions. These are my solutions and could be incorrect. If you spot any mistakes/inconsistencies, please contact me on Liam95morgan@gmail.com, or via LinkedIn.
Some of the figures in this presentation are taken from “An Introduction to Statistical Learning, with applications in R” (Springer, 2013) with permission from the authors: G. James, D. Witten, T. Hastie and R. Tibshirani
library(tidyverse)
library(ISLR)
library(caret)
library(boot)
library(MASS) # Boston data
theme_set(theme_light())
Q: Using basic statistical properties of the variance, as well as singlevariable calculus, derive (5.6). In other words, prove that \(\alpha\) given by (5.6) does indeed minimize \(Var(\alpha X + (1 - \alpha)Y)\).
A:
Recall the topic (minimizing the variance/risk of a two-asset financial portfolio), because this is a weird question with no context:
Suppose that we wish to invest a fixed sum of money in two financial assets that yield returns of \(X\) and \(Y\), respectively, where \(X\) and \(Y\) are random quantities. We will invest a fraction \(\alpha\) of our money in \(X\), and will invest the remaining \(1 - \alpha\) in \(Y\) . Since there is variability associated with the returns on these two assets, we wish to choose \(\alpha\) to minimize the total risk, or variance, of our investment. In other words, we want to minimize \(Var(\alpha X + (1 - \alpha)Y)\).
Essentially, we want to show:
\[\underset{\alpha}{\operatorname{argmin}}(Var(\alpha X + (1 - \alpha)Y)) = \frac{\sigma_Y^2 - \sigma_{XY}}{\sigma_X^2 + \sigma_Y^2 - 2\sigma_{XY}} = \frac{Var(Y) - Cov(X, Y)}{Var(X) + Var(Y) - 2Cov(X, Y)} \quad \text{(5.6)}\].
Let \(Var(\alpha X + (1 - \alpha)Y) = f(\alpha)\) for ease of notation, and expand using the variance property: \[Var(aX + bY) = a^2Var(X) + b^2Var(Y) + 2abCov(X,Y)\]
We get:
\[\begin{align*} f(\alpha) & = Var(\alpha X + (1 - \alpha)Y) \\ & = \alpha^2Var(X) + (1 - \alpha)^2Var(Y) + 2\alpha(1 - \alpha)Cov(X, Y)\\ & = \alpha^2Var(X) + (\alpha^2 - 2\alpha + 1)Var(Y) + (2\alpha - 2\alpha^2)Cov(X, Y) \end{align*}\]
Finding critical points by solving for \(f'(\alpha) = 0\):
\[\begin{align*} & f'(\alpha) = 2\alpha Var(X) + (2\alpha - 2)Var(Y) + (2 - 4\alpha)Cov(X, Y) = 0 \\ \implies & 2\alpha Var(X) + 2\alpha Var(Y) - 4\alpha Cov(X, Y) = 2Var(Y) - 2Cov(X, Y) \\ \implies & \alpha(Var(X) + Var(Y) - 2Cov(X, Y)) = Var(Y) - Cov(X, Y) \\ \implies & \alpha = \frac{Var(Y) - Cov(X, Y)}{Var(X) + Var(Y) - 2Cov(X, Y)} \quad \text{(5.6)} \end{align*}\]
As required.
We will now derive the probability that a given observation is part of a bootstrap sample. Suppose that we obtain a bootstrap sample from a set of \(n\) observations.
Q: What is the probability that the first bootstrap observation is not the \(j\)th observation from the original sample? Justify your answer.
A:
There are \(n\) observations to sample from.
Since there is an equal probability of any of the \(n\) observations being selected, the probability that the \(j\)th observation is selected as the first bootstrap observation is \(\frac{1}{n}\).
Therefore the probability that the \(j\)th observation is not the first bootstrap observation is \(1 - \frac{1}{n}\).
Q: What is the probability that the second bootstrap observation is not the \(j\)th observation from the original sample?
A:
Since bootstrap sampling is sampling with replacement, this is the same as the part a) - each of the \(n\) observations has probability \(\frac{1}{n}\) of being selected, so the probability is still \(1 - \frac{1}{n}\).
Q: Argue that the probability that the \(j\)th observation is not in the bootstrap sample is \((1 - \frac{1}{n})^n\).
A:
We are sampling from a set of \(n\) observations. We sample \(n\) times, randomly and with replacement, and want to know the probability that the observation indexed by \(j\) is not in the final bootstrap sample, which we denote by \(S = \{s_1, s_2, \dots, s_n\}\).
I have already argued intuitively that \(P(s_1 \ne j) = P(s_2 \ne j) = 1 - \frac{1}{n}\). Using exactly the same logic, we can say:
\[P(s_i \ne j) = 1 - \frac{1}{n} \quad (\forall i \in \{1, 2, \dots, n\})\]
Because the samples are independent, we can multiply these probabilities together (using the multiplication rule for independent events), and say that the probability that the \(j\)th observation is in none of these independent samples \(s_1, s_2, \dots, s_n\) is:
\[\begin{align*} & P(s_1 \ne j) \cap P(s_2 \ne j) \cap \dots \cap P(s_n \ne j) \\ = & \prod_{i = 1}^{n} P(s_i \ne j) \\ = & \prod_{i = 1}^{n} \left( 1 - \frac{1}{n} \right) \\ = & \left( 1 - \frac{1}{n} \right)^n \end{align*}\]
Q: When \(n\) = 5, what is the probability that the \(j\)th observation is in the bootstrap sample?
A:
Since the formula above is for not being in the set, we instead apply \(1 - (1 - \frac{1}{n})^n\):
\(1 - (1 - \frac{1}{5})^5\)
round(1 - (1 - 1/5)^5, 3)## [1] 0.672
Q: When \(n\) = 100, what is the probability that the \(j\)th observation is in the bootstrap sample?
A:
As before:
\(1 - (1 - \frac{1}{100})^{100}\)
round(1 - (1 - 1/100)^100, 3)## [1] 0.634
Q: When \(n\) = 10,000, what is the probability that the \(j\)th observation is in the bootstrap sample?
A:
Again:
\(1 - (1 - \frac{1}{10000})^{10000}\)
round(1 - (1 - 1/10000)^10000, 3)## [1] 0.632
Q: Create a plot that displays, for each integer value of \(n\) from 1 to 100,000, the probability that the \(j\)th observation is in the bootstrap sample. Comment on what you observe
A:
I’ve restricted the x-axis to limits to \([0, 100]\), because as you can imagine, the graph is basically a straight line when viewed over the range \([0, 100,000]\).
n <- 1:10000
data.frame(n, prob_j_included = 1 - (1 - 1/n)^n) %>%
ggplot(aes(x = n, y = prob_j_included)) +
geom_line(size = 1) +
geom_hline(aes(yintercept = 1 - 1/exp(1), col = "1 - 1/e")) +
scale_x_continuous(limits = c(0, 100)) +
scale_y_continuous(limits = c(0, 1)) +
scale_color_manual(values = c("green")) +
labs(title = "Bootstrap Sampling - Probability obs.j included", y = "Probability", col = "")We are seeing a visual representation of \(\lim_{n \to \infty} 1 - (1 - \frac{1}{n})^{n} = 1 - \frac{1}{e} \approx 0.632\), which is the reason why this is sometimes called the .632 rule in bootstrapping.
Q: We will now investigate numerically the probability that a bootstrap sample of size \(n\) = 100 contains the \(j\)th observation. Here \(j\) = 4. We repeatedly create bootstrap samples, and each time we record whether or not the fourth observation is contained in the bootstrap sample.
store=rep(NA, 10000)
for(i in 1:10000) {
store[i]=sum(sample (1:100, rep=TRUE)==4) > 0
}
mean(store)
Comment on the results obtained.
A:
To relate this to previous questions, we are basically creating 10,000 separate bootstrap samples, sampling from the set of integers from 1 to 100: \(\{1, 2, \dots, 100 \}\).
In the sample() function there is a size argument, and since we aren’t setting this, the default is to sample n = 100 items from the vector x = 1:100. replace = TRUE means that this sampling occurs with replacement. This occurs for each i in the loop.
sum(sample(1:100, rep=TRUE) == 4) > 0 therefore checks whether any of these 100 items were the number \(4\) (this is our \(j\) in previous questions), returning TRUE if \(4\) was within the sample, else FALSE.
Assigning this to store[i] then stores this result in the ith position of the vector store. This happens 10,000 times (one for each bootstrap sample), so the resulting store vector is logical with 10,000 entries.
At the end the mean is calculated, which for a logical vector will give the proportion of the 10,000 entries in store that had value TRUE = 1.
# R 3.6.0 changed sampling method:
# https://stackoverflow.com/questions/56268011/sample-function-gives-different-result-in-console-and-in-knitted-document-when-s
# since i re-ran this later (01/08/2020), had to set set sample.kind = "Rounding" to reconcile with previous results
set.seed(111, sample.kind = "Rounding")
store = rep(NA, 10000)
for(i in 1:10000) {
store[i] = sum(sample(1:100, rep=TRUE) == 4) > 0
}
round(mean(store), 3)## [1] 0.635
In short: We create 10,000 bootstrap samples from \(\{1, 2, \dots, 100 \}\), then calculate what proportion of them contained \(4\).
If the maths in the previous questions is correct, we would expect that if we perform many many bootstrap samples, \(\approx\) 63.2% of them will contain the number \(4\).
The simulation shows that this seems to hold true, with 63.5% containing \(4\).
We will now derive the probability that a given observation is part of a bootstrap sample. Suppose that we obtain a bootstrap sample from a set of \(n\) observations.
Q: Explain how \(k\)-fold cross-validation is implemented.
A:
The data is segmented into \(k\) distinct, (usually) equal-sized ‘folds’. A model is trained on \(k-1\) of the folds and tested on the remaining fold. This process is repeated \(k\) times, such that each of the \(k\) folds acts as the test data once. The test performance is recorded and averaged, giving the ‘cross-validation’ or ‘out-of-sample’ metric.
The metric being used is not necessarily restricted to MSE and Accuracy for regression/classification problems, as the book seems to imply (to me anyway, p.181 & p.184). In fact any metric can be used (RMSE, MAE, AUROC, AUPRC, …) if it can be obtained on test data from a fitted model.
Q: What are the advantages and disadvantages of \(k\)-fold cross-validation relative to:
i. The validation set approach?
ii. LOOCV?
A:
i. \(k\)-Fold CV vs Validation Set
Advantages:
Disadvantages:
ii. \(k\)-Fold CV vs LOOCV
Advantages:
Disadvantages:
For example, when finding the leave-one-out cross-validation error (\(CV_{(n)}\)) in least squares regression, the following holds:
\[\begin{align*} & CV_{(n)} = \frac{1}{n} \sum_{i = 1}^{n} \left( \frac{y_i - \hat{y_i}}{1 - h_i} \right)^2 \\ where: \quad & H = X(X^TX)^{-1}X^T && \text{(} X \text{ is the design matrix)} \\ \quad & h_i = [H]_{ii} && \text{(diagonal elements of the hat matrix } H \text{, i.e. leverages)} \\ \end{align*}\]
I modified the formula given in the book so that it applies for multiple regression too. In simple linear regression (\(p\) = 1), the leverages simplify to \(h_i = \frac{1}{n} + \frac{(x_i - \bar{x})^2}{\sum_{j = 1}^{n} (x_j - \bar{x})^2}\).
By using the leverages \(h_i\), here the LOOCV statistic uses about the same computational power required to fit a single model, which is much better than \(n\) models!
Q: Suppose that we use some statistical learning method to make a prediction for the response \(Y\) for a particular value of the predictor \(X\). Carefully describe how we might estimate the standard deviation of our prediction.
A:
The bootstrap approach would be appropriate here. If the original data contains \(n\) observations, we create \(B\) bootstrap samples from the data (sampling \(n\) observations with replacement, repeated \(B\) times). On each of these datasets, we would then train a supervised learning method and use it to make our estimate for the ‘particular value of \(X\)’. Once we have these \(B\) estimates, we can calculate the standard deviation of them, as seen in (5.8). Doing so provides the bootstrap estimate for the standard error of our estimate.
Default Dataset (Validation Set Approach)In Chapter 4, we used logistic regression to predict the probability of default using income and balance on the Default data set. We will now estimate the test error of this logistic regression model using the validation set approach. Do not forget to set a random seed before beginning your analysis.
glimpse(Default)## Rows: 10,000
## Columns: 4
## $ default <fct> No, No, No, No, No, No, No, No, No, No, No, No, No, No, No,...
## $ student <fct> No, Yes, No, No, No, Yes, No, Yes, No, No, Yes, Yes, No, No...
## $ balance <dbl> 729.5265, 817.1804, 1073.5492, 529.2506, 785.6559, 919.5885...
## $ income <dbl> 44361.625, 12106.135, 31767.139, 35704.494, 38463.496, 7491...
default with income & balance - Logistic RegressionQ: Fit a logistic regression model that uses income and balance to predict default.
A:
log_def <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(log_def)##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = Default)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4725 -0.1444 -0.0574 -0.0211 3.7245
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.154e+01 4.348e-01 -26.545 < 2e-16 ***
## income 2.081e-05 4.985e-06 4.174 2.99e-05 ***
## balance 5.647e-03 2.274e-04 24.836 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2920.6 on 9999 degrees of freedom
## Residual deviance: 1579.0 on 9997 degrees of freedom
## AIC: 1585
##
## Number of Fisher Scoring iterations: 8
test ErrorUsing the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps:
train/test SplitQ: Split the sample set into a training set and a validation set.
A:
I chose a 70/30 split for train/test respectively:
set.seed(123, sample.kind = "Rounding")
index <- createDataPartition(y = Default$default, p = 0.7, list = F)
train <- Default[index, ]
test <- Default[-index, ]
nrow(train) / nrow(Default)## [1] 0.7001
train - Fitting a Logistic Regression ModelQ: Fit a multiple logistic regression model using only the training observations.
A:
I continue to only use income and balance in the models.
log_def_2 <- glm(default ~ income + balance, data = train, family = "binomial")
summary(log_def_2)##
## Call:
## glm(formula = default ~ income + balance, family = "binomial",
## data = train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.4500 -0.1450 -0.0597 -0.0222 3.6961
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.141e+01 5.099e-01 -22.379 < 2e-16 ***
## income 2.256e-05 5.898e-06 3.825 0.000131 ***
## balance 5.531e-03 2.651e-04 20.866 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2050.6 on 7000 degrees of freedom
## Residual deviance: 1119.2 on 6998 degrees of freedom
## AIC: 1125.2
##
## Number of Fisher Scoring iterations: 8
test PredictionsQ: Obtain a prediction of default status for each individual in the validation set by computing the posterior probability of default for that individual, and classifying the individual to the default category if the posterior probability is greater than 0.5.
A:
I store the predictions in test_pred, showing the first 10 entries:
test_pred <- factor(ifelse(predict(log_def_2, newdata = test, type = "response") > 0.5, "Yes", "No"))
test_pred[1:10]## 2 3 4 12 13 14 15 17 18 20
## No No No No No No No No No No
## Levels: No Yes
test ErrorQ: Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
A:
round(mean(test$default != test_pred), 5)## [1] 0.02601
train/test SplitsQ: Repeat the process in (b) three times, using three different splits of the observations into a training set and a validation set. Comment on the results obtained.
A:
Using a loop I perform three more train/test splits, fit logistic regression models on train, then store the test error in the vector log_def_errors. The results are seen below:
log_def_errors <- c()
log_def_errors[1] <- mean(test$default != test_pred)
set.seed(42, sample.kind = "Rounding")
for (i in 2:4) {
index <- createDataPartition(y = Default$default, p = 0.7, list = F)
train <- Default[index, ]
test <- Default[-index, ]
log_def <- glm(default ~ income + balance, data = train, family = "binomial")
test_pred <- factor(ifelse(predict(log_def, newdata = test, type = "response") > 0.5, "Yes", "No"))
log_def_errors[i] <- mean(test$default != test_pred)
}
round(log_def_errors, 5)## [1] 0.02601 0.02534 0.02601 0.02534
There is some variation, as we would expect with the validation set approach and cross-validation. The average test error is 0.02568.
student Improve test Performance?Q: Now consider a logistic regression model that predicts the probability of default using income, balance, and a dummy variable for student. Estimate the test error for this model using the validation set approach. Comment on whether or not including a dummy variable for student leads to a reduction in the test error rate.
A:
set.seed(43, sample.kind = "Rounding")
index <- createDataPartition(y = Default$default, p = 0.7, list = F)
train <- Default[index, ]
test <- Default[-index, ]
log_def <- glm(default ~ ., data = train, family = "binomial")
summary(log_def)##
## Call:
## glm(formula = default ~ ., family = "binomial", data = train)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.1457 -0.1395 -0.0542 -0.0198 3.6969
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.100e+01 5.957e-01 -18.473 <2e-16 ***
## studentYes -6.353e-01 2.825e-01 -2.249 0.0245 *
## balance 5.780e-03 2.789e-04 20.721 <2e-16 ***
## income 4.235e-06 9.788e-06 0.433 0.6653
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 2050.6 on 7000 degrees of freedom
## Residual deviance: 1093.3 on 6997 degrees of freedom
## AIC: 1101.3
##
## Number of Fisher Scoring iterations: 8
test_pred <- factor(ifelse(predict(log_def, newdata = test, type = "response") > 0.5, "Yes", "No"))The studentYes variable is significant and has caused the income variable to no longer be significant (correlated features). However, here we are really more concerned with the models out-of-sample performance. The test error is below:
round(mean(test$default != test_pred), 5)## [1] 0.02634
It appears that the test error for this model is larger than the test error for the smaller model (larger than all 4 of them, in fact), so including a dummy variable for student does not reduce the test error rate.
Default Dataset (Bootstrap Standard Errors)We continue to consider the use of a logistic regression model to predict the probability of default using income and balance on the Default data set. In particular, we will now compute estimates for the standard errors of the income and balance logistic regression coefficients in two different ways:
glm() functionDo not forget to set a random seed before beginning your analysis.
Q: Using the summary() and glm() functions, determine the estimated standard errors for the coefficients associated with income and balance in a multiple logistic regression model that uses both predictors.
A:
I extract the estimated standard errors of the coefficients from the model object summary:
log_def <- glm(default ~ income + balance, data = Default, family = "binomial")
summary(log_def)$coefficients[, 2]## (Intercept) income balance
## 4.347564e-01 4.985167e-06 2.273731e-04
boot.fn() - Estimating Logistic CoefficientsQ: Write a function, boot.fn(), that takes as input the Default data set as well as an index of the observations, and that outputs the coefficient estimates for income and balance in the multiple logistic regression model.
A:
I create the function boot.fn(), and test it on the Default data. If the index argument is not provided, its default function is to estimate the coefficients for all of the data provided.
boot.fn <- function(data, index = 1:nrow(data)) {
coef(glm(default ~ income + balance, data = data, subset = index, family = "binomial"))[-1]
}
boot.fn(Default)## income balance
## 2.080898e-05 5.647103e-03
boot.fn() & boot::boot() - Bootstrap Estimate of Coefficient SE’sQ: Use the boot() function together with your boot.fn() function to estimate the standard errors of the logistic regression coefficients for income and balance.
A:
I complete 1,000 bootstrap samples just to illustrate the function working, although in practice we would want to use as many as is practical.
set.seed(101, sample.kind = "Rounding")
(boot_results <- boot(data = Default, statistic = boot.fn, R = 1000))##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Default, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 2.080898e-05 9.797648e-08 4.710812e-06
## t2* 5.647103e-03 1.345215e-05 2.293757e-04
I create a histogram of the bootstrap parameter estimates:
as.data.frame(boot_results$t) %>%
rename(income = V1, balance = V2) %>%
gather(key = "variable", value = "estimate") %>%
ggplot(aes(x = estimate, fill = factor(variable))) +
geom_histogram(bins = 20) +
facet_wrap(~ variable, scales = "free_x") +
labs(title = "1,000 Bootstrap Parameter Estimates - 'balance' & 'income'",
subtitle = paste0("SE(balance) = ", formatC(sd(boot_results$t[ ,2]), format = "e", digits = 6),
", SE(income) = ", formatC(sd(boot_results$t[ ,1]), format = "e", digits = 6)),
x = "Parameter Estimate",
y = "Count") +
theme(legend.position = "none")
Q: Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
A:
While the boot() function provides the bootstrap estimate for the standard errors, we can also calculate them ourselves by utilizing equation (5.8) and calculating the standard deviation of these bootstrap estimates.
boot() Method:
sapply(data.frame(income = boot_results$t[ ,1], balance = boot_results$t[ ,2]), sd)## income balance
## 4.710812e-06 2.293757e-04
glm() Method:
summary(log_def)$coefficients[2:3, 2]## income balance
## 4.985167e-06 2.273731e-04
We can see that the standard error estimates for income are equal to 6dp. and the estimates for balance are equal to 5dp. This could be an indication that the assumptions of the logistic SE estimates are well-satisfied.
Weekly Dataset (Leave-One-Out Cross-Validation)In Sections 5.3.2 and 5.3.3, we saw that the cv.glm() function can be used in order to compute the LOOCV test error estimate. Alternatively, one could compute those quantities using just the glm() and predict.glm() functions, and a for loop. You will now take this approach in order to compute the LOOCV error for a simple logistic regression model on the Weekly data set. Recall that in the context of classification problems, the LOOCV error is given in (5.4).
glimpse(Weekly)## Rows: 1,089
## Columns: 9
## $ Year <dbl> 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 1990, 199...
## $ Lag1 <dbl> 0.816, -0.270, -2.576, 3.514, 0.712, 1.178, -1.372, 0.807...
## $ Lag2 <dbl> 1.572, 0.816, -0.270, -2.576, 3.514, 0.712, 1.178, -1.372...
## $ Lag3 <dbl> -3.936, 1.572, 0.816, -0.270, -2.576, 3.514, 0.712, 1.178...
## $ Lag4 <dbl> -0.229, -3.936, 1.572, 0.816, -0.270, -2.576, 3.514, 0.71...
## $ Lag5 <dbl> -3.484, -0.229, -3.936, 1.572, 0.816, -0.270, -2.576, 3.5...
## $ Volume <dbl> 0.1549760, 0.1485740, 0.1598375, 0.1616300, 0.1537280, 0....
## $ Today <dbl> -0.270, -2.576, 3.514, 0.712, 1.178, -1.372, 0.807, 0.041...
## $ Direction <fct> Down, Down, Up, Up, Up, Down, Up, Up, Up, Down, Down, Up,...
Direction with Lag1 & Lag2 - Logistic RegressionQ: Fit a logistic regression model that predicts Direction using Lag1 and Lag2.
A:
log_dir <- glm(Direction ~ Lag1 + Lag2, data = Weekly, family = "binomial")
summary(log_dir)##
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.623 -1.261 1.001 1.083 1.506
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.22122 0.06147 3.599 0.000319 ***
## Lag1 -0.03872 0.02622 -1.477 0.139672
## Lag2 0.06025 0.02655 2.270 0.023232 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1496.2 on 1088 degrees of freedom
## Residual deviance: 1488.2 on 1086 degrees of freedom
## AIC: 1494.2
##
## Number of Fisher Scoring iterations: 4
Q: Fit a logistic regression model that predicts Direction using Lag1 and Lag2 using all but the first observation.
A:
We can use the subset argument here, or just subset the data directly:
log_dir_2 <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-1, ], family = "binomial")
summary(log_dir_2)##
## Call:
## glm(formula = Direction ~ Lag1 + Lag2, family = "binomial", data = Weekly[-1,
## ])
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.6258 -1.2617 0.9999 1.0819 1.5071
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.22324 0.06150 3.630 0.000283 ***
## Lag1 -0.03843 0.02622 -1.466 0.142683
## Lag2 0.06085 0.02656 2.291 0.021971 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 1494.6 on 1087 degrees of freedom
## Residual deviance: 1486.5 on 1085 degrees of freedom
## AIC: 1492.5
##
## Number of Fisher Scoring iterations: 4
Q: Use the model from (b) to predict the direction of the first observation. You can do this by predicting that the first observation will go up if \(P(Direction = Up | Lag1, Lag2) > 0.5\). Was this observation correctly classified?
A:
The prediction for this first observation:
ifelse(predict(log_dir_2, newdata = Weekly[1, ], type = "response") > 0.5, "Up", "Down")## 1
## "Up"
The actual Direction:
as.character(Weekly[1, "Direction"])## [1] "Down"
Therefore the observation was not correctly classified.
Q: Write a for loop from i = 1 to i = \(n\), where \(n\) is the number of observations in the data set, that performs each of the following steps:
i. Fit a logistic regression model using all but the ith observation to predict Direction using Lag1 and Lag2.
ii. Compute the posterior probability of the market moving up for the ith observation.
iii. Use the posterior probability for the ith observation in order to predict whether or not the market moves up.
iv. Determine whether or not an error was made in predicting the direction for the ith observation. If an error was made, then indicate this as a 1, and otherwise indicate it as a 0.
A:
The loop is written below. I store the indicators for a false/correct prediction in the error vector, of which I show the first 10 entries:
error <- c()
for (i in 1:nrow(Weekly)) {
log_dir <- glm(Direction ~ Lag1 + Lag2, data = Weekly[-i, ], family = "binomial") # i.
prediction <- ifelse(predict(log_dir, newdata = Weekly[i, ], type = "response") > 0.5, "Up", "Down") # ii. & iii.
error[i] <- as.numeric(prediction != Weekly[i, "Direction"]) # iv.
}
error[1:10]## [1] 1 1 0 1 0 1 0 0 0 1
Q: Take the average of the \(n\) numbers obtained in (d) iv. in order to obtain the LOOCV estimate for the test error. Comment on the results.
A:
mean(error)## [1] 0.4499541
The LOOCV estimate for the test error is \(\approx\) 0.45. Looking at the split of Direction between Up and Down:
prop.table(table(Weekly$Direction))##
## Down Up
## 0.4444444 0.5555556
We can see that a classifier that predicted that the Direction of the S&P 500 will go Up every week between 1990 and 2010 would have achieved an error of 0.444, so if the LOOCV estimate is anything to go by, our classifier isn’t much good.
We will now perform cross-validation on a simulated data set.
Q: Generate a simulated data set as follows:
set.seed(1)
x = rnorm(100)
y = x - 2*x^2 + rnorm (100)
In this data set, what is \(n\) and what is \(p\)? Write out the model used to generate the data in equation form.
A:
We have \(n\) = 100 and \(p\) = 2.
The model used to generate the data is:
\[Y = X - 2X^2 + \epsilon \\ \epsilon \sim \mathcal{N}(0, 1)\]
Q: Create a scatterplot of X against Y . Comment on what you find.
A:
We have the underlying relationship:
\[f(X) = X - 2X^2 \\ \implies f(X) = X (1 - 2X) \\ \implies f(X) = 0 \iff X \in \{0, 0.5\}\]
Looking for critical points:
\[f(X) = X - 2X^2 \\ \implies f'(X) = 1 - 4X \\ \implies f'(X) = 0 \iff X = 0.25\]
And we have \(f''(0.25) = -4 < 0\), so \(0.25\) is a maximum.
This means that, since \(\epsilon \sim \mathcal{N}(0, 1)\) is centered at \(0\), we should expect the data to show a quadratic relationship between \(X\) and \(Y\), with a maximum at \(\approx X = 0.25\), and crossing the x-axis at \(\approx X = 0\) and \(X = 0.5\).
set.seed(1, sample.kind = "Rounding")
x <- rnorm(100)
y <- x - 2*x^2 + rnorm(100)
ggplot(mapping = aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", formula = "y ~ x + I(x^2)") +
geom_hline(yintercept = 0, col = "grey55") +
geom_vline(xintercept = 0, col = "grey55")I have fit a least squares linear model (with a quadratic term for \(X\)) to the data, and we can see that the fitted model fits the data (and what we would expect from the underlying relationship) very well.
Q: Set a random seed, and then compute the LOOCV errors that result from fitting the following four models using least squares:
Note you may find it helpful to use the data.frame() function to create a single data set containing both X and Y.
A:
As I am going to be fitting lots of models using LOOCV to evaluate, I just want to check that three potential methods all give the same results, along with comparing the speed of them.
To do this, I compute the LOOCV error of a linear model of the form \(y = \hat{\beta_0} + \hat{\beta_1}x + \hat{\beta_2}x^2\) 10 times using each method, then use Sys.time() to record how long these take.
cv.glm() function:data <- data.frame(x = x, y = y)
start_time <- Sys.time()
for (j in 1:10) {
glm_1 <- glm(y ~ x + I(x^2), data = data)
cv_glm_1 <- cv.glm(data, glm_1)
LOOCV_MSE <- cv_glm_1$delta[1]
}
end_time <- Sys.time()
LOOCV_MSE## [1] 0.9374236
round(end_time - start_time, 3)## Time difference of 2.582 secs
start_time <- Sys.time()
for (j in 1:10) {
error <- c()
for (i in 1:nrow(data)) {
model <- glm(y ~ x + I(x^2), data = data[-i,])
prediction <- predict(model, newdata = data[i,])
error[i] <- (prediction - data[i, "y"]) ^ 2
if (i == nrow(data)) {
LOOCV_MSE <- mean(error)
}
}
}
end_time <- Sys.time()
LOOCV_MSE## [1] 0.9374236
round(end_time - start_time, 3)## Time difference of 1.591 secs
\[\begin{align*} & CV_{(n)} = \frac{1}{n} \sum_{i = 1}^{n} \left( \frac{y_i - \hat{y_i}}{1 - h_i} \right)^2 \\ where: \quad & H = X(X^TX)^{-1}X^T && \text{(} X \text{ is the design matrix)} \\ \quad & h_i = [H]_{ii} && \text{(diagonal elements of the hat matrix } H \text{, i.e. leverages)} \\ \end{align*}\]
start_time <- Sys.time()
for (j in 1:10) {
glm_2 <- glm(y ~ x + I(x^2), data = data)
LOOCV_MSE <- mean(((data$y - predict(glm_2)) / (1 - glm.diag(glm_2)$h)) ^ 2)
}
end_time <- Sys.time()
LOOCV_MSE## [1] 0.9374236
round(end_time - start_time, 3)## Time difference of 0.025 secs
Since the third method is so much faster, I create the LOOCV() function, which will (given the data and a formula), compute the LOOCV estimate for the test MSE using this approach. I will use this function for the remainder of the question:
LOOCV <- function(data, formula) {
model <- glm(formula(formula), data = data)
mean(((data$y - predict(model))/(1 - boot::glm.diag(model)$h))^2)
}i. \(Y = \beta_0 + \beta_1X + \epsilon\)
LOOCV(data, "y ~ x") %>% round(3) # 7.288## [1] 7.288
ii. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \epsilon\)
LOOCV(data, "y ~ x + I(x^2)") %>% round(3) # 0.937## [1] 0.937
iii. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 + \epsilon\)
LOOCV(data, "y ~ x + I(x^2) + I(x^3)") %>% round(3) # 0.957## [1] 0.957
iv. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 + \beta_4X^4 + \epsilon\)
LOOCV(data, "y ~ x + I(x^2) + I(x^3) + I(x^4)") %>% round(3) # 0.954## [1] 0.954
Q: Repeat (c) using another random seed, and report your results. Are your results the same as what you got in (c)? Why?
A:
set.seed(2, sample.kind = "Rounding")
LOOCV_first_order <- LOOCV(data, "y ~ x")
round(LOOCV_first_order, 3)## [1] 7.288
LOOCV_second_order <- LOOCV(data, "y ~ x + I(x^2)")
round(LOOCV_second_order, 3)## [1] 0.937
LOOCV_third_order <- LOOCV(data, "y ~ x + I(x^2) + I(x^3)")
round(LOOCV_third_order, 3)## [1] 0.957
LOOCV_fourth_order <- LOOCV(data, "y ~ x + I(x^2) + I(x^3) + I(x^4)")
round(LOOCV_fourth_order, 3)## [1] 0.954
We get the same results. This is because with LOOCV, there is no randomness - there can only be one LOOCV error statistic.
This can be understood better by laying out the steps of how the \(n\) models are fit in the leave-one-out cross-validation process:
train set and a one-observation test settrain and evaluate it on testtest exactly onceUnlike with \(k\)-fold CV (where the random state impacts the initial partition), there is only one way that we can calculate the LOOCV error. If a different seed had an impact on the LOOCV estimate, we would not have been able to reduce the LOOCV MSE estimate to a simple computation from a single least squares model fit!
Q: Which of the models in (c) had the smallest LOOCV error? Is this what you expected? Explain your answer.
A:
The quadratic model has the smallest LOOCV error, although the second, third & fourth order polynomial fits perform almost identically. This is as we would expect, and in part a) I go into more detail about the underlying relationship between \(X\) and \(Y\), where \(Y\) is defined as a second order polynomial of \(X\).
It makes sense why the ‘added benefit’ of going from a first to second-order polynomial is far higher than the ‘penalty’ of going from a second to third/fourth-order polynomial.
This becomes clearer when we look at the form that the higher-order polynomials take. Below I plot the polynomial fits on a graph, we can see for order 2 and above, the fits look identical, even though the functional form assumed by the third and fourth-order polynomial fits are technically incorrect.
This means that the actual predictions are almost identical (and therefore, so is the LOOCV estimate):
g1 <- ggplot(mapping = aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", formula = "y ~ x") +
geom_hline(yintercept = 0, col = "grey55") +
geom_vline(xintercept = 0, col = "grey55") +
labs(title = "Fit: y ~ x",
subtitle = paste0("LOOCV MSE estimate: ", round(LOOCV_first_order, 3)))
g2 <- ggplot(mapping = aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", formula = "y ~ x + I(x^2)") +
geom_hline(yintercept = 0, col = "grey55") +
geom_vline(xintercept = 0, col = "grey55") +
labs(title = "Fit: y ~ x + x^2",
subtitle = paste0("LOOCV MSE estimate: ", round(LOOCV_second_order, 3)))
g3 <- ggplot(mapping = aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", formula = "y ~ x + I(x^2) + I(x^3)") +
geom_hline(yintercept = 0, col = "grey55") +
geom_vline(xintercept = 0, col = "grey55") +
labs(title = "Fit: y ~ x + x^2 + x^3",
subtitle = paste0("LOOCV MSE estimate: ", round(LOOCV_third_order, 3)))
g4 <- ggplot(mapping = aes(x = x, y = y)) +
geom_point() +
geom_smooth(method = "lm", formula = "y ~ x + I(x^2) + I(x^3) + I(x^4)") +
geom_hline(yintercept = 0, col = "grey55") +
geom_vline(xintercept = 0, col = "grey55") +
labs(title = "Fit: y ~ x + x^2 + x^3 + x^4",
subtitle = paste0("LOOCV MSE estimate: ", round(LOOCV_fourth_order, 3)))
gridExtra::grid.arrange(g1, g2, g3, g4, nrow = 2, ncol = 2)
Q: Comment on the statistical significance of the coefficient estimates that results from fitting each of the models in (c) using least squares. Do these results agree with the conclusions drawn based on the cross-validation results?
A:
i. \(Y = \beta_0 + \beta_1X + \epsilon\)
summary(glm(y ~ x, data = data))$coefficients %>% round(6)## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.625427 0.261937 -6.205420 0.000000
## x 0.692497 0.290942 2.380191 0.019238
ii. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \epsilon\)
summary(glm(y ~ x + I(x^2), data = data))$coefficients %>% round(6)## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.056715 0.117655 0.482043 0.630861
## x 1.017161 0.107983 9.419666 0.000000
## I(x^2) -2.118921 0.084766 -24.997388 0.000000
iii. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 + \epsilon\)
summary(glm(y ~ x + I(x^2) + I(x^3), data = data))$coefficients %>% round(6)## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.061507 0.119504 0.514688 0.607954
## x 0.975280 0.187281 5.207564 0.000001
## I(x^2) -2.123791 0.087003 -24.410686 0.000000
## I(x^3) 0.017639 0.064290 0.274358 0.784399
iv. \(Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 + \beta_4X^4 + \epsilon\)
summary(glm(y ~ x + I(x^2) + I(x^3) + I(x^4), data = data))$coefficients %>% round(6)## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 0.156703 0.139462 1.123625 0.264003
## x 1.030826 0.191337 5.387500 0.000001
## I(x^2) -2.409898 0.234855 -10.261215 0.000000
## I(x^3) -0.009133 0.067229 -0.135848 0.892229
## I(x^4) 0.069785 0.053240 1.310769 0.193096
There is no evidence (at the 5% level) that the coefficients for \(X^3\) and \(X^4\) are non-zero. This is in agreement with the LOOCV error, which also concluded that there was no reason to select the third or fourth-order fits over the second-order fit.
Boston Dataset - Bootstrapping (Standard Errors, Confidence Intervals)We will now consider the Boston housing data set, from the MASS library.
glimpse(Boston)## Rows: 506
## Columns: 14
## $ crim <dbl> 0.00632, 0.02731, 0.02729, 0.03237, 0.06905, 0.02985, 0.088...
## $ zn <dbl> 18.0, 0.0, 0.0, 0.0, 0.0, 0.0, 12.5, 12.5, 12.5, 12.5, 12.5...
## $ indus <dbl> 2.31, 7.07, 7.07, 2.18, 2.18, 2.18, 7.87, 7.87, 7.87, 7.87,...
## $ chas <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
## $ nox <dbl> 0.538, 0.469, 0.469, 0.458, 0.458, 0.458, 0.524, 0.524, 0.5...
## $ rm <dbl> 6.575, 6.421, 7.185, 6.998, 7.147, 6.430, 6.012, 6.172, 5.6...
## $ age <dbl> 65.2, 78.9, 61.1, 45.8, 54.2, 58.7, 66.6, 96.1, 100.0, 85.9...
## $ dis <dbl> 4.0900, 4.9671, 4.9671, 6.0622, 6.0622, 6.0622, 5.5605, 5.9...
## $ rad <int> 1, 2, 2, 3, 3, 3, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4,...
## $ tax <dbl> 296, 242, 242, 222, 222, 222, 311, 311, 311, 311, 311, 311,...
## $ ptratio <dbl> 15.3, 17.8, 17.8, 18.7, 18.7, 18.7, 15.2, 15.2, 15.2, 15.2,...
## $ black <dbl> 396.90, 396.90, 392.83, 394.63, 396.90, 394.12, 395.60, 396...
## $ lstat <dbl> 4.98, 9.14, 4.03, 2.94, 5.33, 5.21, 12.43, 19.15, 29.93, 17...
## $ medv <dbl> 24.0, 21.6, 34.7, 33.4, 36.2, 28.7, 22.9, 27.1, 16.5, 18.9,...
medv Population Mean - \(\hat{\mu}\)Q: Based on this data set, provide an estimate for the population mean of medv. Call this estimate \(\hat{\mu}\).
A:
We estimate the population mean of medv by taking the sample mean, so \(\hat{\mu}\) is given by:
mean(Boston$medv)## [1] 22.53281
Q: Provide an estimate of the standard error of \(\hat{\mu}\). Interpret this result.
Hint: We can compute the standard error of the sample mean by dividing the sample standard deviation by the square root of the number of observations
A:
Using the hint, \(SE(\hat{\mu}) = \frac{\sigma}{\sqrt{n}}\), we get estimate the standard error of \(\hat{\mu}\) as:
sd(Boston$medv) / sqrt(length(Boston$medv))## [1] 0.4088611
Q: Now estimate the standard error of \(\hat{\mu}\) using the bootstrap. How does this compare to your answer from (b)?
A:
I calculate the mean for 1,000 bootstrap samples. The bootstrap estimate for the standard error of \(\hat{\mu}\) is shown below.
boot.fn <- function(vector, index) {
mean(vector[index])
}
set.seed(66, sample.kind = "Rounding")
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 22.53281 0.0116587 0.4081538
While not identical, the estimate for \(SE(\hat{\mu})\) is the same to 2dp: 0.4082 vs 0.4089.
Q: Based on your bootstrap estimate from (c), provide a 95% confidence interval for the mean of medv. Compare it to the results obtained using t.test(Boston$medv).
Hint: You can approximate a 95% confidence interval using the formula \([\hat{\mu} - 2SE(\hat{\mu}), \hat{\mu} + 2SE(\hat{\mu})]\)
A:
Since it’s not easy to directly extract the bootstrap standard error from the bootstrap output, we can calculate it ourselves by taking the standard deviation of the bootstrap estimates.
From here, it is simple to calculate the bootstrap 95% confidence interval using the hint:
boot_results_SE <- sd(boot_results$t)
round(c(mean(Boston$medv) - 2*boot_results_SE, mean(Boston$medv) + 2*boot_results_SE), 4)## [1] 21.7165 23.3491
Using t.test(Boston$medv):
t.test(Boston$medv)##
## One Sample t-test
##
## data: Boston$medv
## t = 55.111, df = 505, p-value < 2.2e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
## 21.72953 23.33608
## sample estimates:
## mean of x
## 22.53281
The confidence interval estimates are the same to 1dp.
medv Population Median - \(\hat{\mu}_{med}\)Q: Based on this data set, provide an estimate, \(\hat{\mu}_{med}\), for the median value of medv in the population.
A:
We estimate the population median of medv by taking the sample median, so \(\hat{\mu}_{med}\) is given by:
median(Boston$medv)## [1] 21.2
Q: We now would like to estimate the standard error of \(\hat{\mu}_{med}\). Unfortunately, there is no simple formula for computing the standard error of the median. Instead, estimate the standard error of the median using the bootstrap. Comment on your findings.
A:
We can use the identical code as in part c), but replacing mean() with median():
boot.fn <- function(vector, index) {
median(vector[index])
}
set.seed(77, sample.kind = "Rounding")
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 21.2 0.0094 0.3700318
As with the mean, the standard error is quite small relative to the estimate.
medv Population 10th Percentile - \(\hat{\mu}_{0.1}\)Q: Based on this data set, provide an estimate for the tenth percentile of medv in Boston suburbs. Call this quantity \(\hat{\mu}_{0.1}\). (You can use the quantile() function.)
A:
As before, we calculate the sample tenth percentile as our estimate:
quantile(Boston$medv, 0.1)## 10%
## 12.75
Q: Use the bootstrap to estimate the standard error of \(\hat{\mu}_{0.1}\). Comment on your findings.
A:
boot.fn <- function(vector, index) {
quantile(vector[index], 0.1)
}
set.seed(77, sample.kind = "Rounding")
(boot_results <- boot(data = Boston$medv, statistic = boot.fn, R = 1000))##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = Boston$medv, statistic = boot.fn, R = 1000)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* 12.75 0.02085 0.488873
The standard error is slightly larger relative to \(\hat{\mu}_{0.1}\), but it is still small.