1. 程式人生 > >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維陣列