Reputation: 63
Say I have a tensor like this:
T = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12]].
I have used reduce_sum(T, 1) to get all the sums in a different tensor, but I can't seem to find a way to actually divide the sums by row. How can I divide each row by its sum in Tensorflow (i.e. divide [1,2,3,4] by 10, [5,6,7,8] by 26, etc.)?
Upvotes: 4
Views: 6969
Reputation: 222761
This is easy to achieve just by dividing your matrix element-wise by a vector which represents a sum in each dimension:
import tensorflow as tf
a = tf.constant([
[1, 2, 3, 4],
[5, 6, 7, 8]
], dtype=tf.float32)
b = tf.reduce_sum(a, axis=1)
c = a / tf.reshape(b, (-1, 1))
with tf.Session() as sess:
print sess.run(c)
Upvotes: 10