我只是想了解R包glmnet中实现的套索。 我正在拟合数据,但我得到的解决方案是我选择的lambda 不要最小化套索的标准,例如,如果我以一种方式移动解决方案 我可以获得更小的成本函数。
我理解错误是什么?
library(lattice)
library(Matrix)
library(glmnet)
# Target vector
Target <- c(1.3906275E7, -1.8241672E7, 8181847.0, 1.6927098E7, -6547966.5, -1363836.375)
# Observation vector
Obs <- matrix(c( -0.944, 0.869 ,-0.795,-0.996, 0.617, 0.886,
-0.472 , 0.936 , 0.063 ,-0.080,-0.751 ,-0.834,
-0.107 , 0.343 , 0.261 , 0.327,-0.255,0.705,
-1.803,-0.781,0.168,0.211,-0.349, -0.040),6,4)
#fitting
fits <-glmnet(Obs,Target)
# arbitrary choice of lambda
lambda <- 221800
coef = predict(fits,s = lambda ,type="coefficients")
res = c(coef[2,1],coef[3,1],coef[4,1],coef[5,1])
# Computing the lasso criteria
newbookrisklassor = Target-Obs%*%res
cost = sum(abs(res))
newRisklassor = t(newbookrisklassor) %*% newbookrisklassor+lambda*cost
# Moving solution slightly in 1 way and computing the lasso criteria
epsilon = 500000
resP = res + c(0,epsilon,0,0)
costP = sum(abs(resP))
newbookrisklassorP = Target-Obs%*%resP
newRisklassorP = t(newbookrisklassorP) %*% newbookrisklassorP+lambda*costP
# Error it seems that the resP solution is better
newRisklassor-newRisklassorP
答案 0 :(得分:1)
您应该在拟合中添加截距 newbookrisklassor = Target-Obs%*%res-intercept ...