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).
我不明白是什么意思"use factor levels that can be used as valid R variable names" . 因变量 Y
已经是一个因子,但不是有效的R变量名?
PS:如果在 trainControl()
中删除 classProbs=TRUE
并在 train()
中删除 metric="ROC"
,则代码可以正常工作 . 但是,在我的情况下, "ROC"
指标是我对比最佳模型的度量标准,因此我尝试使用"ROC" metric Build 模型 .
EDIT :代码示例:
# 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", "1"
之外,还必须使用除了因子变量Y
之外的其他值 .在构建数据帧之后,您可以通过至少两种方式执行此操作
df
;第一个是暗示错误消息,即使用make.names
:第二种方法是使用
levels
函数,通过该函数您可以明确控制名称本身;再次在这里显示名称X0
和X1
添加上述任一行之后,显示的
train()
代码将顺利运行(用df
替换training
),但它仍然不会产生任何ROC值,而是提供警告:这将我们带到第二个问题:为了使用ROC指标,你必须在
train()
的trControl
参数中添加summaryFunction = twoClassSummary
:使用您提供的玩具数据运行上面的代码段仍会出现错误(缺少ROC值),但这可能是由于此处使用的非常小的数据集与大量CV折叠相结合,并且不会发生在您自己的情况下,完整数据集(如果我将CV折叠减少到
number=3
,它可以正常工作)...