【问题标题】:Find random state of sklearn decision tree classifier查找 sklearn 决策树分类器的随机状态
【发布时间】:2014-03-12 17:47:47
【问题描述】:

我有一些数据适合sklearn DecisionTreeClassifier。因为分类器使用了一点随机性,所以我运行了几次并保存了最好的模型。但是我希望能够重新训练数据并在不同的机器上获得相同的结果。

在我为每个分类器训练模型后,有没有办法找出最初的 random_state 是什么?

EDIT sklearn 模型有一个名为 get_params() 的方法,它显示输入是什么。但是对于random_state,它仍然显示None。但是根据文档,在这种情况下,它使用numpy 来产生一个随机数。我想弄清楚那个随机数是什么

【问题讨论】:

  • 在线文档表明默认 random_stateNone 所以这看起来是正确的,请参阅:scikit-learn.org/stable/modules/generated/…
  • 我知道这是默认使用,我要问的是当我使用random_state=None并且我拟合模型时,拟合后有没有办法找出@987654332的结果@是?

标签: python scikit-learn decision-tree


【解决方案1】:

您必须将显式随机状态传递给 d-tree 构造函数:

>>> DecisionTreeClassifier(random_state=42).get_params()['random_state']
42

将其保留为默认值None 意味着fit 方法将使用numpy.random 的单例随机状态,这是不可预测的,并且在运行中也不相同。

【讨论】:

  • 也许我的问题措辞不正确。我想知道的是,如果我使用了random_state=None,并且它应该使用numpy.random,有没有办法在模型适合了解numpy.random 的结果后找出?
  • @sedavidw:在这种情况下,答案是“那是不可能的”。
【解决方案2】:

我建议您最好为此目的使用随机森林 - 随机森林包含许多基于预测变量子集建模的树。 然后,您只需使用RandomForestVariableName.estimators_即可查看模型中已使用的random_states

我将在这里使用我的代码作为示例:

with open('C:\Users\Saskia Hill\Desktop\Exported\FinalSpreadsheet.csv', 'rb') as csvfile:
    titanic_reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    row = titanic_reader.next()
    feature_names = np.array(row)

    # Load dataset, and target classes
    titanic_X, titanic_y = [], []
    for row in titanic_reader:  
    titanic_X.append(row)
    titanic_y.append(row[11]) # The target values are your class labels

    titanic_X = np.array(titanic_X)
    titanic_y = np.array(titanic_y)
    print titanic_X, titanic_y

print feature_names, titanic_X[0], titanic_y[0]
titanic_X = titanic_X[:, [2,3,4,5,6,7,8,9,10]] #these are your predictors/ features
feature_names = feature_names[[2,3,4,5,6,7,8,9,10]]

from sklearn import tree

rfclf = RandomForestClassifier(criterion='entropy', min_samples_leaf=1,  max_features='auto', max_leaf_nodes=None, verbose=0)

rfclf = rfclf.fit(titanic_X,titanic_y)

rfclf.estimators_     #the output for this is pasted below:

[DecisionTreeClassifier(compute_importances=None, criterion='entropy',
        max_depth=None, max_features='auto', max_leaf_nodes=None,
        min_density=None, min_samples_leaf=1, min_samples_split=2,
        random_state=1490702865, splitter='best'),
DecisionTreeClassifier(compute_importances=None, criterion='entropy',
        max_depth=None, max_features='auto', max_leaf_nodes=None,
        min_density=None, min_samples_leaf=1, min_samples_split=2,
        random_state=174216030, splitter='best') ......

因此,随机森林将随机性引入到决策树文件中,并且不需要对决策树使用的初始数据进行调整,但它们充当交叉验证的方法,让您对数据的准确性更有信心(特别是如果像我一样,你有一个小数据集)。

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 2019-10-31
    • 2021-12-25
    • 2020-10-11
    • 2020-10-23
    • 2019-03-04
    • 2017-08-13
    • 2018-08-14
    • 1970-01-01
    相关资源
    最近更新 更多