Tensorflow 取掩码张量的元素的平均值
Tensorflow take mean of the elements of a masked tensor
为了处理可变长度的输入序列,所有的输入序列都被填充到相同的长度。这会影响损失值的计算。因此掩码张量与损失张量相乘,使填充元素产生的损失为 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
将张量的归约和除以掩码的归约和。
均值 = tf.math.reduce_sum(t) / tf.math.reduce_sum(遮罩)
为了处理可变长度的输入序列,所有的输入序列都被填充到相同的长度。这会影响损失值的计算。因此掩码张量与损失张量相乘,使填充元素产生的损失为 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
将张量的归约和除以掩码的归约和。
均值 = tf.math.reduce_sum(t) / tf.math.reduce_sum(遮罩)