python - 即使使用 random_state,每次运行代码时也会有不同的值

标签 python scikit-learn

每次运行此代码时,我都会得到不同的 print 语句值。我很困惑为什么要这样做,因为我特别包含了训练/测试分割的 random_state 参数。 (顺便说一句,我希望我应该对数据进行编码;否则它会给出“ValueError:无法将字符串转换为 float ”)。

df = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data',
                 names=['buying', 'maint', 'doors', 'persons',
                        'lug_boot', 'safety', 'acceptability'])

# turns variables into numbers (algorithms won't let you do it otherwise)
df = df.apply(LabelEncoder().fit_transform)
print(df)

X = df.reindex(columns=['buying', 'maint', 'doors', 'persons',
                        'lug_boot', 'safety'])
y = df['acceptability']


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

print(X_train)

# decision trees classification
clf = tree.DecisionTreeClassifier(criterion='entropy')
clf = clf.fit(X_train, y_train)

y_true = y_test
y_pred = clf.predict(X_test)

print(math.sqrt(mean_squared_error(y_true, y_pred)))

最佳答案

DecisionTreeClassifier 还采用 random_state 参数:http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html

您所做的只是确保训练/测试分割是可重复的,但分类器还需要确保每次运行时它自己的种子都是相同的

更新

感谢@Chester VonWinchester 指出:https://github.com/scikit-learn/scikit-learn/issues/8443由于 sklearn 的实现选择,max_features= None 可能是不确定的,即使它应该意味着考虑所有功能。

上面的链接中有更多信息和讨论。

关于python - 即使使用 random_state,每次运行代码时也会有不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909617/

相关文章:

python - 根据来自多个行索引的多个列的值的聚合创建一个列

python - 搜索估计器参数返回的结果不在网格中?

python - 如何在 QDoubleSpinBox 后缀中使用上标

python - 如何在 Keras 中实现 Sklearn Metric 作为 Metric?

Python数据框: Calculating Confidence or Prediction Intervals Using Groupby on One Column

python - 为什么 cross_val_predict 比 KNeighborsClassifier 的拟合慢得多?

image - Scikit 学习。对无序 jpg 进行分类

python - 将数据框与列中的数组合并

python - Django 休息框架 : Unclear error message

python - 为什么我需要等待协程?