R RandomForest分类-测试数据没有预测价值

R RandomForest classification- test data does not have the value to predict

我正在尝试使用 R 中的随机森林进行分类 我有一个 complexityFlag 为 1 或 0 的训练数据集,我正在使用随机森林在数据集上训练我的模型:

model1 <- randomForest(as.factor(ComplexityFlag) ~ ContractTypeCode + IndustryLevel2Description + ClaimantAgeAtDisability + Sex, data = data, ntree = 200, importance=TRUE)

然后我想要 运行 针对我的测试数据集的模型,但我的测试数据集没有 ComplexityFlag。我希望模型预测 ComplexityFlag 像这样:

test$ComplexityFlag <- as.data.frame(predict(model1, newdata = test, type = "class"))

如何计算 ROC 我使用的方法正确吗

对于 ROC 曲线,您可以使用 pROC 包。您只需要确保 predictionsas.numeric().

这里我用一个例子来展示,我用 iris 数据重现了一个二元分类问题。

data <- iris

# change the problem to a binary classifier (setosa or not setosa)
data$bin_response <- as.factor(ifelse(data$Species=="setosa", 1, 0))
data <- data[, -5] # remove "Species"

set.seed(123)

train_test <- sample(150, 100, replace = F) # we sample casually 100 values for the train

# split train-test data
train <- data[train_test, ]
test <- data[-train_test, ]

现在模型和曲线:

# - model
library(randomForest)

rf_mod <- randomForest(bin_response ~ ., data=train)

# make pred on test data
predictions <- predict(rf_mod, newdata = test[, -5]) # note we remove the "bin_response" col
head(predictions) # lets look at them to check if it's fine
# 2  4 10 13 19 21 
# 1  1  1  1  1  1 
# Levels: 0 1

# now the ROC curve
library(pROC)

roc_result <- roc(test$bin_response, as.numeric(predictions))# Draw ROC curve.
plot(roc_result, print.thres="best", print.thres.best.method="closest.topleft")