右 |如何从 cv.glmnet 获得准确度

R | How to get accuracy from cv.glmnet

我一直在使用 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 对象(模型)获取模型精度。

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

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

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

您要添加 type.measure='class',如下面的模型 2 所示,否则 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