Machine Learning in Action Chapter 2
来源:互联网 发布:虽知世故可请你善良 编辑:程序博客网 时间:2024/05/16 17:57
今天尝试了第二章的KNN代码,挨个的查了函数的意思,也遇到了一点问题
from numpy import *import operatordef createDataSet(): group = array([[1.0, 1.1], [1.0, 1.0], [0, 0],[0, 0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labelsdef classify0(inX, dataSet, labels,k): # inX:要输入的分类坐标 dataSet:给定的进行Training的坐标 labels:各个dataSet对应的标签 dataSetSize = dataSet.shape[0] # dataSetSize是dataSet的行数 diffMat = tile(inX, (dataSetSize,1)) - dataSet # 为了求两点的距离,坐标相减. tile():将inX变成4行一模一样的array sqDiffMat = diffMat**2 # 差的平方 sqDistances = sqDiffMat.sum(axis=1) # axis=1:各行相加 distances = sqDistances**0.5 # 开根号 sortedDistIndicies = distances.argsort() #排序,具体说来,按降序排列返回从小到大的原来的序数位置。比如[4,1,3,2],那么就会返回[1,3,2,0] classCount={} for i in range(k): voteIlabel = labels[sortedDistIndicies[i]] classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 # get是取字典里的元素,如果之前这个voteIlabel是有的,那么就返回字典里这个voteIlabel里的值,如果没有就返回0(此处为引用) sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True) # reverse=True:降序 这里有一个Python2和Python3的一个区别,Python2使用iteritems(),Python使用items()函数 # 不然会报错:AttributeError: 'dict' object has no attribute 'iteritems' return sortedClassCount[0][0]group,labels=createDataSet()print(classify0([0,0],group,labels,3))
阅读全文
0 0
- "Machine Learning in Action" Chapter 2
- Machine Learning in Action Chapter 2
- machine learning in action
- Machine Learning in Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning In Action
- Machine Learning in Action
- Machine Learning in Action
- 《Machine Learning In Action》翻译
- MACHINE LEARNING IN ACTION KNN
- Machine Learning in Action--Contents
- 打造android快速开发的工具类FastAndrUtils
- LeetCode 编程练习
- Apache Spark RDD 论文中文版 | ApacheCN
- Unity3D中实现帧同步
- 判断字符串中是否有数字
- Machine Learning in Action Chapter 2
- 安装 Mac 最强大的终端 iTerm2
- [计蒜客16955] Islands [2017 ACM-ICPC 亚洲区(乌鲁木齐赛区)网络赛 F]
- yii框架中使用phpexcel得到的excel文件作为附件发送
- mybaties+mysql:插入数据,返回自增长的id
- Java分布式应用技术架构介绍
- Hbase 一些语句
- JavaSE_8系列博客——Java语言的特性(六)--泛型(1)--宏观把控
- android-studio背景设置大全