K-近邻算法(KNN)思想:
1,计算未知样本与所有已知样本的距离
2,按照距离递增排序,选前K个样本(K<20)
3,针对K个样本统计各个分类的出现次数,取最大次数的分类为未知样本的分类
函数classify0虽然只有短短的几行代码,涉及的知识点却非常多,具体的知识点整理如下:
一、程序清单2-1笔记
1,shape函数
shape函数是numpy.core.fromnumeric中的函数,它的功能是查看矩阵或者数组的维数。
比如:
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
print(group)
print(group.shape)
print("group.shape[0]=%d" % group.shape[0])
结果如下:
dataset如下:
[[ 1. 1.1]
[ 1. 1. ]
[ 0. 0. ]
[ 0. 0.1]]
(4, 2)
group.shape[0]=4
2,tile函数
tile(数组,(在行上重复次数,在列上重复次数))
比如:
array1 = [1,2,3]
print(tile(array1,(2,1)))
print(tile(array1,(1,2)))
print(tile(array1,(2,2)))
结果如下:
[[1 2 3]
[1 2 3]]
[[1 2 3 1 2 3]]
[[1 2 3 1 2 3]
[1 2 3 1 2 3]]
3,sum函数.sum(axis=1)
我们平时用的sum应该是默认的axis=0 就是普通的相加
当加入axis=1以后就是将一个矩阵的每一行向量相加
如:
array2 = [[0,1,2],[0,3,4]]
print(sum(array2,axis=1))
print("
")
结果如下:
[3 7]
4,sort函数和argsort函数
sort函数按照数组值从小到大排序
argsort函数返回的是数组值从小到大的索引值
如:
array3 = [3,2,1]
print(argsort(array3))
print(sort(array3))
print("
")
结果如下:
[2 1 0]
[1 2 3]
5,字典get方法的参数k的意义
dic.get(key,k) = dic.get(key,默认值)
k的含义是:当字典dic中不存在key时,返回默认值k;存在时返回key对应的值
如下:
dic1 = {"A": 1, "B": 2, "C": 3}
print("dic 测试")
print(dic1.get("C",0))
print(dic1.get("D", 0))
print(dic1.get("E", 1))
结果如下:
dic 测试
3
0
1
6,字典的iteritems函数:
注意:python3中dict不存在iteritems,python2中存在
可以使用items代替
dic1 = {"A": 1, "B": 2, "C": 3}
print("测试字典的Item")
print( dic1.items() )
# python3中dict不存在iteritems 'dict' object has no attribute 'iteritems'
#print( dic1.iteritems())
测试结果如下:
测试字典的Item
dict_items([('A', 1), ('B', 2), ('C', 3)])
7,operator.itemgetter定义一个函数
operator.itemgetter(k)定义一个函数,返回第k个域的值
比如:
print("测试operator.itemgetter")
a=[1,2,3]
b=operator.itemgetter(2) #定义函数b,获取对象的第一个域的值
print(b(a))
b=operator.itemgetter(1,0)#定义函数b,获取对象的第1个域和第0个域的值
print(b(a))
测试结果:
测试operator.itemgetter
3
(2, 1)
二、所有的测试代码:
from numpy import *
import operator
def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group,labels
### test ##########################
group,labels = createDataSet()
print("dataset如下:")
print(group)
print(group.shape)
print("group.shape[0]=%d" % group.shape[0])
print("
")
print(labels )
print("
")
array1 = [1,2,3]
print(tile(array1,(2,1)))
print(tile(array1,(1,2)))
print(tile(array1,(2,2)))
print("
")
array2 = [[0,1,2],[0,3,4]]
print(sum(array2,axis=1))
print("
")
array3 = [3,2,1]
print(argsort(array3))
print(sort(array3))
print("
")
dic1 = {"A": 1, "B": 2, "C": 3}
print("dic 测试")
print(dic1.get("C",0))
print(dic1.get("D", 0))
print(dic1.get("E", 1))
#测试字典的Item
print("测试字典的Item")
print( dic1.items() )
# python3中dict不存在iteritems 'dict' object has no attribute 'iteritems'
#print( dic1.iteritems())
print("
")
#测试operator.itemgetter
print("测试operator.itemgetter")
a=[1,2,3]
b=operator.itemgetter(2) #定义函数b,获取对象的第一个域的值
print(b(a))
b=operator.itemgetter(1,0)#定义函数b,获取对象的第1个域和第0个域的值
print(b(a))
######函数定义
def classify0(inX,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = tile(inX,(dataSetSize,1)) - dataSet
print("diffMat")
print(diffMat)
print("
")
sqDiffMat = diffMat ** 2
print("sqDiffMat")
print(sqDiffMat)
print("
")
sqDistances = sqDiffMat.sum(axis=1)
print("sqDistances")
print(sqDistances)
print("
")
distances = sqDistances ** 0.5
print("distances")
print(distances)
print("
")
sortedDistIndicies = distances.argsort()
print("sortedDistIndicies")
print(sortedDistIndicies)
print("
")
#统计前K个样本,各个label出现的次数
classCount = {}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
print("i=%s sortedDistIndicies[i]=%s voteIlabel=%s" % (i,sortedDistIndicies[i],voteIlabel) )
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
print(classCount)
print("
")
sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1),reverse=True)
print("sortedClassCount")
print(sortedClassCount)
print("
")
print("返回的分类为:%s",sortedClassCount[0][0])
return sortedClassCount[0][0]
print("开始执行分类函数.............")
classify0([0,0],group,labels,3)
三、运行结果如下:
"D:Program FilesPython36python.exe" E:/Code/Python/MachineLearningInAction/chapter02_KNN/kNN.py
dataset如下:
[[ 1. 1.1]
[ 1. 1. ]
[ 0. 0. ]
[ 0. 0.1]]
(4, 2)
group.shape[0]=4
['A', 'A', 'B', 'B']
[[1 2 3]
[1 2 3]]
[[1 2 3 1 2 3]]
[[1 2 3 1 2 3]
[1 2 3 1 2 3]]
[3 7]
[2 1 0]
[1 2 3]
dic 测试
3
0
1
测试字典的Item
dict_items([('A', 1), ('B', 2), ('C', 3)])
测试operator.itemgetter
3
(2, 1)
开始执行分类函数.............
diffMat
[[-1. -1.1]
[-1. -1. ]
[ 0. 0. ]
[ 0. -0.1]]
sqDiffMat
[[ 1. 1.21]
[ 1. 1. ]
[ 0. 0. ]
[ 0. 0.01]]
sqDistances
[ 2.21 2. 0. 0.01]
distances
[ 1.48660687 1.41421356 0. 0.1 ]
sortedDistIndicies
[2 3 1 0]
i=0 sortedDistIndicies[i]=2 voteIlabel=B
{'B': 1}
i=1 sortedDistIndicies[i]=3 voteIlabel=B
{'B': 2}
i=2 sortedDistIndicies[i]=1 voteIlabel=A
{'B': 2, 'A': 1}
sortedClassCount
[('B', 2), ('A', 1)]
返回的分类为:%s B
Process finished with exit code 0