我正在学习tensorflow
。完成专家的 tensorflow
教程 MNist
( https://www.tensorflow.org/get_started/mnist/pros ) 后,我尝试使用经过训练的模型来运行推理。
我制作了两个
[28x28]
图像,并将它们放入[28x28x2]
数组中,并保存了Matlab
文件。然后我使用
scipy.io
将数组加载到python
中。但是,我的网络需要一个
[2, 28, 28, 1]
张量。如何将
[28x28x2]
数组转换为[2, 28, 28, 1]
张量?
最佳答案
首先,转置数组,使 28x28x2 变为 2x28x28 (第 3 维先行,然后是第 1 维,最后是第 2 维)。
arr = arr.transpose((2, 0, 1))
Attention: you could have obtained the shape 2x28x28 by using
arr.reshape((2, 28, 28))
, but that would have messed up the order of your data. I usedtranspose
because I believe you wantarr[0]
to be a picture, and the same forarr[1]
.
然后扩展数组以获得最后一个维度
arr = np.expand_dims(arr, -1)
使用 4x4 而不是 28x28 的示例:
>>> arr = np.empty((4, 4, 2)) # an empty array
>>> arr[..., :] = 0, 1 # first picture is all 0s and second is all 1s
>>> arr[..., 0]
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
>>> arr[..., 1]
array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
>>> arr.shape
(4, 4, 2)
现在是转变
>>> arr = arr.transpose((2, 0, 1))
>>> arr = np.expand_dims(arr, -1)
>>> arr.shape
(2, 4, 4, 1)
关于python - 将 [28,28,2] matlab 数组转换为 [2, 28, 28, 1] 张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47948249/