【问题标题】:Decision boundary changing in sklearn each time I run code每次运行代码时,sklearn 中的决策边界都会发生变化
【发布时间】:2017-06-15 04:05:18
【问题描述】:

在 Udacity 的机器学习简介课程中,我发现我的代码的结果每次运行时都会发生变化。正确的值是 acc_min_samples_split_2 = .908 和 acc_min_samples_split_2 = .912,但是当我运行我的脚本时,有时 acc_min_samples_split_2 = .912 的值也是如此。这发生在我的本地计算机和 Udacity 中的 Web 界面上。为什么会发生这种情况?

该程序使用 Python 的 SciKit Learn 库。 这是我写的部分代码:

def classify(features, labels, samples):
        # Creates a new Decision Tree Classifier, and fits it based on sample data 
        # and a specified min_sample_split value
    from sklearn import tree
    clf = tree.DecisionTreeClassifier(min_samples_split = samples)
    clf = clf.fit(features, labels)
    return clf

#Create a classifier with a min sample split of 2, and test its accuracy
clf2 = classify(features_train, labels_train, 2)
acc_min_samples_split_2 = clf2.score(features_test,labels_test)

#Create a classifier with a min sample split of 50, and test its accuracy
clf50 = classify(features_train, labels_train, 50)
acc_min_samples_split_50 = clf50.score(features_test,labels_test)

def submitAccuracies():
    return {"acc_min_samples_split_2":round(acc_min_samples_split_2,3),
      "acc_min_samples_split_50":round(acc_min_samples_split_50,3)}
print submitAccuracies()

【问题讨论】:

    标签: python scikit-learn decision-tree


    【解决方案1】:

    scikit-learn 中的一些分类器具有随机性质,使用一些 PRNG 在内部生成随机数。

    DecisionTree 就是其中之一。检查文档并使用参数random_state 使随机行为具有确定性。

    只需像这样创建适合对象:

    clf = tree.DecisionTreeClassifier(min_samples_split = samples, random_state=0)  # or any other constant
    

    如果您不提供random_state 或我上面示例中的一些种子/整数,PRNG 将由一些外部源(很可能基于系统时间)播种,从而导致不同的结果运行该脚本。*

    两次运行,共享代码和给定常量将表现相同(忽略一些病态架构/平台的东西)。

    【讨论】:

    • 你知道这些模型是如何使用random_state的吗?感谢您指出这一点,我在代码中看到了这一点,但我发现如果我继续重新运行代码,我的 MLPClassifier 有时会达到 19% 的准确度。我认为无论选择什么,random_state 的准确性都不会这么低。
    猜你喜欢
    • 2018-07-12
    • 2020-02-03
    • 2013-10-04
    • 2021-02-11
    • 2016-05-24
    • 1970-01-01
    • 2012-05-18
    • 2012-11-29
    • 1970-01-01
    相关资源
    最近更新 更多