gpt4 book ai didi

Python sklearn RandomForestClassifier 不可重现的结果

转载 作者:行者123 更新时间:2023-11-28 22:22:51 32 4
gpt4 key购买 nike

我一直在使用 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()。

最佳答案

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


当您在 RandomForestClassifier 中使用 random_state 参数时,有几个选项:intRandomState instance


来自文档 here :

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

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

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


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

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from 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 RandomForestClassifier
from sklearn.datasets import make_classification
from 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)))

结果:

True
True
True
True
True

关于Python sklearn RandomForestClassifier 不可重现的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47433920/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com