numpy中增加与减少数据维度

增加维度

在使用神经网络训练时,往往要求我们输入的数据是二维的,但有时我们得到的单条数据是一维的,这时候就需要我们将一维的数据扩展到二维。

方法一

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)

ndarrayshape中,去掉维度为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)

posted @ 2021-01-06 10:24  火锅先生  阅读(4142)  评论(0编辑  收藏  举报