r - train() 中的 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).
我不明白“使用可用作有效 R 变量名称的因子级别”是什么意思。因变量Y
已经是一个因素,但不是有效的 R 变量名称?
PS:如果您classProbs=TRUE
在. 但是,该指标是我比较最佳模型的指标,因此我正在尝试使用“ROC”指标制作模型。trainControl()
metric="ROC"
train()
"ROC"
编辑:代码示例:
# 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)
解决方案
这里有两个不同的问题。
第一个是错误消息,它说明了一切:您必须使用其他东西而不是您的因因素变量"0", "1"
的值Y
。
构建数据框后,您至少可以通过两种方式执行此操作df
;第一个提示错误消息,即使用make.names
:
df$Y <- make.names(df$Y)
df$Y
# "X1" "X1" "X1" "X0" "X0"
第二种方法是使用levels
函数,通过它您可以明确控制名称本身;在这里再次显示它的名字X0
和X1
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
以下trControl
参数train()
:
model_nn <- train(
Y ~ ., df,
method = "nnet",
metric="ROC",
trControl = trainControl(
method = "cv", number = 10,
verboseIter = TRUE,
classProbs=TRUE,
summaryFunction = twoClassSummary # ADDED
)
)
使用您提供的玩具数据运行上述代码段仍然会出现错误(缺少 ROC 值),但这可能是由于此处使用的数据集非常小加上大量 CV 折叠,而您自己的数据不会发生这种情况,完整数据集(如果我将 CV 折叠减少到 ,它可以正常工作number=3
)...
推荐阅读
- java - 如何用箭头键移动圆圈?
- javascript - 在另一个函数内更改 settimeout 内的变量
- python - 如何传递参数(元组) - 不同的长度
- javascript - Firestore 使用 2 次读取来添加带有时间戳的文档
- maven - Eclipse RCP:清理和更新 Maven
- keras - 之后具有多个密集层的堆叠 LSTM
- php - 如何使用按钮更改页面 URL
- python - 尝试从外部脚本更新进度条时,QWidget 变得无响应
- symfony - Symfony 编译错误无法打开所需的代理
- asp.net-core - ASP.NET CORE MVC 项目中未显示字体真棒图标