张量加权均值减少
Tensor weighted mean reduce
使用张量x
和权重w
作为输入:
w = [1, 1, 0]
x = tf.constant(
[[[1., 2.],
[5., 3.],
[6., 4.]],
[[5., 7.],
[10., 8.],
[11., 9.]]]
)
如何输出加权 reduce_mean 张量 y?
y = tf.constant(
[[w[0]*[1., 2.],
w[1]*[5., 3.],
w[2]*[6., 4.]],
[w[0]*[5., 7.],
w[1]*[10., 8.],
w[2]*[11., 9.]]]
)
预期结果是(均值是用总和除以1
的权重):
y = tf.constant(
[[3., 2.5]],
[[7.5, 7.5]]
)
检查这段代码,它给出了你想要的答案,解决方案是多次使用 map_fn
。
w = tf.constant([1.0, 1.0, 0.0])
x = tf.constant(
[[[1., 2.],
[5., 3.],
[6., 4.]],
[[5., 7.],
[10., 8.],
[11., 9.]]]
)
def apply_weight(x, w):
return tf.map_fn(mult, x)
def mult(a):
transposed_a = tf.transpose(a)
return tf.map_fn(mult_pars, transposed_a)
def mult_pars(b):
return tf.reduce_sum(w * b) / tf.reduce_sum(w)
print(apply_weight(x,w))
使用张量x
和权重w
作为输入:
w = [1, 1, 0]
x = tf.constant(
[[[1., 2.],
[5., 3.],
[6., 4.]],
[[5., 7.],
[10., 8.],
[11., 9.]]]
)
如何输出加权 reduce_mean 张量 y?
y = tf.constant(
[[w[0]*[1., 2.],
w[1]*[5., 3.],
w[2]*[6., 4.]],
[w[0]*[5., 7.],
w[1]*[10., 8.],
w[2]*[11., 9.]]]
)
预期结果是(均值是用总和除以1
的权重):
y = tf.constant(
[[3., 2.5]],
[[7.5, 7.5]]
)
检查这段代码,它给出了你想要的答案,解决方案是多次使用 map_fn
。
w = tf.constant([1.0, 1.0, 0.0])
x = tf.constant(
[[[1., 2.],
[5., 3.],
[6., 4.]],
[[5., 7.],
[10., 8.],
[11., 9.]]]
)
def apply_weight(x, w):
return tf.map_fn(mult, x)
def mult(a):
transposed_a = tf.transpose(a)
return tf.map_fn(mult_pars, transposed_a)
def mult_pars(b):
return tf.reduce_sum(w * b) / tf.reduce_sum(w)
print(apply_weight(x,w))