tensorflow Extract a slice from a tensor


Example

Refer to the tf.slice(input, begin, size) documentation for detailed information.

Arguments:

  • input: Tensor
  • begin: starting location for each dimension of input
  • size: number of elements for each dimension of input, using -1 includes all remaining elements

Numpy-like slicing:

# x has shape [2, 3, 2]
x = tf.constant([[[1., 2.], [3., 4. ], [5. , 6. ]],
                 [[7., 8.], [9., 10.], [11., 12.]]])

# Extracts x[0, 1:2, :] == [[[ 3.,  4.]]]
res = tf.slice(x, [0, 1, 0], [1, 1, -1])

Using negative indexing, to retrieve the last element in the third dimension:

# Extracts x[0, :, -1:] == [[[2.], [4.], [6.]]]
last_indice = x.get_shape().as_list()[2] - 1
res = tf.slice(x, [0, 1, last_indice], [1, -1, -1])