python KNN算法的简单实现

时间:2021-02-03 21:24:55

这里依然是学习《统计学习方法》一书中,K近邻算法的一个实验尝试。具体理论可参考该输,这里简单贴出K近邻算法的思想及实现步骤:
python KNN算法的简单实现

结果展示如下:
python KNN算法的简单实现
大的红点是传入的测试点,k传入的是5,也就是说大红点的周围5个点决定大红点的类别。
python KNN算法的简单实现

上图便是判定大红点属于红色类别的判别过程。也就是说,他周围最近邻的k个点进行投票表决,多数决定其类别。

import numpy as np
from matplotlib import pyplot

def randonGenerate15PointerAndThreeClass():
ponters = []
for num in range(3):
data = [[np.random.random_integers(0,9,1),np.random.random_integers(0,9,1),np.array(num)] for a in range(5)]
ponters.append(np.array(data))
np.save("data",ponters)
print(ponters)
return ponters

def loadData(fileName):
return np.load(fileName)

#计算两个向量的距离,用的是欧几里得距离
def distEclud(vecA, vecB):
return np.sqrt(np.sum(np.power(vecA - vecB, 2)))

def drawPointers(pointers,point):
pointersLocal = pointers[:,:,0:2]
i = 0
for classs in pointersLocal:
cs = np.zeros(3,dtype=np.int8)
cs[i]=1
#将list转为numpy中的array,方便切片
xy = np.array(classs)

if(len(xy)>0):
pyplot.scatter(xy[:,0],xy[:,1],c=cs)
i += 1
pyplot.scatter(xy[:, 0], xy[:, 1], c=cs)
cs = np.zeros(3, dtype=np.int8)
cs[point[2]] = 1
pyplot.scatter(point[0],point[1], c=cs,linewidths=20)
pyplot.show()
return None


def sortByTheClu(data):
return data[0]

def sortByTheClu1(data):
return data[1]

def KNN(pointers,point,k):

#计算每个点到点a的欧氏距离
disAll = []
i=0
for data in pointers:
tmpDatas = data[:,:2]
labels = data[:,2]
for pointer in tmpDatas:
dis = distEclud(point,pointer)
disAll.append(np.array([np.array(dis),np.array(labels[i])]))
i += 1
#需要排序,然后统计最近的k个点,通过表决的方式决定point的类别
print(disAll)
disSorted = sorted(disAll,key=sortByTheClu)
print(disSorted)
kdata = np.array(disSorted[0:k])
print(kdata)
for num in range(k):
labels = kdata[:,1]
ksetlabels = np.zeros(k)
i=0
for label in labels:
ksetlabels[i] = label
i += 1
kset = set(ksetlabels)
classAndCount = []
for classs in kset:
count = 0
for label in ksetlabels:
if classs == label:
count +=1
classAndCount.append([int(classs),count])
classAndCountSorted = sorted(classAndCount,key=sortByTheClu1,reverse=True)
return classAndCountSorted[0]

def test():
pointers = loadData("data.npy")
print(pointers)
#给定一个点,计算分类
a = [[3],[5]]
result = KNN(pointers,a,5)
a.append(result[0])
drawPointers(pointers,a)
return None


# randonGenerate15PointerAndThreeClass()
test()

图中的15个点事调用randonGenerate15PointerAndThreeClass()方法随机生成的,因此实验之前,先调用该方法生成15个实验数据。
然后就可以调用test方法进行测试。