Numpy是单独的一个包,需要安装,可以方便的处理矩阵方面的计算,主要是不需要循环了,对数据处理较方便,其中不熟悉的方法可以谷歌.numpy.方法名。便可以在线找到help文件,列出具体例子。
dataset = array([[1,1.2],[2,2.1],[3,3.1]])
datasetSize = dataset.shape[0]
diffMat = tile([3,2],(datasetSize,1)) -dataset
sqdiffMat = diffMat**2
sqDistance = sqdiffMat.sum(axis =1)
array 是Numpy中的一个方法,用列表形式生成数组或矩阵,第一行生成3×2的矩阵,行数3,列数2;
dataset.shape也是numpy中的数组可调用的方法,如果参数为0返回多维数组中的行数,1则返回多维数组的列数,如果是更多维的以此类推;
tile,英文单词是瓦片,瓷砖,有动词和名词两种用法,铺瓷砖,用在这里就是重复的构造数组。
帮助文档定义:numpy.tile(A, reps),Construct an array by repeating A the number of times given by reps.
其中参数A是重复的内容,reps是重复的次数。该方法使用的细节还是让我费解的。
If reps has length d, the result will have dimension of max(d, A.ndim).
例如:a = array([0,1,2])
a.ndim = 1
如果r = tile(a,2),则array([0, 1, 2, 0, 1, 2]),因为d= 1, a.ndim = 1, max(d,A.ndim) = 1
这个就是把列表[0,1,2],重复两次,变成列表[0,1,2,0,1,2].
If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.
例如: a = array([0,1])
r = tile(a,(2,1))
因此此时a.ndim =1 ,而 len((2,1))=2, 出现了 A.ndim < d 的情况了。
根据帮助文件的说明,A 依据预先设定的轴提升为d维度。在此即为2维,
r = array ( [ [0, 1],
0, 1] ] ) 此时r 变成一个列表,每个元素又是一个列表。
第三种情况:
If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).
例如:a = array([[1,2],
[2,3]])
a.ndim =2 , r = tile(a,2)
则r = array([[1, 2, 1, 2],
[2, 3, 2, 3]])
这里是说reps被提升为A.ndim 用1, 这里不很明白???