-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidation_test_set.Rmd
More file actions
43 lines (37 loc) · 1.07 KB
/
Copy pathValidation_test_set.Rmd
File metadata and controls
43 lines (37 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
---
title: "Validation_set_test"
output: html_document
---
We begin by splitting the "Hitters" dataset into a "test" group and "train" group.
```{r}
library(ISLR)
fix(Hitters)
library(leaps)
set.seed(1)
train=sample(c(TRUE,FALSE), nrow(Hitters), rep=TRUE)
train
```
```{r}
test=(!train)
test
```
First, we generate the model using regsubsets() function. Note that we use the [train,] subset of the Hitters dataset.
```{r}
regfit.best=regsubsets(Salary~., data=Hitters[train,], nvmax=19)
```
Now, we generate an "X" data matrix using the test data set.
```{r}
test.matrix = model.matrix(Salary~., data=Hitters[test,])
test.matrix
```
Next, we run a for loop, and for each size of model i, we extract the coefficients from the regfit.best model, multiply them into the columns of the model.matrix to form the predictions, and then compute the MSE (mean squared error).
```{r}
val.errors=rep(NA,19)
for(i in 1:19){
coefi=coef(regfit.best, id=i)
prediction = test.matrix[,names(coefi)]%*%coefi
val.errors[i]=mean((Hitters$Salary[test]-prediction)^2)
}
val.errors
which.min(val.errors)
```