【问题标题】:Why R glmnet predict gives a matrix instead of just one column?为什么 R glmnet predict 给出一个矩阵而不是一列?
【发布时间】:2021-10-11 19:23:05
【问题描述】:

我想用岭正则化拟合逻辑回归。这是我的代码

library(modeldata)
library(glmnet)

# check the data
data(attrition)
head(attrition)

# split the data into training 80%, and test 20%
smp_size <- floor(0.8 * nrow(attrition))

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

# randomly get the index for training data
train_ind <- sample(seq_len(nrow(attrition)), size = smp_size)

# get training and testing data
train <- attrition[train_ind, ]
test <- attrition[-train_ind, ]


# fit the model
X <- model.matrix(Attrition~ ., train)
lm_ridge <- glmnet(X, train$Attrition, family = 'binomial', alpha = 0)


# get predicted values based on ridge regularization
prob_ridge <- predict(lm_ridge, model.matrix(Attrition~ ., test), type = 'response')

prob_ridge 给出了一个 294 * 100 的矩阵。但我希望只有一列,294*1。我的代码有什么问题吗?为什么我从 predict 函数中得到一个矩阵?

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • @MrFlick 感谢您的提示。我更新了我的代码。

标签: r logistic-regression glmnet


【解决方案1】:

对于glmnet,拟合了一系列 lambda,因此您可以获得每个 lambda 的系数以及每个 lambda 的预测。如vignette 中所述:

如果提供了多个 s 值,则预测矩阵为 产生。如果没有提供 s 的值,则预测矩阵为 提供的列对应于 适合。

所以在你的情况下,你的 lambda 值是:

head(lm_ridge$lambda,50)
 [1] 84.7169444 77.1909245 70.3334955 64.0852617 58.3921036 53.2047101
 [7] 48.4781503 44.1714850 40.2474120 36.6719429 33.4141086 30.4456913
[13] 27.7409800 25.2765478 23.0310489 20.9850340 19.1207814 17.4221439
[19] 15.8744087 14.4641699 13.1792130 12.0084080 10.9416141  9.9695913
[25]  9.0839203  8.2769298  7.5416302  6.8716526  6.2611939  5.7049667
[31]  5.1981532  4.7363636  4.3155981  3.9322122  3.5828853  3.2645917
[37]  2.9745744  2.7103214  2.4695439  2.2501564  2.0502587  1.8681194
[43]  1.7021608  1.5509455  1.4131638  1.2876222  1.1732334  1.0690066
[49]  0.9740390  0.8875081

如果你选择 lambda (s = 0.8875081),那么你会得到 1 列:

pred = predict(lm_ridge, model.matrix(Attrition~ ., test), type = 'response',
s = 0.8875081)
dim(pred)
[1] 294   1

如果您想知道可选的 lambda,可以按照小插图中的示例(上面提到)并使用 cv.glmnet 的交叉验证方法,例如:

cvfit = cv.glmnet(X, train$Attrition, family = 'binomial', alpha = 0)
pred = predict(cvfit, model.matrix(Attrition~ ., test), type = 'response')

dim(pred)
[1] 294   1

默认选择:

“lambda.1se”:MSE 在一个标准内的最大 ? 最小 MSE 的误差(默认)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
  • 2020-08-09
  • 2020-10-20
  • 2021-07-21
  • 2015-10-27
  • 1970-01-01
  • 2014-05-15
相关资源
最近更新 更多