在进行深度学习或强化学习时经常需要对数据的维度进行变换,本文总结了numpy中几种常用的变换数据维度的方法
增加一个维度
在多维数组的最后一维再增加一个维度可以使用numpy.reshape或numpy.expand_dims或numpy.newaxis,示例如下:
import numpy as np
import matplotlib.pyplot as plt
# 生成一个二维数据
x = np.array(range(12))
x = np.reshape(x, (3,4))
print(x)
# 输出为:
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# 在多维数组的最后一维再增加一个维度
y1 = np.expand_dims(x, axis=x.ndim)
y2 = np.expand_dims(x, axis=-1)
y3 = x[:,:,np.newaxis]
y4 = np.reshape(x, (*x.shape,1))
# 上述四种方法的结果完全一致
assert(np.all(y1==y2))
assert(np.all(y2==y3))
assert(np.all(y3==y4))
print(y4)
# 输出为:
# [[[ 0]
# [ 1]
# [ 2]
# [ 3]]
# [[ 4]
# [ 5]
# [ 6]
# [ 7]]
# [[ 8]
# [ 9]
# [10]
# [11]]]
减小一个维度
如果多维数组的最后一维的长度为1,可以将该维去掉,去掉的方法可以使用numpy.reshape或numpy.squeeze,示例如下:
# 假设欲将刚才增加一维生成的多维数组y4的最后一维去掉
y = y4
x1 = np.squeeze(y, axis=(y.ndim-1))
x2 = np.squeeze(y)
x3 = np.squeeze(y, axis=-1)
x4 = np.reshape(y, y.shape[:-1])
# 上述四种方法的结果完全一致
assert(np.all(x1==x2))
assert(np.all(x2==x3))
assert(np.all(x3==x4))
print(x4)
# 输出为:
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
将多维数组压缩为一维数组
将多维数组压缩为一维数组,可使用flatten或ravel以及reshape方法,示例如下:
z1 = y.flatten()
z2 = y.ravel()
z3 = y.reshape(y.size)
# 上述三种方法结果完全一致
assert(np.all(z1==z2))
assert(np.all(z2==z3))
print(z3)
# 输出为:
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
将多维数组压缩为二维数组,0轴保持不变
在深度学习或强化学习中,有时需要将shape为(batches, d1, d2, d3,...)的多维数组转化为shape为(batches, d1*d2*d3...)的数组,此时可以使用reshape进行转化,示例如下:
#生成多维数据
d0 = np.expand_dims(x, axis=0)
d1 = np.repeat(d0, 3, axis=0)
print(d1)
# 输出为
# [[[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]]
#转化为二维数组
d2 = np.reshape(d1, (d1.shape[0], d1[0].size))
print(d2)
# 输出为:
# [[ 0 1 2 3 4 5 6 7 8 9 10 11]
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
# [ 0 1 2 3 4 5 6 7 8 9 10 11]]