Reputation: 468
I have a const python list
listA = [1, 2, 3, 23, ...]
and a tensor
tensorA = [[1, 3, 5, 7, 23,...]]
Now I want to modify to tensorA
according to listA
:
for each element
x
in tensorA, ifx
also inlistA
then keep it as it is, otherwise use the default value just like-1
.
After this transformation, tensorA
goes like
tensorB = [[1, 3, -1, -1, 23, ...]]
Is there any elegant way to do this transformation?
Upvotes: 1
Views: 181
Reputation: 59731
Since TensorFlow does not currently have anything like NumPy's isin
, you would need to do an all-to-all comparison:
import tensorflow as tf
listA = tf.constant([1, 2, 3, 23])
tensorA = tf.constant([[1, 3, 5, 7, 23]])
isInList = tf.reduce_any(tf.equal(tf.expand_dims(tensorA, axis=-1), listA), axis=-1)
tensorB = tf.where(isInList, tensorA, -1)
tf.print(tensorB)
# [[1 3 -1 -1 23]]
Upvotes: 2
Reputation: 27515
A list comprehension?
tensorB = [[n if n in listA else -1 for n in tensorA]]
Upvotes: 0