随机森林:R和Python之间的特异性结果不同

时间:2019-12-10 17:12:34

标签: python r statistics random-forest

我的问题如下:我想对医学数据进行二元预测,但要约束其假阴性为0->我不想错过任何阳性观察结果。

我设法做到的方法是获得随机森林的预测概率,并在训练数据中设置等于我的阳性观察结果的最小随机森林概率的阈值。

有了这个阈值,我可以为每个人预测,从而得到我的困惑矩阵。从逻辑上讲,我的敏感度始终为1,而挑战是优化RF以增加我的特异性。

现在这是我的主要工作:我尽力将相同的模型放在R和Python中进行测试,我尝试为每个参数设置相同的值;但是我的专一性在两个软件之间平均差为0.7。

我使用“留一法”评估每个观察结果,并获得“ predict_proba”(在python中)或投票(在“ R”中)。

我补充说,我对这两个模型都运行了几次,我们可以观察到两个软件的结果相当一致,而且两者之间的差异也肯定是一致的。

我很难理解差异的来源。

使用的软件包:Python scikit-learn随机森林,R randomForest

这里是留一法和RF的两个代码:

“”“

from sklearn.model_selection import LeaveOneOut
from sklearn.ensemble import RandomForestClassifier

loo = LeaveOneOut()
loo.get_n_splits(X.index)

parametres = {'oob_score':False,
          'n_estimators':1500,
          'max_features':5, 
          'min_samples_leaf':5, 
          'max_leaf_nodes':50}
random_forest = RandomForestClassifier(**parametres)

y_score = []

# X is the dataFrame of my training data
# y is the dataFrame of my response variable

for train_index, test_index in loo.split(X):
   X_train, X_test, y_train = X.iloc[train_index], X.iloc[test_index],y.iloc[train_index]
   random_forest.fit(X_train, y_train)
   y_score.append(random_forest.predict_proba(X_test)[0][1])

“”“
这导致我得到以下结果:

[537 257]

[0 64]

灵敏度:1.0

特异性:0.6763224181360201

'''

# dw is the table with all my data
# param_opt_rf1 are my parameters : $classwt 1 1 ; $mtry 5 ; $ntree 1500 ; $nodesize 5 ; $maxnodes 50


n <- nrow(dw)
pred_loo_rf1=rep(0,n)
for(i in 1:n){ 
  id_test = i
  rf1 = do.call(randomForest, c(list(x = dw[-id_test,-c(1)], y = dw[-id_test,c(1)],
                                 xtest = dw[id_test,-c(1)], ytest = dw[id_test,c(1)]), param_opt_rf1))

 pred_loo_rf1[i] = rf1$test$votes[,2]
}

pr_loo_rf1=prediction(c(pred_loo_rf1,rep(0,nrow(d)-nrow(dw))), 
                  d[c(which(row.names(d)%in%row.names(dw)),
                      which(!row.names(d)%in%row.names(dw))), "y"])
perf_loo_rf1 <- performance(pr_loo_rf1,"tpr","fpr")

seuil_loo_rf1         <- min(pred_loo_rf1[which(dw$y==1)])
result_loo.rf1        <- ifelse(pred_loo_rf1 >= seuil_loo_rf1,1,0)



final_seuil_loo_rf1       <- max(pred_loo_rf1[which(result_loo.rf1==0)])

vp_loo_rf1 <- sum(pred_loo_rf1[dw$y == 1] > max(pred_loo_rf1[which(result_loo.rf1==0)]))
vn_loo_rf1 <- sum(pred_loo_rf1[dw$y == 0] < min(pred_loo_rf1[dw$y == 1])) + sum(d$ddi < 0.495)
fp_loo_rf1 <- sum(pred_loo_rf1[dw$y == 0] > max(pred_loo_rf1[which(result_loo.rf1==0)]))
fn_loo_rf1 <- sum(pred_loo_rf1[dw$y == 1] < min(pred_loo_rf1[dw$y == 1]))

table_loo_rf1 <- as.table(matrix(c(vp_loo_rf1,fp_loo_rf1,fn_loo_rf1,vn_loo_rf1), nrow = 2, byrow = TRUE))

'''

哪个引导我到结果:

589 205

0 64

特异性:0.7418136

结果如何如此不同?

任何帮助将不胜感激。

0 个答案:

没有答案
相关问题