每次我 运行 RandomForestRegressor 得到不同的结果

Getting different results each time I run RandomForestRegressor

我使用这段代码希望实现确定性:

from sklearn.ensemble import RandomForestRegressor
np.random.seed(0)
import random
random.seed(0)

rf = RandomForestRegressor(n_estimators=1000, criterion='mse', min_samples_leaf=4)

但我的结果不是确定性的。为什么会这样,我该如何解决?

RandomForestRegressor中使用random_state参数:

from sklearn.ensemble import RandomForestRegressor

rf = RandomForestRegressor(n_estimators=1000, criterion='mse', min_samples_leaf=4, 
                           random_state= 0)

这应该return每次都得到相同的结果。


Scikit-learn does not use its own global random state; whenever a RandomState instance or an integer random seed is not provided as an argument, it relies on the numpy global random state, which can be set using numpy.random.seed


也就是说,添加 np.random.seed() 之前 导入 RandomForestRegressor 也应该可以做到。

来源:http://scikit-learn.org/stable/faq.html#how-do-i-set-a-random-state-for-an-entire-execution