In the process of machine learning practice recently,遇到了reshape函數的新用法,簡單總結一下:
Numpy中reshape函數的三種常見相關用法
reshape(1,-1)轉化成1行,Columns need to be calculated:
reshape(2,-1)轉換成兩行,Columns need to be calculated:
reshape(-1,1)轉換成1列,Rows need to be counted:
reshape(-1,2)轉化成兩列,Rows need to be counted.
We next illustrate with an example:
In [2]: import numpy as np
In [3]: x=np.array([[[1,2,3],[4,5,6],[7,8,9]]])
In [4]: x
Out[4]:
array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]])
In [5]: x.shape
Out[5]: (1, 3, 3)
我們定義一個三維數組,A total of nine elements:
首先第一個reshape(1,-1)
:
In [6]: x.reshape((1,-1))
Out[6]: array([[1, 2, 3, 4, 5, 6, 7, 8, 9]])
我們不難理解,Our purpose is to convert a three-dimensional array into a two-dimensional array,且行數為1,Then the number of columns is:9/1=9
所以是一個1*9
的數組.
同樣的道理,Let's look at the other three:
In [7]: x.reshape((3,-1))
Out[7]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [8]: x.reshape((-1,1))
Out[8]:
array([[1],
[2],
[3],
[4],
[5],
[6],
[7],
[8],
[9]])
In [9]: x.reshape((-1,3))
Out[9]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
我們用(3,-1)和(-1,3)的原因很簡單,因為2不能整除9.