Python KNN K近邻

from numpy import  *
import operator
class KNN:
    def createDataset(self):
        group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
        labels = ['A','A','B','B']
        return group,labels

    def knnClassify(self,testX,trainX,lables,K):
        [N,M] = trainX.shape
        # calculate the distance between testX and other training samples
        difference = tile(testX,(N,1)) - trainX # tile for array and repeat for matrix in Python, == repmat in Matlab
        difference = difference ** 2            # take pow(difference,2)
        distance = difference.sum(1)            # take the sum of difference from all dimensions
        distance = distance ** 0.5
        sortdiffidx = distance.argsort()

        # find the k nearest neighbours
        vote = {}   # create the dictionary
        for i in range(K):
            ith_label = lables[sortdiffidx[i]]
            vote[ith_label] = vote.get(ith_label,0)+1   # get(ith_label,0): if dictionary 'vote' exist key 'ith_label', return vote[ith_label,else return 0
        #print vote.iteritems()
        sortedvote = sorted(vote.iteritems(),key = lambda x:x[1],reverse = True) # 'key = lambda x:x[1]' can be substituted by operator.itemgetter(1)
        return sortedvote[0][0]

k = KNN()   # create KNN object
group,labels = k.createDataset()
cls = k.knnClassify([0,0],group,labels,3)
# print group
# print labels
print cls

原文:http://blog.csdn.net/abcjennifer/article/details/19757987


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值