【问题标题】:Confused about random_state in sklearn对 sklearn 中的 random_state 感到困惑
【发布时间】: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


【解决方案1】:

我无法重现该问题。对我来说,当我使用以下方法生成一些数据时,多次运行的变量重要性确实保持不变:

X, y = make_classification(n_samples=1000,
                       n_features=10,
                       n_informative=3,
                       n_redundant=0,
                       n_repeated=0,
                       n_classes=2,
                       random_state=0,
                       shuffle=False)
X = pd.DataFrame(X)

通过选择前 750 个 y/X 数据点将数据更改为具有不均匀的权重也不会导致重要性差异。

你使用什么数据?

【讨论】:

  • 不幸的是,数据是机密的(客户)。我以前从未遇到过,这就是我在这里发布问题的原因。
  • 嗯.. 你能用我上面生成的数据重现你的问题吗?你用的是什么版本的 sklearn?
猜你喜欢
  • 2017-01-02
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2012-07-22
  • 2013-05-13
  • 2020-04-16
  • 2023-03-08
相关资源
最近更新 更多