I'm trying to calculate the beta for ridge regression from scratch. But when I compare the results when using the glmnet
function, they are different. Here's my code:
library(MASS)
Boston=na.omit(Boston)
x=model.matrix(age~.,Boston)[,-1]
y=as.matrix(Boston$age)
lmodel=lm(y~x, data=Boston)
#ridge with glmnet
library(glmnet)
ridge=glmnet(x,y, alpha=0, lambda = 0.1)
beta_ridge=coef(ridge)
#ridge scratch
x=scale(x)
y=scale(y)
beta_r=solve(t(x)%*%x + 0.1*diag(dim(x)[2]))%*%t(x)%*%y
I standardized x and y, but I still get different betas in comparison to the betas from the glmnet function.