python-knn分类器

dataSet=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels=[‘A’,‘A’,‘B’,‘B’]
inX=array([[0.9,0.9]])
print(classify([0.9,0.9],dataSet,labels,1))
dataSetsize=dataSet.shape[0]
#print(dataSetsize)
diffMat=tile(inX,(dataSetsize,1))-dataSet
print(diffMat)
sqDiffMat=diffMat2
print(sqDiffMat)
sqDistances=sqDiffMat.sum(axis=1)
print(sqDistances)
distances=sqDistances
0.5
print(distances)
sortedDistIndicies=distances.argsort()
print(sortedDistIndicies)
classCount={}#创建字典
voteLabel=labels[sortedDistIndicies[3]]
print(voteLabel)
classCount[voteLabel]=classCount.get(voteLabel,0)+1
print(classCount[voteLabel])
classCount[voteLabel]=classCount.get(voteLabel,0)+1
print(classCount[voteLabel])
classCount[voteLabel]=classCount.get(voteLabel,0)+1
print(classCount[voteLabel])
print(classCount)
classCount[“A”]=2
print(classCount.items())
sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
print(sortedClassCount)
print(sortedClassCount[0][0])

[[-0.1 -0.2]
[-0.1 -0.1]
[ 0.9 0.9]
[ 0.9 0.8]]
[[ 0.01 0.04]
[ 0.01 0.01]
[ 0.81 0.81]
[ 0.81 0.64]]
[ 0.05 0.02 1.62 1.45]
[ 0.2236068 0.14142136 1.27279221 1.20415946]
[1 0 3 2]
B
1
2
3
{‘B’: 3}
dict_items([(‘B’, 3), (‘A’, 2)])
[(‘B’, 3), (‘A’, 2)]
B

你可能感兴趣的:(python-knn分类器)