我试图比较使用R和Python的随机森林模型的结果。我比较的模型性能的关键度量是AUC(ROC曲线下的面积)。原因是AUC值代表了预测值(即概率)的分布。我确实发现了R和Python在AUC值上的一些显著差异。关于R和Python之间的差异,我确实通读了一些关于堆栈溢出的相关问题和答案。但是,我觉得我的问题应该和那些不同。在
我试图在R和Python中保持一些关键的超参数不变。它们是:
ntree
设置为Python中的n_estimators
mtry
设置为max_features
nodesize
设置为Python中的min_samples_leaf
NULL
。在Python中,默认值是None
。在replace
设置为bootstrap
,即两者都是True
,或者两者都是{该问题是一个两类分类问题,有86个预测因子。每个预测因子都是连续的或布尔的。在R中没有使用因子类型预测因子。训练数据中有2008个观察值,测试数据中有335个观察值。两组数据的有效率相同,为79.7%。在
结果如下:
R的模型1结果training_auc=0.9249080
,test_auc=0.6308934
R的模型2结果training_auc=0.9245665
,test_auc=0.6364838
Python中的模型1结果training_auc=0.80515863
,test_auc=0.62194316
Python中的模型2结果training_auc=0.86075733
,test_auc=0.61522362
您可以发现R和Python之间的模型2(非引导抽样)中AUC值的差异比模型1(bootstrap采样)中小,尤其是在训练数据的AUC中。在
我的问题是:
为什么即使我在R和Python中设置了相同的超参数,训练数据的AUC会有如此巨大的差异?
我错过了什么重要的参数吗?或者我的R或Python代码有错误吗?
如何在R中使用classwt
,在Python中如何使用class_weight
?
library(randomForest)
library(glmnet)
setwd("D:/Project Files2/Python Efficiency/test RF using another dataset")
#read in data for training and data for testing
X_train01 <- read.csv("X_train_0.csv",header=FALSE)
y_train01 <- read.csv("y_train_0.csv",header=FALSE)
colnames(y_train01) <- "response"
X_test01 <- read.csv("X_test_0.csv",header=FALSE)
y_test01 <- read.csv("y_test_0.csv", header=FALSE)
colnames(y_test01) <- "response"
#define a function for RF
run_quick_rf4 <- function(X_train01,y_train01, X_test01, y_test01, ntree, mtry, nodesize, maxnodes=NULL, replace=TRUE, classwt=NULL, rnd_seed= 12345){
set.seed(rnd_seed)
rf_model <- randomForest(x=X_train01,y=as.factor(y_train01[,1]),
ntree=ntree,
mtry= mtry,
nodesize= nodesize,
maxnodes= maxnodes,
replace = replace,
sampsize = nrow(X_train01),
classwt = classwt
)
train01_pred <- predict(rf_model, X_train01, type='prob')
train01_auc <- auc(y_train01[,1], train01_pred[,2])
test01_pred <- predict(rf_model, X_test01, type='prob')
test01_auc <- auc(y_test01[,1],test01_pred[,2])
auc_outcome<- c(train01_auc, test01_auc)
names(auc_outcome)<- c("training_auc", "test_auc")
return(auc_outcome)
}
#>>>>>>>>>>>>>>>>>>>>>>>>>End of this function>>>>>>>>>>>>>>>>>>
#run random forest models with parameters set.
#Model 1
run_quick_rf4(X_train01, y_train01, X_test01, y_test01, 500, 20, 20, maxnodes=NULL, replace=TRUE, classwt=NULL, rnd_seed= 12345)
#Model 2
run_quick_rf4(X_train01, y_train01, X_test01, y_test01, 500, 20, 20, maxnodes=NULL, replace=FALSE, classwt=NULL, rnd_seed= 12345)
目前没有回答
相关问题 更多 >
编程相关推荐