如何在cross_val_score中使用random_state

每次运行得到不同的值。我在这里做错了什么?

import numpy as npfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import StratifiedKFold, cross_val_scoreX = np.random.random((100,5))y = np.random.randint(0,2,(100,))cross_val_score = RandomForestClassifier()cv = StratifiedKFold(y, random_state=1)s = cross_val_score(cross_val_score, X, y,scoring='roc_auc', cv=cv)print(s)# [ 0.42321429  0.44360902  0.34398496]s = cross_val_score(cross_val_score, X, y, scoring='roc_auc', cv=cv)print(s)# [ 0.42678571  0.46804511  0.36090226]

回答:

您犯的错误是调用了RandomForestClassifier,它的默认参数random_state是None。因此,它会使用np.random生成的种子来产生随机输出。

StratifiedKFoldRandomForestClassifier中,random_state需要相同,才能产生相同的交叉验证得分数组。

示例说明:

X=np.random.random((100,5))y=np.random.randint(0,2,(100,))clf = RandomForestClassifier(random_state=1)cv = StratifiedKFold(y, random_state=1)        # 在这里设置random_state不是必须的s = cross_val_score(clf, X,y,scoring='roc_auc', cv=cv)print(s)##[ 0.57612457  0.29044118  0.30514706]print(s)##[ 0.57612457  0.29044118  0.30514706]

另一种解决方法是不为RFC和SKF提供random_state参数,而只是在开始时使用np.random.seed(value)来创建随机整数。这样也能在输出中产生相同的数组。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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