【发布时间】:2019-01-18 08:17:47
【问题描述】:
所以,基本上,我使用 RF 进行描述性建模,如下所示:
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight('balanced', np.unique(y), y)
class_weights = dict(enumerate(class_weights))
class_weights
{0: 0.5561096747856852, 1: 4.955559597429368}
clf = RandomForestClassifier(class_weight=class_weights, random_state=0)
cross_val_score(clf, X, y, cv=10, scoring='f1').mean()
并将变量重要性绘制为:
import matplotlib.pyplot as plt
def plot_importances(clf, features, n):
importances = clf.feature_importances_
indices = np.argsort(importances)[::-1]
if n:
indices = indices[:n]
plt.figure(figsize=(10, 5))
plt.title("Feature importances")
plt.bar(range(len(indices)), importances[indices], align='center')
plt.xticks(range(len(indices)), features[indices], rotation=90)
plt.xlim([-1, len(indices)])
plt.show()
return features[indices]
imp = plot_importances(clf, X.columns, 30)
我希望变量重要性在多次运行中相同。但是,每当我重新运行笔记本时,它们的重要性都会发生变化。
我不明白为什么会这样。是不是和cross_val_score方法有关?
【问题讨论】:
-
cross_val_score将使用同样依赖于random_state的 StratifiedKFold 拆分数据,因此它会影响到达 RandomForest 的数据,因此分数会发生变化。 -
StatifiedKFold 的默认值为
shuffle=False,而random_state仅在shuffle=True时使用,所以不确定是不是这个问题。
标签: python random scikit-learn random-forest cross-validation