python 数字识别 SVM


利用python 内置的digits 数据进行 数字识别

# The data that we are interested in is made of 8x8 images of digits, let's
# have a look at the first 4 images, stored in the `images` attribute of the
# dataset.  If we were working from image files, we could load them using
# matplotlib.pyplot.imread.  Note that each image must have the same size. For these
# images, we know which digit they represent: it is given in the 'target' of
# the dataset.


from sklearn import datasets,svm,metrics
import numpy as np
import matplotlib.pyplot as plt
digits = datasets.load_digits()
images_and_labels = list(zip(digits.images,digits.target))
#print(images_and_labels[0])
#print(images_and_labels[0:4])

#显示训练集的前4个结果
for index,(image,label) in enumerate(images_and_labels[:4]):
    plt.subplot(2,4,index+1)
    plt.axis('off')
    plt.imshow(image,cmap=plt.cm.gray_r,interpolation='nearest')
    plt.title('Training :%i' %label)

#样本数
n_samples = len(digits.images)
#print(digits.images.shape)

data = digits.images.reshape((n_samples,-1)) #和 reshape(n_samples,64)效果一样 可以用下面的这条验证
#print(np.all(digits.images.reshape((1797,-1))==digits.data)) #true

classifier = svm.SVC(gamma=0.001)
#对前一半样本进行训练,构建模型
classifier.fit(data[:n_samples//2],digits.target[:n_samples//2])
#对后半部分数据进行验证,期望的预测结果
expected = digits.target[n_samples//2:]
#真实的预测结果
predicted = classifier.predict(data[n_samples//2:])
#预测结果与真实结果进行对比,得出预测详细信息(正确率等)
print("Classification report for classifier %s:\n%s\n"
      % (classifier, metrics.classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))

#print(predicted) 所有的预测结果

#将测试数据用zip构建城dict 进行图像与预测结果的对应
images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))

#对结果进行显示
for index, (image, prediction) in enumerate(images_and_predictions[:4]): #只是画出了前四个 预测的结果
    plt.subplot(2, 4, index + 5) #2*4的图 第index+5部分
    plt.axis('off')#不显示坐标信息
    #显示图片(灰色)
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    #在图片上方显示预测结果,方便直观看出正确性
    plt.title('Prediction: %i' % prediction)
plt.show()


上4个图是训练的时候画的,下面4个是预测的(前4张图)

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值