我能够使用我给出的一些R代码成功运行RF模型。这是下面的,它也包括我的数据片段。
唯一的问题是编写代码的方式只输出概率向量而没有来自原始测试数据集的数据,称为“testset”。所以现在我想弄清楚如何输出我的概率和原始数据框,因为我无法在线找到解决方案。换句话说,我希望它是数据集中的另一列,就像在我的FLSAStat列之后。那就是我可以将它们全部输出到一个csv文件。
这就是我所拥有的:
#####################################################
# 1. SETUP DATA
#####################################################
mydata <- read.csv("train_test.csv", header=TRUE)
colnames(testset)
[1] "train" "Target" "ApptCode" "Directorate" "New_Discipline" "Series" "Adjusted.Age"
[8] "Adj.Service" "Adj.Age.Service" "HiEducLv" "Gender" "RetCd" "FLSAStat"
> head(testset)
train Target ApptCode Directorate New_Discipline Series Adjusted.Age Adj.Service Adj.Age.Service HiEducLv Gender
5909 0 NA IN Business Math Computer Science IT PSTS 54.44 10 64.44 Bachelor Male
5910 0 NA IN Computation Math Computer Science IT PSTS 51.51 15 66.51 Bachelor Male
5911 0 NA IN Physical and Life Sciences Physics PSTS 40.45 5 45.45 PHD Male
5912 0 NA IN Weapons and Complex Integ Physics PSTS 62.21 35 97.21 PHD Male
5913 0 NA IN Weapons and Complex Integ Physics PSTS 45.65 15 60.65 PHD Male
5914 0 NA FX Physical and Life Sciences Physics PSTS 36.13 5 41.12 PHD Male
RetCd FLSAStat
5909 TCP2 E
5910 TCP2 E
5911 TCP2 E
5912 TCP2 E
5913 TCP1 E
5914 TCP2 E
#create train and test sets
trainset = mydata[mydata$train == 1,]
testset = mydata[mydata$train == 0,]
#eliminate unwanted columns from train set
trainset$train = NULL
#####################################################
# 2. set the formula
#####################################################
theTarget <- "Target"
theFormula <- as.formula(paste("as.factor(",theTarget, ") ~ . "))
theFormula1 <- as.formula(paste(theTarget," ~ . "))
trainTarget = trainset[,which(names(trainset)==theTarget)]
testTarget = testset[,which(names(testset)==theTarget)]
#####################################################
# Random Forest
#####################################################
library(randomForest)
what <- "Random Forest"
FOREST_model <- randomForest(theFormula, data=trainset, ntree=500)
train_pred <- predict(FOREST_model, trainset, type="prob")[,2]
test_pred <- predict(FOREST_model, testset, type="prob")[,2]
display_results()
testID <- testset$case_id
predictions <- test_pred
submit_file = cbind(testID,predictions)
write.csv(submit_file, file="RANDOM4.csv", row.names = FALSE)
我认为问题在于我缺少额外的代码行来将预测向量合并回testSet。我猜这会在第三行到最后一行代码之前的某个地方。
答案 0 :(得分:0)
只需将列添加到数据框中,如下所示:
testset$Predictions <- test_pred
write.csv(testset, file="RANDOM4.csv", row.names = FALSE)