I have a basic question about how to do indexing in TensorFlow.
In numpy:
x = np.asarray([1,2,3,3,2,5,6,7,1,3]) e = np.asarray([0,1,0,1,1,1,0,1]) #numpy print x * e[x]
I can get
[1 0 3 3 0 5 0 7 1 3]
How can I do this in TensorFlow?
x = np.asarray([1,2,3,3,2,5,6,7,1,3]) e = np.asarray([0,1,0,1,1,1,0,1]) x_t = tf.constant(x) e_t = tf.constant(e) with tf.Session(): ????
Thanks!
You can use tf. slice on higher dimensional tensors as well. You can also use tf. strided_slice to extract slices of tensors by 'striding' over the tensor dimensions.
Tensor is not simply a multidimensional array. Tensor is "something" which can be represented as multidimensional array. And this representation must depend in some very specific way from where you are looking at this "something".
transpose(x, perm=[1, 0]) . As above, simply calling tf. transpose will default to perm=[2,1,0] . To take the transpose of the matrices in dimension-0 (such as when you are transposing matrices where 0 is the batch dimension), you would set perm=[0,2,1] .
Fortunately, the exact case you're asking about is supported in TensorFlow by tf.gather()
:
result = x_t * tf.gather(e_t, x_t) with tf.Session() as sess: print sess.run(result) # ==> 'array([1, 0, 3, 3, 0, 5, 0, 7, 1, 3])'
The tf.gather()
op is less powerful than NumPy's advanced indexing: it only supports extracting full slices of a tensor on its 0th dimension. Support for more general indexing has been requested, and is being tracked in this GitHub issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With