【问题标题】:Need help reshaping multidimensional NumPy array需要帮助重塑多维 NumPy 数组
【发布时间】:2018-01-09 18:01:26
【问题描述】:

在 TensorFlow 中,我有一个张量 h,形状为 (?, 14, 14, 512)

我通过tf.reshape(h, [-1, 196, 512])重塑了自己的形象

这会导致形状为 (?, 196, 512) 的张量。完美的。我需要对 numpy 数组做同样的事情。

我有一个巨大的多维 NumPy 数组保存到磁盘。它看起来像这样:

features = numpy.ndarray([3000, 14, 14, 2048], dtype=np.float32)

并且需要它的形状:

[3000, 196, 2048]

如何进行这种转换,以免丢失信息?

numpy.reshape(features, (3000, 196, 2048))吗?

还是numpy.reshape(features, (-1, 196, 2048))

这两种重塑方法的结果是一样的还是有什么区别?

【问题讨论】:

  • 使用 tf.reshape 和 np.reshape 应该得到相同的结果

标签: python numpy tensorflow tensor


【解决方案1】:

两者都是有效的,并且会给你相同的结果:

features = np.ndarray([3000, 14, 14, 2048], dtype=np.float32)

# prints (3000, 196, 2048)
print(np.reshape(features, (3000, 196, 2048)).shape)

# prints (3000, 196, 2048)
print(np.reshape(features, (-1, 196, 2048)).shape)

# another option, prints (3000, 196, 2048) as well
print(features.reshape((-1, 196, 2048)).shape)

只要你恰好有一个-1 维度,numpy 就能自动计算出它的值。

【讨论】:

    【解决方案2】:

    可以写成

    a = np.ndarray([3000,14,14,2048])
    b = a.reshape((-1, 196, 2048))
    

    形状维度可以是-1,并且该值是从数组的长度和剩余维度推断出来的。

    在您的情况下,维度的第一个值必须是 3000 才能满足其余维度。

    这两种重塑方法的结果是一样的还是有什么区别?

    这两个应该给你相同的结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 2021-03-15
      相关资源
      最近更新 更多