【问题标题】:convert [28,28,2] matlab array to [2, 28, 28, 1] tensor将 [28,28,2] matlab 数组转换为 [2, 28, 28, 1] 张量
【发布时间】:2017-12-22 22:55:27
【问题描述】:

我正在学习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] 张量?

【问题讨论】:

  • 试图使问题更具可读性并突出显示到目前为止采取的要点/步骤。尝试使您的帖子具有可读性,以便您得到正确的回复而不是反对
  • 您在 MATLAB 中创建数组并在 Python 中使用它。您想在 MATLAB 或 Python 中进行此转换吗?请具体,并适当地标记您的问题。

标签: python matlab tensorflow tensor


【解决方案1】:

首先,转置数组,使 28x28x2 变为 2x28x28 (第 3 维先行,然后第 1 维,然后第 2 维)。

arr = arr.transpose((2, 0, 1))

注意:您可以使用arr.reshape((2, 28, 28)) 获得形状2x28x28,但这会打乱数据的顺序。我使用了transpose,因为我相信您希望arr[0] 成为一张图片,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)

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 2020-02-11
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2017-12-28
    相关资源
    最近更新 更多