python - 将 [28,28,2] matlab 数组转换为 [2, 28, 28, 1] 张量

标签 python matlab tensorflow tensor

我正在学习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 used transpose because I believe you want arr[0] to be a picture, and the same for arr[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/

相关文章:

python - 一次获取 NumPy 数组中多行的索引

c++ - 如何在 C++ 中打印/检查 vector 的值

python - 找不到-lpython2 : MatCaffe installation error

python - 使用装饰器恢复生成器

python - 使用两种不同的键和值源的字典推导式

python - '名称错误: name 'fcntl' is not defined' when using urwid on windows

matlab - 用Matlab将矩阵插入另一个矩阵

python - 如何在 Tensorflow 中打印标志描述?

python - 无法从 'keras_export' 导入名称 'tensorflow.python.util.tf_export'

python - 使用 argmax 从 Tensor 获取值