简体   繁体   中英

How do I subtract the max element of each row of a 2D tensor from all elements of that row

Originally, I asked this with the global max, but the solution of just subtracting tf.reduce_max() doesn't work when you put in dimensions. I'd want something like mytensor - tf.reduce_max(mytensor, 1) but this gives a dimension error.

I can't use tf.constant(value = tf.reduce_max(mytensor,1) , shape = mytensor.get_shape()[1]) with a specified value because the output of reduce_max() is a tensor and not a constant.

For global max, you can do:

import tensorflow as tf
inp = tf.constant([[1, 2, 3],[4,5,6]
    ])
res=tf.reduce_max(inp)
res1=inp-res
sess = tf.Session()
print(sess.run(res))
print(sess.run(res1)) 

Then res is 6 and res1 is

[[-5 -4 -3]
 [-2 -1  0]]

If you want to subtract the maximum element in each row, this will do the job:

import tensorflow as tf
inp = tf.constant([[1, 2, 3],[6,6,6]
    ])
res=tf.reduce_max(inp,1)
res1=inp-tf.reshape(res,[-1,1])
sess = tf.Session()
print(sess.run(res1)) 

Then res1 is

 [[-2 -1  0]
 [ 0  0  0]]

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