【发布时间】: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