R |如何从cv.glmnet获得准确性

时间:2020-10-24 05:23:09

标签: r glm lasso-regression

我一直在使用cv.glmnet函数来拟合套索逻辑回归模型。我正在使用R

这是我的代码。我正在使用iris数据集。

df = iris %>% 
  mutate(Species = as.character(Species)) %>% 
  filter(!(Species =="setosa")) %>% 
  mutate(Species = as.factor(Species))
  
X = data.matrix(df %>% select(-Species))
y = df$Species

Model = cv.glmnet(X, y, alpha = 1, family = "binomial")

如何从cv.glmnet对象(模型)获得模型精度。

如果我在正常的Logistic回归模型上使用插入符号,则输出中已经存在准确性。

train_control = trainControl(method = "cv", number = 10)
M2 = train(Species ~., data = df, trControl = train_control, 
           method = "glm", family = "binomial")
M2$results

但是cv.glmnet对象似乎不包含此信息。

1 个答案:

答案 0 :(得分:2)

您要像下面的模型2一样添加type.measure='class',否则family='binomial'的默认值为'deviance'

df = iris %>% 
  mutate(Species = as.character(Species)) %>% 
  filter(!(Species =="setosa")) %>% 
  mutate(Species = as.factor(Species))

X = data.matrix(df %>% select(-Species))
y = df$Species

Model  = cv.glmnet(X, y, alpha = 1, family = "binomial")
Model2 = cv.glmnet(X, y, alpha = 1, family = "binomial", type.measure = 'class')

然后cvm给出误分类率。

Model2$lambda ## lambdas used in CV
Model2$cvm    ## mean cross-validated error for each of those lambdas

如果您想要获得最佳lambda的结果,则可以使用lambda.min

Model2$lambda.min ## lambda with the lowest cvm
Model2$cvm[Model2$lambda==Model2$lambda.min] ## cvm for lambda.min