预测错误 - ROCR包(使用概率)

问题描述 投票:0回答:1

我已经使用svm的“rfe”函数来创建具有减少功能的模型。然后我在测试数据上使用“预测”,输出类标签(二进制),0类概率,1类概率。然后我尝试在ROCR包中使用预测函数预测概率和真实类标签,但得到以下错误并且不确定为什么因为2个数组的长度相等:

> pred_svm <- prediction(pred_svm_2class[,2], as.numeric(as.character(y)))
Error in prediction(pred_svm_2class[, 2], as.numeric(as.character(y))) : 
Number of predictions in each run must be equal to the number of labels for each run.

我有下面的代码,输入在这里click me.It是一个二进制分类的小数据集,因此代码运行速度很快。

library("caret")
library("ROCR")
sensor6data_2class <- read.csv("/home/sensei/clustering/svm_2labels.csv")
sensor6data_2class <- within(sensor6data_2class, Class <- as.factor(Class))

set.seed("1298356")
inTrain_svm_2class <- createDataPartition(y = sensor6data_2class$Class, p = .75, list = FALSE)
training_svm_2class <- sensor6data_2class[inTrain_svm_2class,]
testing_svm_2class <- sensor6data_2class[-inTrain_svm_2class,]
trainX <- training_svm_2class[,1:20]
y <- training_svm_2class[,21]

ctrl_svm_2class <- rfeControl(functions = rfFuncs , method = "repeatedcv", number = 5, repeats = 2, allowParallel = TRUE)
model_train_svm_2class <- rfe(x = trainX, y = y, data = training_svm_2class, sizes = c(1:20), metric = "Accuracy", rfeControl = ctrl_svm_2class, method="svmRadial")

pred_svm_2class = predict(model_train_svm_2class, newdata=testing_svm_2class)
pred_svm <- prediction(pred_svm_2class[,2], y)

谢谢,感谢您的帮助。

r roc
1个回答
3
投票

这是因为在线

pred_svm <- prediction(pred_svm_2class[,2], y)

pred_svm_2class [,2]是对测试数据的预测,y是训练数据的标签。只需在像这样的单独变量中生成测试标签

y_test <- testing_svm_2class[,21]

现在,如果你这样做

pred_svm <- prediction(pred_svm_2class[,2], y_test)

没有错误。完整代码如下 -

# install.packages("caret")
# install.packages("ROCR")
# install.packages("e1071")
# install.packages("randomForest")
library("caret")
library("ROCR")
sensor6data_2class <- read.csv("svm_2labels.csv")
sensor6data_2class <- within(sensor6data_2class, Class <- as.factor(Class))

set.seed("1298356")
inTrain_svm_2class <- createDataPartition(y = sensor6data_2class$Class, p = .75, list = FALSE)
training_svm_2class <- sensor6data_2class[inTrain_svm_2class,]
testing_svm_2class <- sensor6data_2class[-inTrain_svm_2class,]
trainX <- training_svm_2class[,1:20]
y <- training_svm_2class[,21]
y_test <- testing_svm_2class[,21]

ctrl_svm_2class <- rfeControl(functions = rfFuncs , method = "repeatedcv", number = 5, repeats = 2, allowParallel = TRUE)
model_train_svm_2class <- rfe(x = trainX, y = y, data = training_svm_2class, sizes = c(1:20), metric = "Accuracy", rfeControl = ctrl_svm_2class, method="svmRadial")

pred_svm_2class = predict(model_train_svm_2class, newdata=testing_svm_2class)
pred_svm <- prediction(pred_svm_2class[,2], y_test)
© www.soinside.com 2019 - 2024. All rights reserved.