# coding=utf-8

from numpy import *
import pylab as pl

def loadData():
    group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels

def classify0(dataSet, labels, data, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(data, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistance = sqDiffMat.sum(axis=1)
    distance = sqDistance ** 0.5
    sortedDistanceIndicies = distance.argsort()         # 排序获得下标
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistanceIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    sortedClassCount = sorted(classCount.iteritems(), key=lambda classCountItem : classCountItem[1], reverse=True)
    return sortedClassCount[0][0]

dataSet, labels = loadData()
print classify0(dataSet, labels, array([0, 1]), 3)
pl.plot(dataSet[:2, 0], dataSet[:2, 1], 'ob')
pl.plot(dataSet[2:, 0], dataSet[2:, 1], 'or')
pl.plot(0, 1, 'oy')
pl.show()