我一直在尝试在 R 中创建一个随机套索函数,但它似乎不会产生与 Python sklearn 随机套索函数相同的结果。我在这里应用相同的理念,但无法理解其中的区别。代码基于此代码进行了修改:R中的随机套索函数。
以下是代码和示例数据:
# generate synthetic data
set.seed(100)
size = 750
x = matrix(runif(14*size),ncol=14)
y = 10 * sin(pi*X[,1]*X[,2]) + 20*(X[,3]-0.5)**2 + 10*X[,4] + 5*X[,5] + runif(1,0,1)
nbootstrap = 200
nsteps = 20
alpha = 0.2
dimx <- dim(x)
n <- dimx[1]
p <- dimx[2]
halfsize <- as.integer(n/2)
freq <- matrix(0,1,p)
for (i in seq(nbootstrap)) {
# Randomly reweight each variable
xs <- t(t(x)*runif(p,alpha,1))
# Ramdomly split the sample in two sets
perm <- sample(dimx[1])
i1 <- perm[1:halfsize]
i2 <- perm[(halfsize+1):n]
# run the randomized lasso on each sample and check which variables are selected
cv_lasso <- lars::cv.lars(xs[i1,],y[i1],plot.it=FALSE, mode = 'step')
idx <- which.max(cv_lasso$cv - cv_lasso$cv.error <= min(cv_lasso$cv))
coef.lasso <- coef(lars::lars(xs[i1,],y[i1]))[idx,]
freq <- freq + abs(sign(coef.lasso))
cv_lasso <- lars::cv.lars(xs[i2,],y[i2],plot.it=FALSE, mode = 'step')
idx <- which.max(cv_lasso$cv - cv_lasso$cv.error <= min(cv_lasso$cv))
coef.lasso <- coef(lars::lars(xs[i1,],y[i1]))[idx,]
freq <- freq + abs(sign(coef.lasso))
print(freq)
}
# normalize frequence in [0,1]
freq <- freq/(2*nbootstrap)
结果应该与此表中显示的结果相似(稳定性)python 中的稳定性。但是,这种方法和第一个超链接参考中显示的原始 R 代码没有找到 X11 到 X14 的相关特征。不确定我的 R 代码中哪个部分不能正常工作。