'How to modify values of a column of a 2D tensor based on condition - Tensorflow?
I have a 2D tensor and want values of its last column to be 0 if values > 0 and 1 otherwise. It should behave somewhat similar to the following block of numpy code:
x = np.random.rand(8, 4)
x[:, -1] = np.where(x[:, -1] > 0, 0, 1)
Is there a way to achieve the same behavior for a 2D tensor in Tensorflow?
Solution 1:[1]
This might not be the most elegant solution, but it works:
x=tf.ones((5,10))
rows=tf.stack(tf.range(tf.shape(x)[0]))
column=tf.ones_like(rows)*tf.shape(x)[1]-1
idx=tf.stack((rows,column),axis=1)
x_new=tf.tensor_scatter_nd_update(x, idx, tf.where(x[:, -1] > 0, 0., 1.))
print(x_new)
And the result looks like this (the original x is a tf.ones):
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 0.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 0.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 0.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 0.]
[1. 1. 1. 1. 1. 1. 1. 1. 1. 0.]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Franciska Rajki |
