TL;DR:
TensorFlow tensor is of shape (50, 50, 6)
, want these indices (:, :, (0, 2, 3)). How to extract them?
Here is an example array I am working with:
import numpy as np
a = np.random.randint(0,10, (50, 50, 6))
I want to extract the the first, third, and fourth row; in other words I need all these entries (:, :, (1, 3))
, which works for numpy arrays:
out = a[:,:, [0, 2, 3]]
out.shape #(50, 50, 3)
Working with a tensor t = tf.convert_to_tensor(a)
and then calling the index like
t[:,:, [0, 2, 3]]
throws an error:
TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got [0, 1, 3]
For numpy I have found the following relevant questions, but they naturally focus on numpy arrays:
How to slice a 2D array non-consecutively in Python
Slicing a numpy array along a dynamically specified axis
Looking at the TF documentation I found gather_nd
and boolean_mask
, which I feel are helpful, but I must freely admit that I have not understood the docs at this part. On SO I found this question How to select elements of a tensor along a specific axis in TensorFlow, which focuses on single elements; I am looking for complete dimensions (if that's the right wording here).
How can I do the numpy thing in TensorFlow?