【问题标题】:Tensorflow take mean of the elements of a masked tensorTensorflow 取掩码张量的元素的平均值
【发布时间】:2020-03-19 06:03:12
【问题描述】:

为了处理可变长度的输入序列,所有的输入序列都被填充到相同的长度。这会影响计算损失的价值。因此,将掩码张量与损失张量相乘以使填充元素产生的损失为 0。但是在使用 tf.math.reduce_mean 或 tf.keras.metrics.Mean 取损失的平均值时,这些填充元素对意思。

所以我的问题是,如何取 tensorflow 中的掩蔽损失的平均值?

例如:

t = [1, 2, 3]
t = pad(t, 6) # padding, now t = [1, 2, 3, 0, 0, 0]
mask = [True, True, True, False, False, False]
loss = [0.1, 0.2, 0.3, 0.12, 0.2, 0.4] # notice padded elements contribute to loss
loss = loss * mask # loss = [0.1, 0.2, 0.3, 0, 0, 0]

现在我想要类似的东西:

Mean(loss) = 0.6, which is (0.1 + 0.2 + 0.3) / 3

不是这样的:

Mean(loss) = 0.1, which is (0.1 + 0.2 + 0.3 + 0 + 0 + 0)/6

【问题讨论】:

    标签: python tensorflow mean mask loss-function


    【解决方案1】:

    参考这个tensorflow google group

    将张量的归约和除以掩码的归约和。

    mean = tf.math.reduce_sum(t) / tf.math.reduce_sum(mask)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多