Functions that work with structures.
A structure of type T
is a structure whose atomic items are of type T
. For example, a structure of tf.Tensor
only contains tf.Tensor
as its atoms.
Historically a nested structure was called a nested sequence in TensorFlow. A nested structure is sometimes called a nest or a tree, but the formal name nested structure is preferred.
Refer to Nesting Data Structures.
The following collection types are recognized by tf.nest
as nested structures:
collections.abc.Sequence
(except string
and bytes
). This includes list
, tuple
, and namedtuple
.collections.abc.Mapping
(with sortable keys). This includes dict
and collections.OrderedDict
.collections.abc.MappingView
(with sortable keys).attr.s
classes.Any other values are considered atoms. Not all collection types are considered nested structures. For example, the following types are considered atoms:
set
; {"a", "b"}
is an atom, while ["a", "b"]
is a nested structure.dataclass
classestf.Tensor
numpy.array
tf.nest.is_nested
checks whether an object is a nested structure or an atom. For example:
tf.nest.is_nested("1234") False tf.nest.is_nested([1, 3, [4, 5]]) True tf.nest.is_nested(((7, 8), (5, 6))) True tf.nest.is_nested([]) True tf.nest.is_nested({"a": 1, "b": 2}) True tf.nest.is_nested({"a": 1, "b": 2}.keys()) True tf.nest.is_nested({"a": 1, "b": 2}.values()) True tf.nest.is_nested({"a": 1, "b": 2}.items()) True tf.nest.is_nested(set([1, 2])) False ones = tf.ones([2, 3]) tf.nest.is_nested(ones) False
Note: A proper structure shall form a tree. The user shall ensure there is no cyclic references within the items in the structure, i.e., no references in the structure of the input of these functions should be recursive. The behavior is undefined if there is a cycle.
assert_same_structure(...)
: Asserts that two structures are nested in the same way.
flatten(...)
: Returns a flat list from a given structure.
is_nested(...)
: Returns true if its input is a nested structure.
map_structure(...)
: Creates a new structure by applying func
to each atom in structure
.
pack_sequence_as(...)
: Returns a given flattened sequence packed into a given structure.
© 2022 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 4.0.
Code samples licensed under the Apache 2.0 License.
https://www.tensorflow.org/versions/r2.9/api_docs/python/tf/nest