注释写得很清楚了,熟悉了一下python的一些基本语法和numpy中的一些操作。

 from numpy import *
import operator def createDataSet():
# generate the samples and labels.
group = array([[1.0,1.1], [1.0,1.0], [0,0], [0,0.1]])
labels = ['A', 'A', 'B', 'B']
print group
return group, labels def classify(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0] # get the size of one dimension.
                            # calculate the distance between inX and samples.
diffMat = tile(inX, (dataSetSize, 1)) - dataSet # repeat inX to generate a dataSetSize * 1 matrix. Then subtract the corresponding number in dataSet.
sqDiffMat = diffMat ** 2 # get the square of each D-value.
sqDistances = sqDiffMat.sum(axis=1) # get the sum of each pair of numbers.
distances = sqDistances ** 0.5 # get the square root of each sum. Those are distances between inX and samples. sortedDistIndicies = distances.argsort() # return the index if 'distances' is sorted.
classCount = {} # make a directory {label:display times}.
for i in range(k): # get first kth nearest samples.
voteIlabel = labels[sortedDistIndicies[i]] # get the ith's label.
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # count the number of this label.
sortedClassCount = sorted(classCount.iteritems(), # get the most frequent label.
key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0] # return the most frequent label. dataSet, labels = createDataSet()
print classify([-100.0,-100.1], dataSet, labels, 1)

最新文章

  1. yii2整合百度编辑器umeditor
  2. 【caffe】train_lenet.sh在windows下的解决方案
  3. Windows Server 2012/2016在桌面上添加计算机等图标
  4. ionic cordova plugin simple demo
  5. Python标准库:迭代器Itertools
  6. Count Good Substrings
  7. directive和controller如何通信
  8. 自定义VS程序异常处理及调试Dump文件(一)
  9. Java Enum用法详解
  10. Python内置函数(12)——str
  11. BZOJ4727 [POI2017]Turysta
  12. 好程序员告诉你HTML好在哪里,为什么值得我们学习
  13. Flex读取txt文件里的内容(一)
  14. matlab 测试 数字二次混频
  15. python的前后端分离(一):django+原生js实现get请求
  16. Jersey入门——对Json的支持
  17. 浏览器缓存之Expires Etag Last-Modified max-age详解
  18. python语言中的数据类型之列表
  19. .gitignore文件规则不起效的解决办法
  20. Oracle EBS GL 会计科目报错 GL_ACCESS_SET_LEDGERS

热门文章

  1. BZOJ2694: Lcm
  2. 版本控制 - Git
  3. 使用TCP协议的NAT穿透技术
  4. ObjectStore onFetch方法获取记录总数
  5. eclipse sdk 无法更新
  6. 哪些问题困扰着我们?DevOps 使用建议
  7. 替代jquery
  8. POJ 1650
  9. C# WinForm窗口最小化到系统托盘
  10. [转载] ACE 组播校验和出错问题解决