Reputation: 578
How can I make x
from y
where
x = tf.constant([[1,5,3], [100,20,3]])
y = ([[-1,1,-1], [1,-1,-1]])
So it basically projects the max value to 1 and makes other elements to -1. One important constraint is we should not use zero. (Because if I use zero, the gradient does not flow on that node.) Using tf.argmax
we can get the max indices but don't really know how to make y
from it.
Could you please help?
For pedagogical purpose I set x
as constant, but in the actual problem I'am solving, x
is actually a placeholder that gets inputs of a network.
Upvotes: 1
Views: 2058
Reputation: 101
Following is much cleaner solution that works for me:
y = tf.one_hot(tf.argmax(x, axis=1), x.shape[1], on_value=1, off_value=-1)
Basically, tf.argmax gives you the index of the max value along the dimension 1 and the one_hot method creates the desired tesnor.
Upvotes: 0
Reputation: 214927
You can use tf.reduce_max
to calculate the max
per row, compare with original tensor, and use tf.where
to set values conditionally:
x = tf.constant([[1,5,3], [100,20,3]])
sess = tf.InteractiveSession()
sess.run(
tf.where(
tf.equal(tf.reduce_max(x, axis=1, keep_dims=True), x),
tf.constant(1, shape=x.shape),
tf.constant(-1, shape=x.shape)
)
)
array([[-1, 1, -1],
[ 1, -1, -1]], dtype=int32)
Upvotes: 3