首页 文章

查找sklearn决策树分类器的随机状态

提问于
浏览
1

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

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

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

2 回答

  • 1

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

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

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

  • 3

    我建议您最好使用随机森林来实现此目的 - 随机森林包含许多以预测变量子集为模型的树 . 然后,您可以通过简单地使用 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') ......
    

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

相关问题