train(),插入符号包中的ROC度量

时间:2018-06-01 01:31:37

标签: r machine-learning neural-network r-caret roc

df在火车和测试数据帧中被分割。列车数据框在训练和测试数据框架中分开。因变量Y是二进制(因子),值为0和1.我试图用这个代码预测概率(神经网络,插入符号包):

library(caret)

model_nn <- train(
  Y ~ ., training,
  method = "nnet",
  metric="ROC",
  trControl = trainControl(
    method = "cv", number = 10,
    verboseIter = TRUE,
    classProbs=TRUE
  )
)

model_nn_v2 <- model_nn
nnprediction <- predict(model_nn, testing, type="prob")
cmnn <-confusionMatrix(nnprediction,testing$Y)
print(cmnn) # The confusion matrix is to assess/compare the model

然而,它给了我这个错误:

    Error: At least one of the class levels is not a valid R variable name; 
This will cause errors when class probabilities are generated because the
 variables names will be converted to  X0, X1 . Please use factor levels 
that can be used as valid R variable names  (see ?make.names for help).

我不明白是什么意思&#34;使用可以用作有效R变量名称的因子水平&#34;。因变量Y已经是一个因子,但不是有效的R变量名??

PS:如果您删除classProbs=TRUE中的trainControl()metric="ROC"中的train(),则代码可以正常运行。但是,"ROC"指标是我的最佳模型的比较指标,因此我尝试使用&#34; ROC&#34;度量。

编辑:代码示例:

# You have to run all of this BEFORE running the model
classes <- c("a","b","b","c","c")
floats <- c(1.5,2.3,6.4,2.3,12)
dummy <- c(1,0,1,1,0)
chr <- c("1","2","2,","3","4")
Y <- c("1","0","1","1","0")
df <- cbind(classes, floats, dummy, chr, Y)
df <- as.data.frame(df)
df$floats <- as.numeric(df$floats)
df$dummy <- as.numeric(df$dummy)

classes <- c("a","a","a","b","c")
floats <- c(5.5,2.6,7.3,54,2.1)
dummy <- c(0,0,0,1,1)
chr <- c("3","3","3,","2","1")
Y <- c("1","1","1","0","0")
df <- cbind(classes, floats, dummy, chr, Y)
df <- as.data.frame(df)
df$floats <- as.numeric(df$floats)
df$dummy <- as.numeric(df$dummy)

1 个答案:

答案 0 :(得分:4)

这里有两个不同的问题。

第一个是错误消息,它说明了一切:您必须使用除"0", "1"以外的其他内容作为作为因变量因变量Y

在构建数据框df之后,您可以通过至少两种方式执行此操作;第一个是暗示错误消息,即使用make.names

df$Y <- make.names(df$Y)
df$Y
# "X1" "X1" "X1" "X0" "X0"

第二种方法是使用levels函数,通过该函数,您可以明确控制名称本身;再次使用名称X0X1

在此处显示
levels(df$Y) <- c("X0", "X1")
df$Y
# [1] X1 X1 X1 X0 X0
# Levels: X0 X1

在添加上述任一行之后,显示的train()代码将顺利运行(将training替换为df),但它仍然不会产生任何ROC值,而是警告:

Warning messages:
1: In train.default(x, y, weights = w, ...) :
  The metric "ROC" was not in the result set. Accuracy will be used instead.

这就引出了我们的第二个问题:为了使用ROC指标,您必须在summaryFunction = twoClassSummary的{​​{1}}参数中添加trControl

train()

使用您提供的玩具数据运行上述代码段仍然会出现错误(缺少ROC值),但这可能是由于此处使用的非常小的数据集与大量CV折叠相结合,并且不会发生使用您自己的完整数据集(如果我将CV折叠减少到model_nn <- train( Y ~ ., df, method = "nnet", metric="ROC", trControl = trainControl( method = "cv", number = 10, verboseIter = TRUE, classProbs=TRUE, summaryFunction = twoClassSummary # ADDED ) ) ,则工作正常)...