【问题标题】:how to perform element wise multiply for two 4d tensor of shape [1,16,16,3] and [1,4,4,3]如何对形状为 [1,16,16,3] 和 [1,4,4,3] 的两个 4d 张量执行逐元素乘法
【发布时间】:2018-11-08 03:50:42
【问题描述】:

我想按元素将两个 4d 张量相乘并将结果存储在 4d 张量中。我有一个张量,例如形状 [batch_size,16,16,3] 的张量和形状 [batch_size] 的张量“B” ,4,4,3]。我想执行一种平铺操作,以便张量“A”的每个 4x4x3 块与张量“B”进行元素乘法。 结果存储在形状与张量“A”相同的张量“C”中,即[batch_size,16,16,3]。 AS张量'B'的高度和宽度是张量'A'的高度和宽度的倍数。我应该在张量“C”中连接或累加或分配 4 个元素乘法的结果。

【问题讨论】:

  • 我在文档中没有看到任何表明 tf.math.multiply 不起作用的内容,它会引发错误吗?如果不是,请展示该尝试以及输出与您期望的输出有何不同?
  • 目前我可以分配一个 4,4,3 张量并与其他 4,4,3 张量执行 tf.multiply 但我如何将结果存储为 16,16,3 包括四个4,4,3 个结果
  • 您是否尝试过使用tf.concat?请发布您的代码示例!

标签: python tensorflow


【解决方案1】:

这可以通过重塑和使用broadcasting来完成。

import tensorflow as tf

batch_size = 50

# These are the tensors we want to multiply
a = tf.random_normal(shape=(batch_size,16,16,3))
b = tf.random_normal(shape=(batch_size,4,4,3))

# We reshape the tensors so that they their shapes are
# compatible for broadcasting
a_reshape = tf.reshape(a,(-1,4,4,4,4,3))
b_reshape = tf.reshape(b,(-1,4,1,4,1,3))

# we perform the multiplication. Each dimenshion of size 1 in `b_reshape`
# will be tiled to have the corresponding size 4 of `a_reshape`
c_reshape = a_reshape*b_reshape

# convert result to required shape
c = tf.reshape(c_reshape,(-1,16,16,3))

【讨论】:

    猜你喜欢
    • 2021-05-21
    • 2018-10-23
    • 1970-01-01
    • 2019-03-05
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多