Create supervised datasets from features and labels
Training from in-memory arrays
TensorFlow · Module
Creates a Dataset by slicing supplied tensors along their first dimension. Each resulting element preserves the input structure and contains one corresponding slice.
The method builds a dataset by taking corresponding slices along the first dimension of the supplied tensors. It removes that dimension from each element while retaining the tensors’ nested structure, so tuples or dictionaries become structured dataset elements.
tf.data.Dataset.from_tensor_slices(tensors, name=None) -> 'DatasetV2'| Name | Type | Description |
|---|---|---|
tensors | Tensors or nested structures of tensors | The tensors or nested tensor structure to slice along the first dimension. Inputs supplied together must have matching first-dimension sizes. |
name | string | Optional name for the operation. |
A DatasetV2 whose elements are first-dimension slices of the supplied tensors, with the input structure preserved.
import tensorflow as tf
features = tf.constant([[1, 10], [2, 20], [3, 30]])
labels = tf.constant([0, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
for feature, label in dataset:
print(feature.numpy(), label.numpy())Creates three dataset elements, each pairing one row of features with the corresponding label.
Training from in-memory arrays
Iterating over rows or examples
Preserving structured inputs
It returns a Dataset whose elements are formed from first-dimension slices of the input. The first dimension becomes the dataset length, and that dimension is removed from each produced element.
Follow-up: What happens when a 2D tensor is supplied? Each row becomes one 1D tensor element, preserving the remaining dimensions.
All inputs are sliced along dimension zero in lockstep. Therefore, their first dimensions must have the same size so each produced element can contain corresponding pieces.
Follow-up: How would you represent paired inputs such as examples and labels? Pass them as a tuple, producing tuple-shaped dataset elements.
A 1D input produces scalar elements, while a 2D input produces 1D elements. Nested input structures are retained in the resulting dataset element specification.
Follow-up: When should from_tensors be used instead? Use it when the entire input should be one dataset element rather than several slices.
tf.data.Dataset.from_tensorstf.data.Dataset.batchtf.data.Dataset.maptf.data.Dataset.as_numpy_iterator