# algorithm:K-NN(最近邻分类算法)
# author:Kermit.L
# time: 2016-8-7
#==============================================================================
from numpy import *
import operator
import matplotlib.pyplot as plt

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

group,labels = creatDataSet()
plt.figure(1)
plt.plot(group[:,0],group[:,1],'or')
plt.xlim(-0.5, 1.5)
plt.ylim(-0.5, 1.5)
plt.grid()
for i in xrange(group.shape[0]):
plt.text(group[i][0]-0.06,group[i][1],labels[i])
plt.show()

def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX,(dataSetSize,1)) - dataSet;
sqDiffMat = diffMat ** 2
sqDistance = sqDiffMat.sum(axis = 1)
distance = sqDistance ** 0.5
sortDistanceIndex = distance.argsort()
classCount ={}
for i in xrange(k):
voteLabel = labels[sortDistanceIndex[i]]
classCount[voteLabel] = classCount.get(voteLabel,0) + 1
sortedClassCount = sorted(classCount.iteritems(),key = operator.itemgetter,
reverse = True)
return sortedClassCount[0][0]
# print sortDistanceIndex
# sqDiffMat = diffMat.sum(axs = 1)
# print sqDiffMat
# distance = sqDiffMat ** 0.5

inX =[0.8,0.6]
print classify0(inX, group, labels, 2)

最新文章

  1. MATLAB-RSP 随笔
  2. 一个新人如何学习在大型系统中添加新功能和Debug
  3. jQuery-1.9.1源码分析系列(七) 钩子(hooks)机制及浏览器兼容
  4. JavaScript高级-定义函数(类)方法
  5. TreeSet集合深入了解--------攻击原理
  6. A trip through the Graphics Pipeline 2011_09_Pixel processing – “join phase”
  7. linux 搭建SVN服务器,为多个项目分别建立版本库并单独配置权限
  8. 【BZOJ】【1055】【HAOI2008】玩具取名
  9. HTML之一字符集
  10. Java通过JDBC连接Oracle之后查询结果和在sqlplus查询结果不一样
  11. jsoup技术抓取网页数据大全
  12. Linux-手动释放缓存(Buffer、Cache)
  13. JSON多层数据添加与访问
  14. logging的使用方法
  15. android java.lang.IllegalStateException: Circular dependencies cannot exist in RelativeLayout
  16. python 小技巧
  17. enctype=“multipart/form-data”详解
  18. SSL/TLS中间人攻击
  19. centos 安装git服务器,配置使用证书登录并你用hook实现代码自动部署
  20. AWK 知识库

热门文章

  1. linkedin第三方登陆
  2. Shamir秘密共享方案 (Python)
  3. iOS 索引列 使用详解
  4. Mac 上超好用的代码对比工具 beyond compare,对比json差异
  5. CentOS下Python尝试
  6. JMeter 安装 启动(即中文的修改)
  7. java并发编程实战《八》管程
  8. PyQt(Python+Qt)学习随笔:QListView的gridSize属性
  9. pytorch SubsetRandomSampler 用法和说明
  10. 利用promise实现间隔1s打印1,2,3