我不明白
我在尝试使用Scikit-learn和Matplotlib处理数字数据集
这是我的代码
import matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn import svmfrom sklearn.model_selection import train_test_splitdigits = datasets.load_digits()clf = svm.SVC(gamma=0.001, C=100.)X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=2017)clf.fit(X_train, y_train)pred = clf.predict(X_test)print("Prediction: {}".format(pred)) plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest')plt.show()
Matplotlib显示的是图像编号4,但每次我尝试打印预测结果时,得到的输出总是这样的
Prediction: [8 1 3 8 5 8 1 4 9 7 5 2 1 4 3 2 4 9 5 4 1 9 2 4 7 8 9 3 1 7 5 7 6 2 0 5 7 1 6 1 9 4 4 5 3 7 3 6 3 3 9 8 5 2 6 1 1 1 4 5 4 2 8 2 7 2 9 7 8 9 1 2 8 0 7 8 9 0 1 5 4 0 0 9 2 6 7 8 6 5 1 3 1 8 7 7 2 2 2 6 7 4 1 7 2 5 8 3 4 2 3 7 6 1 1 0 3 0 2 5 9 3 1 6 9 5 6 2 0 3 2 7 4 6 5 3 9 5 1 5 6 0 1 8 6 5 1 6 2 1 2 5 0 2 3 4 2 4 9 4 4 2 3 9 2 9 8 2 5 9 9 7 3 7 8 1 4 9 2 9 5 1 8 7 4 8 2 7 6 9 8 8 3 7 1 9 1 4 5 7 0 5 9 3 5 0 5 0 5 5 2 1 3 5 3 2 8 4 7 4 7 3 7 2 9 5 6 2 8 0 5 0 2 1 9 2 9 6 1 0 1 7 6 3 1 0 3 2 4 0 6 1 2 1 6 2 8 2 7 1 5 6 6 9 2 1 4 4 8 0 7 6 2 5 0 4 5 5 5 5 7 4 8 1 0 8 4 8 7 2 5 5 7 3 2 4 4 7 8 2 0 7 1 4 0 9 6 1 8 5 5 1 5 6 1 7 1 5 5 8 4 6 6 0 6 5 0 9 8 0 8 0 9 2 0 9 5 7 0 8 1 7 0 6 7 7 0 0 7 7 5 0 3 2 2 8 8 7 7 0]
我在尝试用Matplotlib打印数字,但得到的输出是这样的
我期望打印 prediction: 8
回答:
好的,以下是评论中人们试图告诉你的内容:
X_test
不是单个数据点,而是你整个测试集。它包含多少样本?
X_test.shape# (360, 64)
所以,它包含360个样本;因此,你的 pred
变量也必须包含这360个样本的预测。确实如此:
pred.shape# (360,)
你想检查 X_test
中第一个样本的预测结果吗?
pred[0]# 8
这个预测的真实值是什么?
y_test[0]# 8
看起来你确实正确预测了第一个测试样本。你想绘制这个样本(X_test[0]
)吗?你需要先将其重塑为 (8,8)
,因为 train_test_split
load_digits()
函数将原始的8×8图像展平为长度为64的一维数组:
plt.imshow(X_test[0].reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest')plt.show()
嗯,看起来有点像8…