我使用pythonsklearn(版本0.17)来选择数据集上的理想模型。为此,我遵循以下步骤:使用cross_validation.train_test_split和test_size = 0.2拆分数据集。在
使用GridSearchCV在训练集中选择理想的k近邻分类器。在
将GridSearchCV返回的分类器传递给plot_learning_curve。plot_learning_curve给出了如下图。在
在获得的测试集上运行GridSearchCV返回的分类器。在
从图中我们可以看出,最大训练规模的得分约为0.43。此分数是sklearn.learning_curve.learning_curve函数返回的分数。在
但是当我在测试集中运行最好的分类器时,我得到的准确度得分为0.61,由sklearn.metrics.accuracy_score(正确预测的标签/标签数量)返回
链接到图像:
这是我使用的代码。我没有包含plot_learning_curve函数,因为它需要很大的空间。我从here取了plot_learning_curveimport pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from matplotlib import pyplot as plt
import sys
from sklearn import cross_validation
from sklearn.learning_curve import learning_curve
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import train_test_split
filename = sys.argv[1]
data = np.loadtxt(fname = filename, delimiter = ',')
X = data[:, 0:-1]
y = data[:, -1] # last column is the label column
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)
params = {'n_neighbors': [2, 3, 5, 7, 10, 20, 30, 40, 50],
'weights': ['uniform', 'distance']}
clf = GridSearchCV(KNeighborsClassifier(), param_grid=params)
clf.fit(X_train, y_train)
y_true, y_pred = y_test, clf.predict(X_test)
acc = accuracy_score(y_pred, y_test)
print 'accuracy on test set =', acc
print clf.best_params_
for params, mean_score, scores in clf.grid_scores_:
print "%0.3f (+/-%0.03f) for %r" % (
mean_score, scores.std() / 2, params)
y_true, y_pred = y_test, clf.predict(X_test)
#pred = clf.predict(np.array(features_test))
acc = accuracy_score(y_pred, y_test)
print classification_report(y_true, y_pred)
print 'accuracy last =', acc
plot_learning_curve(clf, "KNeighborsClassifier",
X, y,
train_sizes=np.linspace(.05, 1.0, 5))
这正常吗?我能理解分数可能会有一些差异,但这是0.18的差异,换算成百分比后是43%对61%。分类报告也给出了平均0.61的召回率。在
我做错什么了吗?在learning_curve计算分数的方式上有区别吗?{{cd13>函数也试图让它的准确度有任何差别。在
任何建议都会大有帮助。在
我使用的是葡萄酒质量(白色)data set from UCI,并且在运行代码之前删除了头。在