直接从sklearn调用KNeighborsClassifier,设置n_neighbor = 5,使用默认的uniform的weight function,即每个neighbor的贡献都是1。代码如下,不过跑的很慢(i7-4800MQ)
# coding=utf-8
# 都是抄别人的,侵权不究
# typhoonbxq
# the University of Hong Kong
# Reference: http://blog.leanote.com/post/jevonswang/python%E8%AF%BB%E5%8F%96mnist%E6%95%B0%E6%8D%AE%E9%9B%86
import numpy as np
import struct
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.neighbors import KNeighborsClassifier
def loadImageSet(filename):
# print "load image set", filename
binfile = open(filename, 'rb')
buffers = binfile.read()
head = struct.unpack_from('>IIII', buffers, 0)
# print "head,", head
offset = struct.calcsize('>IIII')
imgNum = head[1]
width = head[2]
height = head[3]
# [60000]*28*28