使用python-opencv 的KNN对MNIST手写数字进行分类

import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
import struct
def load_mnist(path, kind='train'):
            labels_path = os.path.join(path,'%s-labels.idx1-ubyte'% kind)
            images_path = os.path.join(path,'%s-images.idx3-ubyte'% kind)
            with open(labels_path, 'rb') as lbpath:
                        magic, n = struct.unpack('>II', lbpath.read(8))
                        labels = np.fromfile(lbpath,dtype=np.uint8)
            with open(images_path, 'rb') as imgpath:
                        magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))
                        images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784)
            return images, labels
images, labels=load_mnist('MNIST_data', kind='train')
knn = cv2.ml.KNearest_create()
images=images.astype(np.float32)
labels=labels.astype(np.float32)
knn.train(images, cv2.ml.ROW_SAMPLE, labels)
images_test, labels_test=load_mnist('MNIST_data', kind='t10k')
images_test=images_test.astype(np.float32)
labels_test=labels_test.astype(np.float32)
corret=0
num=images_test.shape[0]
for i in range(num):  
           ret,result,neighbours,dist = knn.findNearest(images_test[i].reshape(1,784),k=5)
           if ret==labels_test[i]:
                       corret=corret+1
corret_rate=corret/num
print(corret_rate)
准确率达到96.88%。

你可能感兴趣的:(使用python-opencv 的KNN对MNIST手写数字进行分类)