numpy的tile函数是numpy的lib中的shape_base模块中的函数,形式为numpy.tile(A,reps),主要作用是通过给定的参数reps来控制A重复的次数,返回一个构造完成的数组。

官方文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html

该函数部分源码: https://github.com/numpy/numpy/blob/v1.14.2/numpy/lib/shape_base.py#L844-L932

其中的部分解释为:

numpy.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 < 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.

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).

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.


文档中提到,如果reps有长度d,那么返回的结果数组的维度 = max(reps的长度d, A数组的维度A.nidm)

首先需要明白什么是数组的维度,与维度在一起比较的还有shape属性。测试如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import numpy as np
# 对应一维数组a
a = np.array([1,2,3,4,5])
a.ndim #1
a.shape #(5,)
# 对于二维数组b
b = np.array(
[
[1,2,3],
[4,5,6],
[7,8,9]
]
)
b.ndim # 2
b.shape # (3,3)
#对于三维数组c
c = np.array(
[
[
[1,2,3],
[4,5,6]
],
[
[7,8,9],
[10,11,12]
]
]
)
c.ndim # 3
c.shape # (2,2,3)

比较简单的判断数组A的维度就是看中括号嵌入了几层。

然后需要明白参数数组A和reps都是array_like, 字面意思是类数组,主要包含的类型有array,list,tuple,dict等,可以看下这两篇文章:

http://blog.sina.com.cn/s/blog_6bd0612b0101cr3u.html

https://stackoverflow.com/questions/40378427/numpy-formal-definition-of-array-like-objects


令reps的长度为d。tile函数测试例子结果如下: