y[train] 的 glmnet 中的套索错误

Lasso error in glmnet for y[train]

我对 R 中的包 glmnet 有疑问。我正在尝试使用它,但遇到以下问题: {

 > names(mtcars)

#lasso
## 75% of the sample size


 > smp_size <- floor(0.75 * nrow(mtcars))

## set the seed to make your partition reproductible
> set.seed(123)

> train_ind <- sample(seq_len(nrow(mtcars)), size = smp_size)

> train <- mtcars[train_ind, ]

> names(train)

> y<-train["hp"]

> c(y)

> yvector<-c(y)

> is.vector(yvector)

> grid=10^seq(10,-2,length=24)

> lasso.mod=glmnet(train,yvector, alpha=1, lambda=grid)

Error in glmnet(train, yvector, alpha = 1, lambda = grid) : number of observations in y (1) not equal to the number of rows of x (24)

> lasso.mod=glmnet(train,y, alpha=1, lambda=grid)

Error in weighted.mean.default(y, weights) : 'x' and 'w' must have the same length

> lasso.mod=glmnet(train,train, alpha=1, lambda=grid)

Error in weighted.mean.default(y, weights) : 'x' and 'w' must have the same length }

每次我将最后一行(glmnet 程序)更改为 y(输入相同长度的矩阵或向量)时,它会重复最后三个错误!!!我该怎么办?

在这一行

y <- train["hp"]

结果是包含一个变量 (hp) 的数据框。你想要的是提取那个变量到一个向量中:

y <- train[["hp"]]
# or
y <- train$hp

您还可以使用我的 glmnetUtils 包来处理设置响应向量和模型矩阵的机制。

devtools::install_github("hong-revo/glmnetUtils")
library(glmnetUtils)
lasso.mod <- glmnet(hp ~ ., data=train, alpha=1, lambda=grid)