关于np.newaxis
经常在程序中看到np.newaxis,这里记录一下我的理解:
np.arange(0, 10)
这句话 生成的是一个一维的数组,如下:
[0 1 2 3 4 5 6 7 8 9]
其shape为(10,)
那么我如何才能将其转化为shape=(1,10)呢?
有两种方法:
1.使用shape:
y=np.arange(0, 10)
y.shape=(10,1)
print(y)
- 使用np.newaxis
print(np.arange(0, 10)[:, np.newaxis])
输出结果一样:
[[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]]
np.newaxis的作用就是在这一位置增加一个维度,这一位置指的是np.newaxis所在的位置:
例1:
x1 = np.array([1, 2, 3, 4, 5])
# the shape of x1 is (5,)
x1_new = x1[:, np.newaxis]
# now, the shape of x1_new is (5, 1)
# array([[1],
# [2],
# [3],
# [4],
# [5]])
x1_new = x1[np.newaxis,:]
# now, the shape of x1_new is (1, 5)
# array([[1, 2, 3, 4, 5]])
例2:
In [1]: arr = np.arange(5*5).reshape(5,5)
In [2]: arr.shape
Out[2]: (5, 5)
# promoting 2D array to a 5D array
In [3]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]
In [4]: arr_5D.shape
Out[5]: (1, 5, 5, 1, 1)
数据维度
对于数据的维度,用一个例子理解,在RNN中往LSTM隐层传递数据时,数据的shape通常会是(batch_size, time_steps, inputs),拿MNIST手写数字数据集来说:
6万张训练图片和1万张测试图片,每张图片都是28*28大小;
为了计算的速度,用到batch_size=100分批次传入,做参数回归训练,更新参数;
将每一张图片看成28个序列,每一次输入28个数据,因此在传入隐层是数据要reshape成(batch_size, time_steps, inputs)的形状;
综上:我的理解是在传入数据时,每一先传入一个28的数据的inputs,一张图片28个时序,一个batch100张图片,按照数据形状[a, b, c, d…],由后向前的先后按批传入。