Python sklearn RandomForestClassifier 结果不可重现

我一直在使用 sklearn 的随机森林,并尝试比较几个模型。然后我注意到,即使使用相同的种子,随机森林也会给出不同的结果。我尝试了两种方法:random.seed(1234) 以及使用随机森林内置的 random_state = 1234。在这两种情况下,我得到的结果都无法重复。我错过了什么…?

# 1random.seed(1234)RandomForestClassifier(max_depth=5, max_features=5, criterion='gini', min_samples_leaf = 10)# or 2RandomForestClassifier(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)# 如描述,我尝试了几种方式使用 random_state,结果还是不同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() 更可取。


回答:

首先确保你有最新版本的所需模块(例如 scipy、numpy 等)。你输入random.seed(1234)时,你使用的是numpy生成器。


当你在RandomForestClassifier中使用random_state参数时,有几种选择:整数RandomState 实例None


这里的文档中可以看到:

  • 如果是整数,random_state 是随机数生成器使用的种子;

  • 如果是 RandomState 实例,random_state 就是随机数生成器;

  • 如果是 None,随机数生成器是 np.random 使用的 RandomState 实例。


在两种情况下使用同一个生成器的方法如下。 我在这两种情况下使用同一个(numpy)生成器,并且我得到了可重现的结果(两种情况下的结果相同)。

from sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import make_classificationfrom numpy import *X, y = make_classification(n_samples=1000, n_features=4,                       n_informative=2, n_redundant=0,                       random_state=0, shuffle=False)random.seed(1234)clf = RandomForestClassifier(max_depth=2)clf.fit(X, y)clf2 = RandomForestClassifier(max_depth=2, random_state = random.seed(1234))clf2.fit(X, y)

检查结果是否相同:

all(clf.predict(X) == clf2.predict(X))#True

在运行相同代码5次后检查:

from sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import make_classificationfrom numpy import *for i in range(5):    X, y = make_classification(n_samples=1000, n_features=4,                       n_informative=2, n_redundant=0,                       random_state=0, shuffle=False)    random.seed(1234)    clf = RandomForestClassifier(max_depth=2)    clf.fit(X, y)    clf2 = RandomForestClassifier(max_depth=2, random_state = random.seed(1234))    clf2.fit(X, y)    print(all(clf.predict(X) == clf2.predict(X)))

结果:

TrueTrueTrueTrueTrue

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注