MxNet中NDArray的reshape用法總結


reshape沒有特殊值時的常規用法就不用細說了,比如

>>> from mxnet import nd
>>> a = nd.array([1,2,3,4])
>>> a.shape
(4L,)
>>> a.reshape(2,2)

[[1. 2.]
 [3. 4.]]
<NDArray 2x2 @cpu(0)>

  

 下面詳細講下帶有特殊值,需要推倒的情況:

1. 表示復用輸入中的維度值

>>> from mxnet import nd
>>> a = nd.random.uniform(shape=(2,3,4))
>>> a.shape
(2L, 3L, 4L)
>>> b = a.reshape(4, 0, 2)
>>> b.shape
(4L, 3L, 2L)

上面例子中,輸出的第2個維度值與輸入的第2個維度值保持不變

2. -1 表示根據輸入與輸出中元素數量守恆的原則,根據已知的維度值,推導值為-1的位置的維度值

>>> from mxnet import nd
>>> a = nd.random.uniform(shape=(2,3,4))
>>> a.shape
(2L, 3L, 4L)
>>> b = a.reshape(-1, 12)
>>> b.shape
(2L, 12L)

3. -2 表示復用所有該位置之后的維度

>>> from mxnet import nd
>>> a = nd.random.uniform(shape=(2,3,4))
>>> a.shape
(2L, 3L, 4L)
>>> b = a.reshape(2, -2)
>>> b.shape
(2L, 3L, 4L)

4. -3 表示將連續兩個維度相乘作為新的維度

>>> from mxnet import nd
>>> a = nd.random.uniform(shape=(2,3,4))
>>> a.shape
(2L, 3L, 4L)
>>> b = a.reshape(2, -3)
>>> b.shape
(2L, 12L)

5. -4 表示把當前位置的維度拆分為后面兩個維度,這后面兩個數的乘積等於當前維度的輸入值

>>> a = nd.random.uniform(shape=(2,3,4))
>>> a.shape
(2L, 3L, 4L)
>>> b = a.reshape(-4, 1, 2, -2)
>>> b.shape
(1L, 2L, 3L, 4L)

reverse=True時,表示按照從右往左的順序進行推導,這個推導的技巧是把原維度和reshape的參數右側對齊,從右往左依次推導 比如:

reverse=False的情況(缺省)

>>> from mxnet import nd
>>> a = nd.random.uniform(shape=(10, 5, 4))
>>> a.shape
(10L, 5L, 4L)
>>> b = a.reshape(-1, 0)
>>> b.shape
(40L, 5L)

reverse=True的情況下:

>>> from mxnet import nd
>>> a = nd.random.uniform(shape=(10, 5, 4))
>>> a.shape
(10L, 5L, 4L)
>>> b = a.reshape(-1, 0, reverse=True)
>>> b.shape
(50L, 4L)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM