码迷,mamicode.com
首页 > 其他好文 > 详细

[MachineLearning]KNN

时间:2014-06-21 13:30:34      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:class   blog   get   2014   set      

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 18 11:46:15 2014

@author: hp
"""

import numpy as np
import operator

def createDataSet():
    group=np.random.rand(4,2)
    labels=[‘a‘,‘b‘,‘c‘,‘d‘]
    return group,labels
    
def classify0(inX,dataSet,labels,k):
    dataSetSize=dataSet.shape[0]
    diffMat=np.tile(inX,(dataSetSize,1))-dataSet
    sqDiffMat=diffMat**2
    sqDistances=sqDiffMat.sum(axis=1)
    distances=sqDistances**0.5
    sortedDistIndicies=distances.argsort()
    classCount={}
    for i in range(k):
        voteLabel=labels[sortedDistIndicies[i]]
        classCount[voteLabel]=classCount.get(voteLabel,0)+1
    sortedClassCount=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]
    
group,labels=createDataSet()
result=classify0([0,1],group,labels,3)
print ‘对坐标0,0的分类为%s‘%(result)

  

[MachineLearning]KNN,布布扣,bubuko.com

[MachineLearning]KNN

标签:class   blog   get   2014   set      

原文地址:http://www.cnblogs.com/colipso/p/3794724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!