from_tensor_slices() is the most common starting point for building a tf.data pipeline from data already in memory — passing it an array of shape (num_examples, ...) produces a Dataset yielding num_examples separate elements, each one row/slice of the original array. Passing a tuple of arrays, like (features, labels), produces a Dataset yielding matching (feature, label) pairs, one per index, which is exactly the format model.fit() expects when training with a Dataset instead of raw arrays.
1Understanding tf.data.Dataset.from_tensor_slices()
from_tensor_slices() is the most common starting point for building a tf.data pipeline from data already in memory — passing it an array of shape (num_examples, ...) produces a Dataset yielding num_examples separate elements, each one row/slice of the original array. Passing a tuple of arrays, like (features, labels), produces a Dataset yielding matching (feature, label) pairs, one per index, which is exactly the format model.fit() expects when training with a Dataset instead of raw arrays.
Pass a tuple of (features, labels) arrays to from_tensor_slices() to build a Dataset that yields properly paired (feature, label) elements directly usable by model.fit(), rather than building the features and labels as two separate, unlinked Datasets.
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4])
for element in dataset:
print(element.numpy())2Practical Example
Here is a real-world application of tf.data.Dataset.from_tensor_slices() showing how it is used in production TensorFlow code.
import tensorflow as tf
features = [[1, 2], [3, 4], [5, 6]]
labels = [0, 1, 0]
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
for x, y in dataset:
print(x.numpy(), y.numpy())3Best Practices
Follow these guidelines when working with tf.data.Dataset.from_tensor_slices():
1. Use from_tensor_slices() as the standard starting point for building a tf.data pipeline from in-memory NumPy arrays or tensors
2. Pass features and labels together as a single tuple to from_tensor_slices() so the resulting Dataset yields matching (feature, label) pairs
3. Chain .batch(), .shuffle(), and .prefetch() after from_tensor_slices() to build a complete, efficient input pipeline rather than using the raw sliced dataset directly
Tip: Pass a tuple of (features, labels) arrays to from_tensor_slices() to build a Dataset that yields properly paired (feature, label) elements directly usable by model.fit(), rather than building the features and labels as two separate, unlinked Datasets.
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4])
for element in dataset:
print(element.numpy())