from numpy import *
import operator # 运算符模块
def createDataSet():
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 = createDataSet()
def classify0(inX, dataSet, labels, k): # inX为待划分的输入向量,dataSet为已知类别数据集,labels标签向量
dataSetSize = dataSet.shape[0] # 行数,即样本数量
diffMat = tile(inX, (dataSetSize,1)) - dataSet # tile(A, (a,b)):对array_like的A进行,a:行数重复,b:列数重复
sqDiffMat = diffMat**2 # diff是点的差值集
# ([(x1-x0)**2,(y1-y0)**2],[(x2-x0)**2,(y2-x0)**2],[(x3-x0)**2,(y3-y0)**2],[(x4-x0)**2,(y4-y0)**2])
sqDistances = sqDiffMat.sum(axis=1) # 逐列相加
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort() # argsort()将array中的元素从小到大排序,提取其对应的index
classCount={}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 # 字典dict.get(key, default=None),返回指定键的值,如果
# 键不在字典中返回默认值None或者设置的默认值。
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) # 同书上不同,自python3.5后
# 简写items()
return sortedClassCount[0][0]
print("标签:", classify0([2,4], group, labels, 3))
机器学习实战2.1KNN分类器代码(带注释)
最新推荐文章于 2024-05-09 19:20:18 发布