(1)计算已知类别数据集中的点与当前点之间的距离
(2)按照距离递增次序排序;
(3)选取与当前距离最小的k个点;
(4)确定前k个点所在类别的出现频率;
(5)返回前k个点出现频率最高的类别作为当前点的预测分类。
#kNN.py
from numpy import *
import operator
def createDataSet():
group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
lables=['A','A','B','B']
return group,lables
def classify0(inX,dataSet,labels,k):
#获取数组的一维长度,行数
dataSetSize = dataSet.shape[0]
#将矩阵扩展,与dataSet矩阵行数列数相同
diffMat=tile(inX,(dataSetSize,1))-dataSet
sqDiffMat=diffMat**2
#对矩阵横向求和
sqDistance=sqDiffMat.sum(axis=1)
#开根号求距离
distance=sqDistance**0.5
#对矩阵元素排序,返回从小到大元素的下标,list
sortedDistIndcies=distance.argsort()
#建立一个字典,用来记录'A','B'出现的次数
classCount={}
for i in range(k):
voteIlabel=labels[sortedDistIndcies[i]]
#从字典中取得键,如果不存在返回0,然后+1,把它的值存进字典
#如果存在键,返回它对应的值,然后+1,把它的值存进字典
classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
#排序以出现次数,进行降序,排列,
sortedClassCount=sorted(classCount.items(),
key=operator.itemgetter(1),
reverse=True)
#返回第一个元素
return sortedClassCount[0][0]
#main.py
from Modules import kNN
group,labels=kNN.createDataSet()
a=kNN.classify0([0,0],group,labels,3)
print(a)
函数详细介绍
help(numpy.shape)
1、shape函数
使用>>>help(numpy.shape)查看帮助
shape[0] 第一维度的长度
shape[1] 第二维度的长度
shape函数是numpy.core.fromnumeric中的函数,它的功能是查看矩阵或者数组的维数。
>>>help(numpy.shape)
Help on function shape in module numpy.core.fromnumeric:
shape(a)
Return the shape of an array.
Parameters
----------
a : array_like
Input array.
Returns
-------
shape : tuple of ints
The elements of the shape tuple give the lengths of the
corresponding array dimensions.
#返回一个有序列表元组,元组的每个元素,代表对应数组的维度
See Also
--------
alen
ndarray.shape : Equivalent array method.
Examples
--------
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
2、tille()函数用法
Help on function tile in module numpy.lib.shape_base:
tile(A, reps)
A是被重复的对象,rep是重复的次数
Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
3、sorted()函数
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
#返回一个list,其元素按照升序排列
Return a new list containing all items from the iterable in ascending order.
#可以提供自定义键功能,来自定义排序顺序
A custom key function can be supplied to customize the sort order, and the
#反向标志可以设置为按降序请求结果。
reverse flag can be set to request the result in descending order.