k-邻近算法笔记
算法流程
- (1)收集数据:数据整归
- (2)准备数据:计算距离值
- (3)分析数据
- (4)训练算法
- (5)测试算法:计算错误率
- (6)使用算法
伪代码:
def classfiy(inX,dataSet,labels,k): #inX输入向量,dataSet为训练集,labels为训练标签,k为所需近似个数
dataSetSize = dataSet.shape[0]
diffMat = tile(inX,[dataSetSize,1]) - dataSet
sqdiffMat = diffMat ** 2
sqdistance = sqdiffMat.sum(axis=1)
distances = sqdistance ** 0.5 #按照欧氏距离计算
sortedDistIndicies = distances.argsort() #排序
classCount = {}
for i in range(k):
voteLabel = labels[sortedDistIndicies[i]]
classCount[voteLabel] = classCount.get(voteLabel,0) + 1 #选择距离最小的k个点
sortedclassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True) #排序
return sortedclassCount[0][0]
group,labels = kNN.createDataSet()
print(classfiy([0,0],group,labels,3))
代码相关
- a numpy.tile()
Signature: tile(A, reps)
Docstring:Construct an array by repeating A the number of times given by reps.
tile()
的作用是将A
矩阵重复reps
次,reps
可以是矩阵举例如下:
>>> import numpy
>>> numpy.tile([0,0],5)#在列方向上重复[0,0]5次,默认行1次
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> numpy.tile([0,0],(1,1))#在列方向上重复[0,0]1次,行1次
array([[0, 0]])
>>> numpy.tile([0,0],(2,1))#在列方向上重复[0,0]1次,行2次
array([[0, 0],
[0, 0]])
>>> numpy.tile([0,0],(3,1))
array([[0, 0],
[0, 0],
[0, 0]])
>>> numpy.tile([0,0],(1,3))#在列方向上重复[0,0]3次,行1次
array([[0, 0, 0, 0, 0, 0]])
>>> numpy.tile([0,0],(2,3))#在列方向上重复[0,0]3次,行2次
In [25]: tile([[0,0],[1,1],[2,2]],[1,2,3])
Out[25]:
array([[[0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2],
[0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2]]])
numpy.argsort()
Returns the indices that would sort an array.
One dimensional array:
>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])
Two-dimensional array:
>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
[2, 2]])
>>> np.argsort(x, axis=0)
array([[0, 1],
[1, 0]])
>>> np.argsort(x, axis=1)
array([[0, 1],
[0, 1]])
Sorting with keys:
>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> np.argsort(x, order=('x','y'))
array([1, 0])
>>> np.argsort(x, order=('y','x'))
array([0, 1])
- 广播
注意矩阵格式,广播需要条件,以后涉及到再细讲 AttributeError: 'dict' object has no attribute 'iteritems'
python3.5中:iteritems
变为items
以前版本:items
返回的是dict
的list
iteritems()
返回的是dict
的generator
strip()
s.strip(rm):s为字符串,rm为要删除的字符序列
只能删除开头或是结尾的字符或者字符串。不能删除中间的字符或是字符串
当rm为空时,默认删除空白符(包括’\n’,’\r’,’\t’,’ ‘)plt.ax.scatter()