Simple TensorFlow2 function - tf.data.Dataset.from_tensor_slices

Category: General Catalog of "TensorFlow2 Functions Explained in Simple Ways"


Returns a dataset whose elements are slices of the given tensor. The given tensors are sliced ​​along their first dimension. This operation preserves the structure of the input tensors, removing the first dimension of each tensor and using it as the dataset dimension. All input tensors must have the same size in their first dimension.

grammar

@staticmethod
from_tensor_slices(
    tensors, name=None
)

parameter

  • tensors: Dataset element whose components have the same first dimension. Supported values ​​are documented here.
  • name: [optional] the name of the operation

return value

one Dataset.

example

enter:

# Slicing a 1D tensor produces scalar tensor elements.
dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])
list(dataset.as_numpy_iterator())

output:

[1, 2, 3]

enter:

# Slicing a 2D tensor produces 1D tensor elements.
dataset = tf.data.Dataset.from_tensor_slices([[1, 2], [3, 4]])
list(dataset.as_numpy_iterator())

output:

[array([1, 2]), array([3, 4])]

enter:

# Dictionary structure is also preserved.
dataset = tf.data.Dataset.from_tensor_slices({"a": [1, 2], "b": [3, 4]})
list(dataset.as_numpy_iterator()) == [{'a': 1, 'b': 3},
                                      {'a': 2, 'b': 4}]

output:

True

Guess you like

Origin blog.csdn.net/hy592070616/article/details/130450024