【发布时间】:2018-05-06 03:30:00
【问题描述】:
我一直在使用 sklearn 的随机森林,并尝试比较几个模型。然后我注意到即使 使用相同的种子,随机森林也会给出不同的结果。我尝试了两种方式:random.seed(1234) 以及使用随机森林内置 random_state = 1234 在这两种情况下,我都会得到不可重复的结果。我错过了什么……?
# 1
random.seed(1234)
RandomForestClassifier(max_depth=5, max_features=5, criterion='gini', min_samples_leaf = 10)
# or 2
RandomForestClassifier(max_depth=5, max_features=5, criterion='gini', min_samples_leaf = 10, random_state=1234)
有什么想法吗?谢谢!!
编辑: 添加我的代码的更完整版本
clf = RandomForestClassifier(max_depth=60, max_features=60, \
criterion='entropy', \
min_samples_leaf = 3, random_state=seed)
# As describe, I tried random_state in several ways, still diff results
clf = clf.fit(X_train, y_train)
predicted = clf.predict(X_test)
predicted_prob = clf.predict_proba(X_test)[:, 1]
fpr, tpr, thresholds = metrics.roc_curve(np.array(y_test), predicted_prob)
auc = metrics.auc(fpr,tpr)
print (auc)
编辑:已经有一段时间了,但我认为使用RandomState 可能会解决问题。我自己还没有测试它,但如果你正在阅读它,它值得一试。此外,通常最好使用 RandomState 而不是 random.seed()。
【问题讨论】:
-
在第二次调用随机森林分类器之前是否也调用了相同的随机种子?你也可以展示你的不同结果吗?
-
如果我的回答解决了您的问题,请告诉我
-
第一次跑(1)几次,计算predict和ROC/AUC。每次都给出不同的结果。然后我做了同样的事情,使用方法(2),结果仍然无法重现。然后我使用了第三种方法,正如@sera 建议的那样,仍然没有乐趣。对于所有其他方法(逻辑回归、LDA、朴素贝叶斯),我得到了完全相同的结果。
-
一些例子:在同一个种子下得到的AUC为:0.779396, 0.794945
标签: python random random-forest reproducible-research