#科学计算包
from numpy import *
# 运算符模块
import operator
def createDataSet():
group = array([
[1.0,1.1],
[1.0,1.0],
[0,0],
[0,0.1],
[0,0.2]
])
#label包含每个数据点的标签信息
#label包含的元素个数等于group矩阵行数
labels = ['A','A','B','B','B']
return group,labels
group,labels = createDataSet()
print(group)
print(labels)
#对位置类别属性的数据集中的每个点依次执行一下操作
# 计算已知类别数据集中的点与当前点之间的距离
# 按照距离递增次序排序
# 选取与当前点距离最小的k个点
# 确定前k个点所在类别的出现频率
# 返回前k个点出现频率最高的类别作为当前点的预测分类
def classify0(inX,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX,(dataSetSize,1)) -dataSet
print(diffMat)
sqDiffMat = diffMat**2
print(sqDiffMat)
sqDistances = sqDiffMat.sum(axis=1)
print(sqDistances)
distances = sqDistances**0.5
print(distances)
#返回的是数组值从小到大的索引值
sortedDistIndicies = distances.argsort()
classCount={}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
# 函数返回指定键的值,如果值不在字典中返回默认值
classCount[voteIlabel] = classCount.get(voteIlabel,0)+1
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
print(sortedClassCount)
return sortedClassCount[0][0]
sortedDistIndicies = classify0([4,5],group,labels,4)
print(sortedDistIndicies)