首页 > 代码库 > Numpy 中tile(A, reps)方法

Numpy 中tile(A, reps)方法

官方文档:

个人理解:

返回值

            ndarray,该函数是通过reps重复A后得到一个多位数组, 有点绕...

参数

            A几乎可以是全体类型, array, list , tuple, dict, matrix, int, long ,str, bool 等等

            reps,类型也很多, array, tuple, list, dict ,int ,long, bool 但是不管怎样都必须是 “一维数组(不一定是数组, 这里说成类一维数组)” , 如[1,2,3,4] , (1,2,3)或 3等等

实现过程

            1:   设 ndim = A的维度, ndimsA[] = A 各个坐标分量的长度

                  d = reps的长度(由于reps必须是“类一维数组”)

                  ans = tile(A, d) , ndimsAns[] = ans各个坐标分量的长度

            2:   ans.ndim = max(A. ndim, d)

                   如果  A.ndim >= d:

                                                    例如ndims = (2,3,4,5) , reps = (2,2)

                                                    那么ndims[]不变, 在reps数组前面添加A.ndim-d个‘1’,   那么reps = (1,1,2,2)

                  否则 A.ndim < d:

                                                    例如ndims = (2,3), reps = (1,2,3,4)

                                                    此时ndims维度不够, 应该增加维度到d, 同理在ndims前面添加d-A.ndims个‘1’, 即 ndims(1,1,2,3)

            3:  计算ndimsAns[]

                  由于通过2已经使得ndims和reps长度相同,故 ndimsAns = (ndism[0] * reps[0] , ndims[1] * reps[1], ndims[2] * reps[2],...) 对索引的值相乘

                  例如 ndims = (2,3,4,5) , reps = (2,2)

                  那么ndimsAns = (2*1, 3*1, 4*2,5*2) = (2,3,8,10)

          4:   计算ans

                 通过2确定了ans的维度大小,  通过3确定了ans各个维度分量的长度

                 注意维度的重复是先从右边开始的(可以理解为从低维开始) ,具体见下面的例子

举例说明:

>>> A = array([[1,2],[3,4]])

>>> A
array([[1, 2],
       [3, 4]])
>>> reps = (1,2,3)
>>> ans = tile(A,reps)
>>> ans
array([[[1, 2, 1, 2, 1, 2],
        [3, 4, 3, 4, 3, 4],
        [1, 2, 1, 2, 1, 2],
        [3, 4, 3, 4, 3, 4]]])

>>> ans.shape
(1, 4, 6)

从低维开始, 列重复3次,得到A‘ =[ [1,2,1,2,1,2],

                                                             [3,4,3,4,3,4]]

让后行从重复2次, 得到A‘‘ = [   [[1,2,1,2,1,2],

                                                     [3,4,3,4,3,4],

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

                                                     [3,4,3,4,3,4]]    ]

最后层重复1次(没有变化), ans = [   [[1,2,1,2,1,2],

                                                               [3,4,3,4,3,4],

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

                                                               [3,4,3,4,3,4]]    ]

因此最有一个(1,4,6)的3维数组