【问题标题】:Tensorflow 2.0 `tf.multiply` method gives unexpected resultsTensorflow 2.0 `tf.multiply` 方法给出了意想不到的结果
【发布时间】:2020-07-01 09:01:17
【问题描述】:

我对这个操作的输出形状有点困惑

>>> eps = tf.random.uniform((3))
>>> images = tf.random.normal((3, 28, 28, 1))
>>> output = eps * images
>>> output.get_shape()
(3, 28, 28, 3)

我希望这将 eps 中的每个标量与图像中形状 (28, 28, 1) 的每个图像相乘,以获得输出形状 (3, 28, 28, 1)

类似的东西

>>> output = []
>>> output.append(eps[0] * images[0])
>>> output.append(eps[1] * images[1])
>>> output.append(eps[2] * images[2])
>>> output = tf.convert_to_tensor(output)
>>> output.get_shape()
(3, 28, 28, 1)

请帮忙。

【问题讨论】:

    标签: python tensorflow broadcasting


    【解决方案1】:

    这是由于broadcasting(链接来自 NumPy 文档,但它在 TensorFlow 中的工作方式相同)。如果您想将eps 的单一维度与images 的第一个维度“匹配”,则需要向eps 添加额外的单一维度,以便广播按预期工作:

    eps = tf.random.uniform((3))
    # Add dimensions for broadcasting
    eps = tf.reshape(eps, [-1, 1, 1, 1])
    output = eps * images
    print(output.get_shape())
    # (3, 28, 28, 1)
    

    或者,您可以直接使用该形状创建eps

    eps = tf.random.uniform((3, 1, 1, 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 2017-01-05
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2021-04-22
      • 2016-02-13
      相关资源
      最近更新 更多