numpy中的reshape中參數為-1


 

上篇文章中的reshape(-1,2),有的時候不明白為什么會有參數-1,可以通過查找文檔中的reshape()去理解這個問題

根據Numpy文檔()的解釋:

newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, **the value is inferred from the length of the array and remaining dimensions**.

數組新的shape屬性應該要與原來的配套,如果等於-1的話,那么Numpy會根據剩下的維度計算出數組的另外一個shape屬性值。

舉幾個例子或許就清楚了,有一個數組z,它的shape屬性是(4, 4)

z = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) z.shape (4, 4) 
z.reshape(-1)
z.reshape(-1) array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) 
z.reshape(-1, 1)

也就是說,先前我們不知道z的shape屬性是多少,但是想讓z變成只有1列,行數不知道多少,通過`z.reshape(-1,1)`,Numpy自動計算出有16行,新的數組shape屬性為(16, 1),與原來的(4, 4)配套。

z.reshape(-1,1) array([[ 1], [ 2], [ 3], [ 4], [ 5], [ 6], [ 7], [ 8], [ 9], [10], [11], [12], [13], [14], [15], [16]]) 
z.reshape(-1, 2)

newshape等於-1,列數等於2,行數未知,reshape后的shape等於(8, 2)

 z.reshape(-1, 2) array([[ 1, 2], [ 3, 4], [ 5, 6], [ 7, 8], [ 9, 10], [11, 12], [13, 14], [15, 16]]) 

同理,只給定行數,newshape等於-1,Numpy也可以自動計算出新數組的列數。


免責聲明!

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



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