python语言编写KNN程序
来源:互联网 发布:2016淘宝双11成交额 编辑:程序博客网 时间:2024/06/03 14:40
Python版本为:3.2.3
代码为:
from numpy import*
import operator
#k邻近算法
def classify0(inX,dataSet,labels,k):
dataSetSize = dataSet.shape[0] #数据矩阵的行
diffMat = tile(inX,(dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sum(sqDiffMat,axis=1)
distances = sqDistances**0.5
sortedDistIndicies = argsort(distances)
classCount = {}
for i in range(k):
voteLabel = labels[sortedDistIndicies[i]]
classCount[voteLabel] = classCount.get(voteLabel,0)+1
sortedClassCount = sorted(classCount.items(),key = operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
#创建一些训练数据
def createDataSet():
group = array([[1,1.1],[1,1],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group,labels
#测试
data,label = createDataSet()
test_data = [0,0]
classify0(test_data,data,label,3)
将代码复制在Python的IDLE工具中时,不能直接复制粘贴,不然有些语句运行不了。
实际粘贴运行过程为:
>>> from numpy import*
>>> import operator
>>> def classify0(inX,dataSet,labels,k):
dataSetSize = dataSet.shape[0] #数据矩阵的行
diffMat = tile(inX,(dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sum(sqDiffMat,axis=1)
distances = sqDistances**0.5
sortedDistIndicies = argsort(distances)
classCount = {}
for i in range(k):
voteLabel = labels[sortedDistIndicies[i]]
classCount[voteLabel] = classCount.get(voteLabel,0)+1
sortedClassCount = sorted(classCount.items(),key = operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
>>> def createDataSet():
group = array([[1,1.1],[1,1],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group,labels
>>> data,label = createDataSet()
>>> data
array([[ 1. , 1.1],
[ 1. , 1. ],
[ 0. , 0. ],
[ 0. , 0.1]])
>>> label
['A', 'A', 'B', 'B']
>>> test_data = [0,0]
>>> classify0(test_data,data,label,3)
'B'
- python语言编写KNN程序
- python 的KNN 程序
- C语言程序编写
- C语言程序编写
- Python编写MapReduce程序
- python 交互程序编写
- 开始编写python程序
- knn python
- D 语言编写CGI程序
- C语言编写时钟程序
- C语言编写五子棋程序
- C语言编写CGI程序
- C语言编写GUI程序
- C语言编写程序计时
- Python语言编写BP神经网络
- python编写网络爬虫程序
- Eric4 + PyQt 编写Python程序
- Python编写FTP下载程序
- LeetCode : Plus One
- flume高并发优化——(12)filesource 支撑文件组&兼容cat监控
- 没找到第三方框架文件问题
- HDU 1203 I NEED A OFFER! by Assassin
- Linux服务器配置——搭建SVN服务器
- python语言编写KNN程序
- 第5章 路由事件(2)——冒泡路由事件
- Activity和fragment传值问题
- 从头学java day1
- samrty 获取当前的循环次数
- 9月份英语学习总结—坚持
- 英语学习——梨花带雨
- servlet4
- 自定义Drawable