-
Notifications
You must be signed in to change notification settings - Fork 3
/
ridge_regression.Rmd
208 lines (163 loc) · 5.78 KB
/
ridge_regression.Rmd
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
---
title: "Ridge Regression"
output:
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
set.seed(1)
source("install_packages.r")
require(knitr)
require(plotly)
require(ggplot2)
require(ISLR)
require(glmnet)
```
## Data
```{r}
Hitters <- Hitters
names(Hitters)
summary(Hitters)
sum(is.na(Hitters$Salary))
Hitters <- na.omit(Hitters)
```
| Variable | Description | |
|------------|-------------------------------------------------------------------------------------|---|
| AtBat | Number of times at bat in 1986 | |
| Hits | Number of hits in 1986 | |
| HmRun | Number of home runs in 1986 | |
| Runs | Number of runs in 1986 | |
| RBI | Number of runs batted in in 1986 | |
| Walks | Number of walks in 1986 | |
| Years | Number of years in the major leagues | |
| CAtBat | Number of times at bat during his career | |
| CHits | Number of hits during his career | |
| CHmRun | Number of home runs during his career | |
| CRuns | Number of runs during his career | |
| CRBI | Number of runs batted in during his career | |
| Cwalks | Number of walks during his career | |
| League | A factor with levels A and N indicating player’s league at the end of 1986 | |
| Division | A factor with levels E and W indicating player’s division at the end of 1986 | |
| PutOuts | Number of put outs in 1986 | |
| Assists | Number of assists in 1986 | |
| Errors | Number of errors in 1986 | |
| Salary | 1987 annual salary on opening day in thousands of dollars | |
| NewLeague | A factor with levels A and N indicating player’s league at the beginning of 1987 | |
`model.matrix()` - function need input in matrix $\mathbf{X}$ and vector $\mathbf{y}$
## Ridge regression
```{r}
x = model.matrix(Salary~., Hitters)[ , -1]
y = Hitters$Salary
```
function `glmnet()` - lasso, ridge regression
alpha = 0 - ridge regression
alpha = 1 - lasso regression
lambda (regularization/penality) coefficient can be selected automatically by `glmnet()` itself
we estimate model for lambda <0, 10^10,>
```{r}
grid = 10^seq(10, -2, length=100)
ridge.mod = glmnet(x, y ,alpha=0, lambda=grid)
plot(ridge.mod, xvar="lambda", label=TRUE)
```
20 coefficients for 101 models
```{r}
dim(coef(ridge.mod))
```
```{r}
#value of lambda
ridge.mod$lambda[50]
#coef
coef(ridge.mod)[,50]
sqrt(sum(coef(ridge.mod)[-1, 50]^2))
```
```{r}
#value of lambda
ridge.mod$lambda[60]
#coef
coef(ridge.mod)[,60]
sqrt(sum(coef(ridge.mod)[-1, 60]^2))
```
smaller lambda = larger coefficients
```{r}
predict(ridge.mod, s=50, type="coefficients")[1:20, ]
```
## Cross-Validation
```{r}
set.seed(1)
train=sample(1: nrow(x), nrow(x)/2)
test=(-train)
y.test=y[test]
```
```{r}
ridge.mod=glmnet(x[train, ], y[train], alpha=0, lambda=grid, thresh=1e-12)
```
Model with lambda = 4
```{r}
ridge.pred=predict(ridge.mod, s=4, newx = x[test ,])
mean((ridge.pred - y.test)^2)
```
Model consisting only of constant (intercept) - no variability explaind
```{r}
mean((mean(y[train]) - y.test)^2)
```
Similar result with very large lambda
```{r}
ridge.pred=predict(ridge.mod ,s=1e10 ,newx=x[test, ])
mean((ridge.pred-y.test)^2)
```
Ridge model with lambda = 0 is equal to least squares (for recalculation with s=0 exact should be set to T)
Comparison of MSEs
```{r}
ridge.pred=predict(ridge.mod, x=x[train,] , y=y[train] ,s=0, exact=T, newx=x[test, ])
mean((ridge.pred - y.test)^2)
lm.mod <- lm(Salary~., data=Hitters, subset=train)
lm.pred <- predict(lm.mod, newdata = Hitters[-train,])
mean((lm.pred - y.test)^2)
```
Ridge model with lambda = 0 is equal to least squares (for recalculation with s=0 exact should be set to T)
Coefficient comparison
```{r}
(lm(y~x, subset=train))
(predict(ridge.mod, x=x[train,] , y=y[train] ,s=0, exact=T, type="coefficients")[1:20 ,])
```
function `cv.glmnet()` - cross-validation function, default = ten-fold
```{r}
set.seed(1)
cv.out =cv.glmnet(x[train ,], y[train], alpha =0)
plot(cv.out)
bestlam =cv.out$lambda.min
bestlam
```
```{r}
ridge.pred=predict(ridge.mod, s=bestlam, newx=x[test ,])
mean((ridge.pred - y.test)^2)
```
Estimed on full data set
```{r}
out=glmnet(x, y, alpha =0)
predict(out, type="coefficients", s=bestlam )[1:20 ,]
```
No zero coefficients => ridge regression doesnt perform variable selection.
## Lasso Regression
alpha = 1
```{r}
lasso.mod=glmnet(x[train, ], y[train], alpha=1, lambda=grid)
```
```{r}
plot(lasso.mod)
```
```{r}
cv.out=cv.glmnet(x[train ,], y[train], alpha=1)
plot(cv.out)
(bestlam=cv.out$lambda.min)
```
```{r}
lasso.pred=predict(lasso.mod, s=bestlam, newx=x[test, ])
mean((lasso.pred - y.test)^2)
```
```{r}
out=glmnet(x,y,alpha=1, lambda=grid)
lasso.coef=predict(out ,type="coefficients", s=bestlam)[1:20, ]
lasso.coef
```
Some coefficeint are zero => Lasso regression can be used to performe variable selection.