0
votes

Given a 1D tensor (just to be clear, not array): [0,2,0,1,-3], I'd like to get back just the values different than zero. Following the example, I'd like to get back [2,1,-3] as the result. How can I do that in TensorFlow.js?

1

1 Answers

1
votes
  • First we need to find the indexes of the non-zeros values by using tf.whereAsync on the tensor casted to bool. That way all values except 0 values are true and their indexes are thus collected.

  • With tf.gather we create a new tensor by collecting the values at the previous indexes.

t = tf.tensor1d([0,2,0,1,-3])
indices = await tf.whereAsync(t.cast('bool'))
tf.gather(t, indices.reshape([-1])).print()