import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
digits = datasets.load_digits()
print(digits.data)
classifier = svm.SVC(gamma=0.4, C=100)
x, y = digits.data[:-1], digits.target[:-1]
x = x.reshape(1,-1)
y = y.reshape(-1,1)
print((x))
classifier.fit(x, y)
###
print('Prediction:', classifier.predict(digits.data[-3]))
###
plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()我也重塑了x和y。尽管如此,我还是收到了一个错误:
发现样本数量不一致的输入变量: 1,1796
Y有1796个元素的一维阵列,而x有很多元素。它是如何显示x的1的?
发布于 2016-10-25 21:18:58
实际上放弃我下面的建议:
This link describes the general dataset API。属性data是每个图像的2d数组,已经展平:
import sklearn.datasets
digits = sklearn.datasets.load_digits()
digits.data.shape
#: (1797, 64)这就是您需要提供的所有内容,不需要重塑。类似地,属性data是每个标签的一维数组:
digits.data.shape
#: (1797,)不需要重塑。只需将训练和测试分成两部分并运行即可。
尝试打印x.shape和y.shape。我觉得你会找到类似这样的东西:(1, 1796, ...)和(1796, ...)。当为scikit中的分类器调用fit时,它需要两个形状相同的迭代器。
线索是,为什么在重塑周围的不同方式时会有争论:
x = x.reshape(1, -1)
y = y.reshape(-1, 1)也许可以试试:
x = x.reshape(-1, 1)与您的问题完全无关,但是当训练集中唯一剩下的元素是digits.data[-1]时,您在digits.data[-3]上进行了预测。不确定那是不是故意的。
无论如何,使用scikit metrics包检查分类器的更多结果可能是很好的。This page has an example of using it over the digits dataset。
发布于 2016-10-25 21:54:06
重塑将把你的8x8矩阵转换成一个1维向量,它可以用作一个特征。您需要重塑整个X向量,而不仅仅是训练数据的X向量,因为您将用于预测的向量需要具有相同的格式。
下面的代码显示了如何:
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
digits = datasets.load_digits()
classifier = svm.SVC(gamma=0.4, C=100)
x, y = digits.images, digits.target
#only reshape X since its a 8x8 matrix and needs to be flattened
n_samples = len(digits.images)
x = x.reshape((n_samples, -1))
print("before reshape:" + str(digits.images[0]))
print("After reshape" + str(x[0]))
classifier.fit(x[:-2], y[:-2])
###
print('Prediction:', classifier.predict(x[-2]))
###
plt.imshow(digits.images[-2], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
###
print('Prediction:', classifier.predict(x[-1]))
###
plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()它将输出:
before reshape:[[ 0. 0. 5. 13. 9. 1. 0. 0.]
[ 0. 0. 13. 15. 10. 15. 5. 0.]
[ 0. 3. 15. 2. 0. 11. 8. 0.]
[ 0. 4. 12. 0. 0. 8. 8. 0.]
[ 0. 5. 8. 0. 0. 9. 8. 0.]
[ 0. 4. 11. 0. 1. 12. 7. 0.]
[ 0. 2. 14. 5. 10. 12. 0. 0.]
[ 0. 0. 6. 13. 10. 0. 0. 0.]]
After reshape[ 0. 0. 5. 13. 9. 1. 0. 0. 0. 0. 13. 15. 10. 15. 5.
0. 0. 3. 15. 2. 0. 11. 8. 0. 0. 4. 12. 0. 0. 8.
8. 0. 0. 5. 8. 0. 0. 9. 8. 0. 0. 4. 11. 0. 1.
12. 7. 0. 0. 2. 14. 5. 10. 12. 0. 0. 0. 0. 6. 13.
10. 0. 0. 0.]对最后两个没有用于训练的图像进行正确的预测-但是你可以决定在测试和训练集之间进行更大的划分。
https://stackoverflow.com/questions/40240944
复制相似问题