问题描述
作为一项学习练习,我正在尝试手动编写代码(用R编写),以将不同的机器学习模型“堆叠”(集成)在一起(目标是二进制响应分类)。我已经从R中获取了流行的“声纳”数据集:首先,我获取了一些训练数据,并将其输入到“随机森林”算法以及“ ada boost”算法中。我从这两种算法获得输出概率,然后将其提供给“ xgboost”算法进行最终预测。由于某种原因,这导致模型的训练误差为0。这不对。
有人可以告诉我我做错了什么,如何解决此问题?我在下面附加了我的代码。
library (mlbench)
library (randomForest)
library(ada)
library(xgboost)
library(caret)
数据(声纳)
index = createDataPartition(y=Sonar$Class,p=0.75,list=FALSE)
train_set = Sonar[index,]
test_set = Sonar[-index,]
########Fit Random Forest
model_rf = randomForest(Class~.,train_set,mtry = 12,ntree=500,prob=TRUE)
model_rf
####### Fit ada model
model_ada = ada(train_set[,-61],train_set$Class,nu=0.01,iter = 100,type="discrete")
model_ada
######### Predict on train data
pred_train_rf = predict(model_rf,train_set[,type="prob")
pred_train_ada = predict(model_ada,type="prob")
######### Append predicted probabilities to the trainset : for class "M"
train_set$pred_rf = pred_train_rf[,1]
train_set$pred_ada = pred_train_ada[,1]
############# Fit xgboost model on the predicted probabilities of earlier two models
data_matrix <- as.matrix(train_set[,c(62:63)])
output_vector = as.vector(ifelse(train_set$Class == "M",1,0))
model_xgboost <- xgboost(data = data_matrix,label = output_vector,max.depth = 2,eta = 1,nthread = 2,nrounds = 10,objective = "binary:logistic")
#########################################
[1] train-error:0.000000
[2] train-error:0.000000
[3] train-error:0.000000
[4] train-error:0.000000
[5] train-error:0.000000
[6] train-error:0.000000
[7] train-error:0.000000
[8] train-error:0.000000
[9] train-error:0.000000
[10] train-error:0.000000
谢谢。
解决方法
这里的行为是意外的。 RandomForest总是过度适合训练数据。
您可以通过在训练数据上计算出RF模型的准确性来看到这一点。
model_rf = randomForest(Class~.,train_set,mtry = 12,ntree=500,prob=TRUE)
mean(predict(model_rf,data = train_set) == train_set$Class)
几乎每次您运行代码时,它都是100%准确的。因此,如果我是对的,那么您或多或少都使用Class来预测xgboost代码中的Class。
您需要做的是稍微更改工作流程。代替使用data_matrix
的训练数据,请使用test_data。那应该做的。您还需要编写一个循环并多次执行此操作,以获得更现实的可预测性,因为小的数据集在任何精度测量中都可能导致大量噪声。