TensorFlow
Tensor
Random Slice
Machine Learning
Deep Learning

Extract random slice from tensor in Tensorflow

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Extracting a random slice from a tensor usually means choosing a valid random starting index and then taking a fixed-size window from that position. TensorFlow gives you the building blocks for this directly, but you need to compute the legal index range so the slice stays inside the tensor bounds.

The exact code depends on the tensor rank. The general pattern is the same for vectors, matrices, and higher-dimensional tensors: compute the slice size, compute the maximum starting offset, sample a random offset, then apply tf.slice or a specialized helper.

A Simple 1D Example

For a one-dimensional tensor, the logic is straightforward:

python
1import tensorflow as tf
2
3tensor = tf.constant([10, 20, 30, 40, 50, 60, 70, 80])
4slice_length = 3
5
6max_start = tf.shape(tensor)[0] - slice_length + 1
7start = tf.random.uniform([], minval=0, maxval=max_start, dtype=tf.int32)
8
9random_slice = tf.slice(tensor, [start], [slice_length])
10print(random_slice.numpy())

If the tensor has length 8 and the slice length is 3, then valid starts are 0 through 5. The + 1 matters because the upper bound in tf.random.uniform is exclusive.

A 2D Random Slice

For a matrix or image-like tensor, you do the same calculation per dimension:

python
1import tensorflow as tf
2
3tensor = tf.reshape(tf.range(1, 26), (5, 5))
4slice_height = 2
5slice_width = 3
6
7shape = tf.shape(tensor)
8max_row = shape[0] - slice_height + 1
9max_col = shape[1] - slice_width + 1
10
11start_row = tf.random.uniform([], 0, max_row, dtype=tf.int32)
12start_col = tf.random.uniform([], 0, max_col, dtype=tf.int32)
13
14random_slice = tf.slice(
15    tensor,
16    begin=[start_row, start_col],
17    size=[slice_height, slice_width]
18)
19
20print(tensor.numpy())
21print(random_slice.numpy())

This is the most general approach because it works for any tensor type as long as you know the slice size.

Use tf.image.random_crop for Image Data

If the tensor represents an image or batch of images, TensorFlow also provides a higher-level helper:

python
1import tensorflow as tf
2
3image = tf.random.uniform((256, 256, 3))
4cropped = tf.image.random_crop(image, size=(128, 128, 3))
5
6print(cropped.shape)

This is often the better choice for image augmentation because the intent is clearer and the API is built specifically for random cropping.

When You Need Reproducible Random Slices

For debugging or deterministic preprocessing, set the TensorFlow random seed before sampling indices:

python
tf.random.set_seed(42)

That makes the sampled offsets reproducible across runs of the same program, which is useful when you are comparing preprocessing behavior or tracking down a bug in an augmentation pipeline.

The same idea also works inside a tf.data.Dataset.map pipeline, as long as the slice size is known and valid for each element being processed.

General Rule for Valid Random Starts

For each dimension:

max_start = tensor_size - slice_size + 1

If that value is zero or negative, the requested slice does not fit. That is the boundary condition you should check before sampling random indices.

This matters when slice sizes come from user input or from a variable preprocessing pipeline.

Common Pitfalls

  • Forgetting that the upper bound of tf.random.uniform is exclusive.
  • Requesting a slice larger than the tensor dimension.
  • Hard-coding slice indices instead of deriving them from tf.shape, which breaks for dynamic shapes.
  • Using tf.slice for image crops when tf.image.random_crop would be clearer.
  • Mixing Python integers and tensor shapes carelessly inside graph code.

Summary

  • Random slicing in TensorFlow means sampling a valid random start index and then applying a fixed-size slice.
  • 'tf.slice is the general solution for arbitrary tensors.'
  • 'tf.image.random_crop is a convenient specialized option for image tensors.'
  • The valid start range depends on tensor size minus slice size plus one.
  • Dynamic shape handling is important if the tensor size is not known statically.

Course illustration
Course illustration

All Rights Reserved.