cross_val_score 在 sklearn 中使用不同的分类器表现不同
cross_val_score behaves differently with different classifiers in sklearn
我在 sklearn
中使用 cross_val_score()
时遇到一些困难。
我已经使用以下代码实例化了一个 KNeighborsClassifier
:
clf = KNeighborsClassifier(n_neighbors=28)
然后我使用交叉验证来了解这个分类器在我的 df
特征 (x
) 和目标系列 (y
) 上的准确性:
cv_score_av = np.mean(cross_val_score(clf, x, y, cv=5))
每次我 运行 我希望获得不同结果的脚本,但是没有像 RandomForestClassifier()
那样设置 random_state=None
的选项。有没有办法用每个 运行 获得不同的结果,或者我是否必须在 运行 宁 cross_val_score
之前在我的 KNeighborsClassifier
模型上手动随机随机排列我的数据。
你这边好像有什么误解;随机森林中的 random_state
参数指的是算法本身,而不是交叉验证部分。这样的论点在这里是必要的,因为 RF 在模型构建中确实包含了一些随机性(lot,事实上,正如算法名称所暗示的那样);但相比之下,knn 是一种确定性算法,因此原则上不需要使用任何 random_state
.
也就是说,你的问题确实有道理;我有 in the past on this annoying and inconvenient absence of a shuffling argument in cross_val_score
. Digging into the documentation,我们看到在引擎盖下,该函数使用 StratifiedKFold
或 KFold
来构建折叠:
cv : int, cross-validation generator or an iterable, optional
For integer/None inputs, if the estimator is a classifier and y
is either binary or multiclass, StratifiedKFold
is used. In all other cases, KFold
is used.
以及这两个函数,正如您可以从链接的文档页面中轻松看到的那样,使用 shuffle=False
作为默认值。
无论如何,解决方案很简单,只需要增加一行代码;您只需要将 cv=5
替换为对先前定义的 StratifiedKFold
对象的调用 shuffle=True
:
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True)
cv_score_av = np.mean(cross_val_score(ml_10_knn, x, y, cv=skf))
我在 sklearn
中使用 cross_val_score()
时遇到一些困难。
我已经使用以下代码实例化了一个 KNeighborsClassifier
:
clf = KNeighborsClassifier(n_neighbors=28)
然后我使用交叉验证来了解这个分类器在我的 df
特征 (x
) 和目标系列 (y
) 上的准确性:
cv_score_av = np.mean(cross_val_score(clf, x, y, cv=5))
每次我 运行 我希望获得不同结果的脚本,但是没有像 RandomForestClassifier()
那样设置 random_state=None
的选项。有没有办法用每个 运行 获得不同的结果,或者我是否必须在 运行 宁 cross_val_score
之前在我的 KNeighborsClassifier
模型上手动随机随机排列我的数据。
你这边好像有什么误解;随机森林中的 random_state
参数指的是算法本身,而不是交叉验证部分。这样的论点在这里是必要的,因为 RF 在模型构建中确实包含了一些随机性(lot,事实上,正如算法名称所暗示的那样);但相比之下,knn 是一种确定性算法,因此原则上不需要使用任何 random_state
.
也就是说,你的问题确实有道理;我有 cross_val_score
. Digging into the documentation,我们看到在引擎盖下,该函数使用 StratifiedKFold
或 KFold
来构建折叠:
cv : int, cross-validation generator or an iterable, optional
For integer/None inputs, if the estimator is a classifier and
y
is either binary or multiclass,StratifiedKFold
is used. In all other cases,KFold
is used.
以及这两个函数,正如您可以从链接的文档页面中轻松看到的那样,使用 shuffle=False
作为默认值。
无论如何,解决方案很简单,只需要增加一行代码;您只需要将 cv=5
替换为对先前定义的 StratifiedKFold
对象的调用 shuffle=True
:
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True)
cv_score_av = np.mean(cross_val_score(ml_10_knn, x, y, cv=skf))