【问题标题】:How to fix randomization in sklearn如何修复sklearn中的随机化
【发布时间】:2021-03-08 19:26:08
【问题描述】:

我正在尝试修复代码中的随机性,但每次运行时,我都会得到不同的最佳分数和最佳参数。结果相差不大,但如何修复结果以在每次运行时获得相同的最佳分数和参数?

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 27)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)


clf = DecisionTreeClassifier(random_state=None)

parameter_grid = {'criterion': ['gini', 'entropy'],
                  'splitter': ['best', 'random'],
                  'max_depth': [1, 2, 3, 4, 5,6,8,10,20,30,50],
                  'max_features': [10,20,30,40,50]
                 }

skf = StratifiedKFold(n_splits=10, random_state=None)
skf.get_n_splits(X_train, y_train)

grid_search = GridSearchCV(clf, param_grid=parameter_grid, cv=skf, scoring='precision')

grid_search.fit(X_train, y_train)
print('Best score: {}'.format(grid_search.best_score_))
print('Best parameters: {}'.format(grid_search.best_params_))

clf = grid_search.best_estimator_

y_pred_iris = clf.predict(X_test)
print(confusion_matrix(y_test,y_pred),"\n")
print(classification_report(y_test,y_pred),"\n")

【问题讨论】:

    标签: python random scikit-learn random-seed


    【解决方案1】:

    为了获得可重现的结果,代码中的每个随机源都必须明确播种(即使这样,你也必须小心 的隐含假设em>所有其他都相等实际上是成立的 - 请参阅 Why does the importance parameter influence performance of Random Forest in R? 以了解它不成立的情况。

    您的代码中有三个部分固有地包含随机元素:

    • train_test_split
    • DecisionTreeClassifier
    • StratifiedKFold

    您正确地为第一个播种(使用random_state=27),但您没有为其他两个播种,而在它们两个中都留下了random_state=None

    您应该做的只是用显式种子替换代码中random_state=None 的两种情况,就像您对train_test_split 所做的那样;它不必是任何特定的数字,甚至在所有情况下都相同,只需明确设置即可。

    【讨论】:

    • random_state=False 根据文档应该可以达到同样的效果。但显然不是。但是,我尝试了您的建议,它奏效了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 2016-07-23
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2021-01-24
    相关资源
    最近更新 更多