Python–numpy中的tile()函数

首先是官方给的定以(我是用的VsCode,鼠标放置在tile上出现的),建议直接看后面的示例。
 
def tile(A, reps)

Construct an array by repeating A the number of times given by reps.

If reps has length d, the result will have dimension of max(d, A.ndim).

If A.ndim < dA 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.

If A.ndim > dreps 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).

Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions.

Parameters

A : array_like

The input array.

reps : array_like

The number of repetitions of `A` along each axis.

Returns

c : ndarray

The tiled output array.

See Also

repeat : Repeat elements of an array. broadcast_to : Broadcast an array to a new shape

Examples

a = np.array([0, 1, 2])

np.tile(a, 2)     /*列(水平方向)重复2次 */

array([0, 1, 2, 0, 1, 2])

这里的可以理解为a向右复制,同理,理解为a向下复制。复制次数包括本身(即2为复制1次,加上原来的为2个)。

当参数仅1个时候(如上),默认水平方向复制

当参数为2个时候(如下),则第一个表示行(垂直方向)复制,第二个表示会列(水平方向)复制

 

np.tile(a, (3, 2))    /*行(垂直方向)重复3次,列(水平方向)重复2次*/

array([[0, 1, 2, 0, 1, 2],

          [0, 1, 2, 0, 1, 2],

          [0, 1, 2, 0, 1, 2]])
Note: 1或者2参数时候可以以上面的理解,下面的就不太适合了。
 
 
下面这一个的话,从最右的开始往左,先是列(水平方向)重复2次,垂直方向不动,然后整体的二维复制一下(不知道方向了);下面再举一个对应的例子

np.tile(a, (2, 1, 2))  /*这个目前也不太理解,应该是超平面,大于三维时候*/

array([[[0, 1, 2, 0, 1, 2]],

          [[0, 1, 2, 0, 1, 2]]])

np.tile(a, (2, 1, 2)) 

array([[[0, 1, 2, 0, 1, 2],

            [0, 1, 2, 0, 1, 2]],

           [[0, 1, 2, 0, 1, 2],
            [0, 1, 2, 0, 1, 2]]])
 
 
 
当参数仅1个时候(如下),默认水平方向复制。整个b向右(水平方向)复制。

b = np.array([[1, 2], [3, 4]])

np.tile(b, 2)

array([[1, 2, 1, 2],

          [3, 4, 3, 4]])
 
当参数为2个时候(如下),则第一个表示行(垂直方向)复制2次,第二个表示会列(水平方向)复制1次(1次即保持原型)。

np.tile(b, (2, 1))

array([[1, 2],

          [3, 4], 
          [1, 2], 
          [3, 4]])
 
 

c = np.array([1,2,3,4])

np.tile(c,(4,1))

array([[1, 2, 3, 4],

          [1, 2, 3, 4], 
          [1, 2, 3, 4], 
          [1, 2, 3, 4]])
 
 
PS: 上述仅为个人理解以及记录,如能帮助到你,很开心,如有错误也烦请指正。
 
Tags: