简体   繁体   中英

Tensor weighted mean reduce

Using a tensor x and weights w as input:

w = [1, 1, 0]
x = tf.constant(
    [[[1., 2.],
      [5., 3.],
      [6., 4.]],

     [[5., 7.],
      [10., 8.],
      [11., 9.]]]
)


How could someone output the weighted reduce_mean tensor 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.]]]
)

The expected result is (mean is calculated dividing the sum by the amount of 1 in weights):

y = tf.constant(
    [[3., 2.5]],

     [[7.5, 7.5]]
)

Check this code, it gives the answer you want, the solution was to use map_fn multiple times.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM