K-NN(最近邻分类算法 python
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了K-NN(最近邻分类算法 python相关的知识,希望对你有一定的参考价值。
# algorithm:K-NN(最近邻分类算法)
# author:Kermit.L
# time: 2016-8-7
#==============================================================================
from numpy import *
import operator
import matplotlib.pyplot as plt
def creatDataSet():
group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = [‘A‘, ‘A‘, ‘B‘, ‘B‘]
return group,labels
group,labels = creatDataSet()
plt.figure(1)
plt.plot(group[:,0],group[:,1],‘or‘)
plt.xlim(-0.5, 1.5)
plt.ylim(-0.5, 1.5)
plt.grid()
for i in xrange(group.shape[0]):
plt.text(group[i][0]-0.06,group[i][1],labels[i])
plt.show()
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX,(dataSetSize,1)) - dataSet;
sqDiffMat = diffMat ** 2
sqDistance = sqDiffMat.sum(axis = 1)
distance = sqDistance ** 0.5
sortDistanceIndex = distance.argsort()
classCount ={}
for i in xrange(k):
voteLabel = labels[sortDistanceIndex[i]]
classCount[voteLabel] = classCount.get(voteLabel,0) + 1
sortedClassCount = sorted(classCount.iteritems(),key = operator.itemgetter,
reverse = True)
return sortedClassCount[0][0]
# print sortDistanceIndex
# sqDiffMat = diffMat.sum(axs = 1)
# print sqDiffMat
# distance = sqDiffMat ** 0.5
inX =[0.8,0.6]
print classify0(inX, group, labels, 2)
以上是关于K-NN(最近邻分类算法 python的主要内容,如果未能解决你的问题,请参考以下文章
k近邻算法(k-nearest neighbor,k-NN)
R语言非参数方法:使用核方法和K-NN(k近邻算法)分类预测心脏病数据