增加維度
在使用神經網絡訓練時,往往要求我們輸入的數據是二維的,但有時我們得到的單條數據是一維的,這時候就需要我們將一維的數據擴展到二維。
方法一
numpy.expand_dims(a, axis)
-
若
axis
為正,則在a的shape
的第axis
個位置增加一個維度(從0開始數) -
若
axis
為負,則在a的shape
的從后往前數第-axis
個位置增加一個維度(從1開始數)
舉例:
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> a
array([1, 2, 3])
>>> a.shape
(3,)
>>> np.expand_dims(a, axis=0)
array([[1, 2, 3]])
>>> np.expand_dims(a, axis=0).shape
(1, 3)
>>> np.expand_dims(a, axis=1).shape
(3, 1)
>>> b = np.array([[1,2,3],[2,3,4]])
>>> b.shape
(2, 3)
>>> np.expand_dims(b, axis=0).shape
(1, 2, 3)
>>> np.expand_dims(b, axis=1).shape
(2, 1, 3)
>>> np.expand_dims(b, axis=2).shape
(2, 3, 1)
>>> np.expand_dims(b, axis=-1).shape
(2, 3, 1)
>>> np.expand_dims(b, axis=-2).shape
(2, 1, 3)
>>> np.expand_dims(b, axis=-3).shape
(1, 2, 3)
方法二
使用numpy.reshape(a, newshape)
>>> a
array([1, 2, 3])
>>> a.shape
(3,)
>>> np.reshape(a, (1,3)).shape
(1, 3)
>>> np.reshape(a, (3,1)).shape
(3, 1)
>>> b
array([[1, 2, 3],
[2, 3, 4]])
>>> b.shape
(2, 3)
>>> np.reshape(b, (1,2,3)).shape
(1, 2, 3)
>>> np.reshape(b, (2,1,3)).shape
(2, 1, 3)
>>> np.reshape(b, (2,3,1)).shape
(2, 3, 1)
減少維度
有時候我們又想把高維度數據轉換成地維度
方法一
numpy.squeeze(axis=None)
從ndarray
的shape
中,去掉維度為1的。默認去掉所有的1。
注意:只能去掉shape中的1,其他數字的維度無法去除。
舉例:
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> a = a.reshape(1, 1, 1, 2, 5)
>>> a.shape
(1, 1, 1, 2, 5)
>>> a.squeeze().shape # 默認去掉shape中的所有的1
(2, 5)
>>> a.squeeze(0).shape # 去掉第1個1
(1, 1, 2, 5)
>>> a.squeeze(-3).shape # 去掉倒數第3個1
(1, 1, 2, 5)
方法二
同上,使用numpy.reshape(a, newshape)