我有一个三维 numpy 图像数组 ( CIFAR-10 dataset )。图像阵列形状如下:
a = np.random.rand(32, 32, 3)
在我进行任何深度学习之前,我想对数据进行归一化以获得更好的结果。对于一维数组,我知道我们可以像这样进行最小最大归一化:
v = np.random.rand(6)
(v - v.min())/(v.max() - v.min())
Out[68]:
array([ 0.89502294, 0. , 1. , 0.65069468, 0.63657915,
0.08932196])
但是,当涉及到 3D 阵列时,我完全迷失了。具体来说,我有以下问题:
- 我们沿着哪个轴取最小值和最大值?
- 我们如何使用 3D 阵列实现它?
感谢您的帮助!
编辑:
事实证明,我需要使用形状为 (202, 32, 32, 3)
的 4D Numpy 数组,因此第一个维度将是图像的索引,最后 3 个维度是实际图像。如果有人能为我提供规范化此类 4D 数组的代码,那就太好了。谢谢!
编辑 2: 感谢@Eric 下面的代码,我已经弄明白了:
x_min = x.min(axis=(1, 2), keepdims=True)
x_max = x.max(axis=(1, 2), keepdims=True)
x = (x - x_min)/(x_max-x_min)
最佳答案
假设您正在处理形状为 (W, H, 3)
的图像数据,您应该分别对每个 channel (axis=2
) 进行归一化,因为在另一个答案中提到。
你可以这样做:
# keepdims makes the result shape (1, 1, 3) instead of (3,). This doesn't matter here, but
# would matter if you wanted to normalize over a different axis.
v_min = v.min(axis=(0, 1), keepdims=True)
v_max = v.max(axis=(0, 1), keepdims=True)
(v - v_min)/(v_max - v_min)
关于python - 如何规范化 4D numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460217/