-
Notifications
You must be signed in to change notification settings - Fork 0
/
302_ridge.Rmd
71 lines (51 loc) · 1.43 KB
/
302_ridge.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
# Ridge Regression - L2 Regularization
<!-- Discussion of the model goes here -->
```{r}
ridge <- function(X, Y, rm_na=T, standardise=F, lambda, method="matrix") {
if (!is.matrix(X)) {
X <- as.matrix(X)
}
if (rm_na) {
index <- complete.cases(X) & complete.cases(Y)
X <- X[index,]
Y <- Y[index]
}
if (standardise) {
X <- apply(X, 2, function(x) (x - mean(x))/sd(x))
}
# if (intercept) {
# X <- cbind(rep(1,nrow(X)), X)
# colnames(X)[1] <- "(Intercept)"
# }
k <- ncol(X)
if (method=="matrix") {
b <- solve(crossprod(X) + lambda*diag(k)) %*% crossprod(X, Y)
} else if (method=="MLE") {
start <- numeric(k)
ridgeMin <- function(b) {
crossprod(Y - X%*%b) + lambda * crossprod(b)
}
out <- optim(start, ridgeMin, method="BFGS")
b <- out$par
names(b) <- colnames(X)
}
return(b)
}
```
Testing the function:
```{r}
library(glmnet)
X <- as.matrix(mtcars[, -1])
X_standard <- apply(X, 2, function(x) (x-mean(x)) / sd(x))
Y <- mtcars[[1]]
data.frame(
glmnet = glmnet(X, Y, alpha=0, lambda=0.5, intercept = F, standardize=F)$beta[,1],
Ridge_Matrix = ridge(X, Y, lambda=0.5),
Ridge_MLE = ridge(X, Y, lambda=0.5, method="MLE")
)
data.frame(
glmnet = glmnet(X_standard, Y, alpha=0, lambda=0.5, intercept = F, standardize=F)$beta[,1],
Ridge_Matrix = ridge(X_standard, Y, lambda=0.5),
Ridge_MLE = ridge(X_standard, Y, lambda=0.5, method="MLE")
)
```