TensorFlow slice() Function Explained
The tf.slice() function extracts a contiguous slice from a tensor along specified dimensions.
tf.slice(input_, begin, size, name=None)
Parameters:
input_: The source tensor to slice from.begin: A 1-D tensor specifying the start indices for each dimension.size: A 1-D tensor specifying the number of elements to extract along each dimension.
Understanding Tensor Shape
Consider a 3D tensor:
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]])
The shape [3, 2, 3] indicates:
- 3 elements in the first dimension
- 2 elements in the second dimension
- 3 elements in the third dimension
Structurally, t cnotains three 2x3 matrices (outer dimension), where each matrix has two rows (middle dimension), and each row has three values (inner dimension).
Example 1: Basic Slicing
tf.slice(t, [1, 0, 0], [1, 1, 3])
begin = [1, 0, 0]: Start at index 1 in dimension 0, index 0 in dimension 1, index 0 in dimension 2.size = [1, 1, 3]: Extract 1 element from dimension 0, 1 element from dimension 1, 3 elements from dimension 2.
Step-by-step:
- Dimension 0: Starting from index 1, extract 1 element → selects the second matrix
- Dimension 1: Starting from index 0, extract 1 element → selects the first row
- Dimension 2: Starting from index 0, extract 3 elements → selects all three values in that row
Result:
[[[3, 3, 3]]]
Example 2: Extracting Multiple Elements
tf.slice(t, [1, 0, 0], [1, 2, 3])
begin = [1, 0, 0]: Same starting point as before.size = [1, 2, 3]: Extract 1 element from dimension 0, 2 elements from dimension 1, 3 elements from dimension 2.
Step-by-step:
- Dimension 0: Starting from index 1, extract 1 element → selects the second matrix
- Dimension 1: Starting from index 0, extract 2 elements → selects both rows
- Dimension 2: Starting from index 0, extract 3 elements → selects all three values per row
Result:
[[[3, 3, 3], [4, 4, 4]]]
Example 3: Using -1 for Remaining Elements
tf.slice(t, [1, 0, 0], [-1, -1, -1])
Setting any dimension in size to -1 includes all remaining elements in that dimension from the starting position.
When size[i] is -1, TensorFlow interprets it as:
size[i] = input.dim_size(i) - begin[i]
With begin = [1, 0, 0] and -1 for all dimension:
- Dimension 0: Extract from index 1 to the end → 2 elements (matrices at indices 1 and 2)
- Dimension 1: Extract from index 0 to the end → 2 elements (both rows)
- Dimesnion 2: Extract from index 0 to the end → 3 elements (all values)
Result:
[[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]]]
Key Points
- Python uses 0-based indexing.
- The
beginarray must not exceed the tensor's dimensions. - The
sizearray specifies the shape of the output tensor. - Using
-1in the size parameter automatically includes all remaining elements from the starting position to the end of that dimension.