Let's consider a numpy matrix, o
:
If we want to use the following function by using numpy:
o[np.arange(x), column_array]
I can get multiple indices from a numpy array at once.
I have tried to do the same with tensorflow, but it doesn't work as what I have done. When o
is a tensorflow tensor;
o[tf.range(0, x, 1), column_array]
I get the following error:
TypeError: can only concatenate list (not "int") to list
What can I do?
Tensors are multi-dimensional arrays with a uniform type (called a dtype ). You can see all supported dtypes at tf. dtypes.
Single element indexing for a 1-D tensors works mostly as expected. Like R, it is 1-based. Unlike R though, it accepts negative indices for indexing from the end of the array. (In R, negative indices are used to remove elements.)
Basically to subset a tensor for some indexes [a,b,c] It needs to get in the format [[0,a],[1,b],[2,c]] and then use gather_nd() to get the subset.
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.
You can try tf.gather_nd()
, as How to select rows from a 3-D Tensor in TensorFlow? this post suggested.
Here is an example for getting multiple indices from matrix o
.
o = tf.constant([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
# [row_index, column_index], I don’t figure out how to
# combine row vector and column vector into this form.
indices = tf.constant([[0, 0], [0, 1], [2, 1], [2, 3]])
result = tf.gather_nd(o, indices)
with tf.Session() as sess:
print(sess.run(result)) #[ 1 2 10 12]
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