【问题标题】:How to reshape a tensor where one dimension is reduced to 1?如何重塑一维减少为1的张量?
【发布时间】:2021-07-13 13:38:08
【问题描述】:

我正在尝试使用从 [30,50,32,64] 到 [30,50,32,1] 的加法和挤压/归一化来重塑张量。当我使用 Tensorflow reshape 时,出现以下错误。

o = tf.reshape(o, shape=[30, 50, 32, 1])

ValueError: 无法将具有 3072000 个元素的张量整形为具有输入形状的“鉴别器/嵌入/Reshape_4”(操作:“Reshape”)的 [30,50,32,1](48000 个元素):[30,50 ,32,64], [4] 并且输入张量计算为部分形状:输入[1] = [30,50,32,1]。

有人可以提出解决办法吗?

【问题讨论】:

  • 你不能那样做,你的休息呢63张量!

标签: python python-3.x tensorflow pytorch tensor


【解决方案1】:

我认为您将重塑操作与缩减混淆了。首先,重塑与规范化无关。根据定义,任何整形操作都应该保留张量元素的数量和值。 即不可能将 30x50x32x64(3072000 个元素)张量重塑为 30x50x32x1 张量(48000 个元素)。

查看文档:https://www.tensorflow.org/api_docs/python/tf/reshape

所以如果你想对最后一个张量的维度应用归约操作,你可以这样做:

In [1]: import tensorflow as tf
In [2]: data = tf.random.normal(shape=[30, 50, 32, 64])
In [3]: tf.math.reduce_mean(data, axis=-1, keepdims=True).shape
Out[3]: TensorShape([30, 50, 32, 1])

Squeeze/unsqueezing 可以看作是 reshape 操作的一种特殊情况。删除或添加单色调维度的位置。

# squeeze example
In [4]: tf.squeeze(tf.math.reduce_mean(data, axis=-1, keepdims=True)).shape
Out[4]: TensorShape([30, 50, 32])

# unsqueeze example
In [5]: tf.expand_dims(tf.math.reduce_mean(data, axis=-1, keepdims=True), axis=0).shape
Out[5]: TensorShape([1, 30, 50, 32, 1])

【讨论】:

    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 2017-09-05
    • 2019-08-23
    • 2021-01-25
    • 2016-03-17
    • 2018-10-26
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多