W3cubDocs

/TensorFlow 2.4

tf.nest.flatten

Returns a flat list from a given nested structure.

If nest is not a structure , tuple (or a namedtuple), dict, or an attrs class, then returns a single-element list: [nest].

In the case of dict instances, the sequence consists of the values, sorted by key to ensure deterministic behavior. This is true also for OrderedDict instances: their sequence order is ignored, the sorting order of keys is used instead. The same convention is followed in pack_sequence_as. This correctly repacks dicts and OrderedDicts after they have been flattened, and also allows flattening an OrderedDict and then repacking it back using a corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys cannot be flattened.

Users must not modify any collections used in nest while this function is running.

Examples:

  1. Python dict (ordered by key):
dict = { "key3": "value3", "key1": "value1", "key2": "value2" }
tf.nest.flatten(dict)
['value1', 'value2', 'value3']
  1. For a nested python tuple:
tuple = ((1.0, 2.0), (3.0, 4.0, 5.0), (6.0))
tf.nest.flatten(tuple)
    [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
  1. Numpy array (will not flatten):
array = np.array([[1, 2], [3, 4]])
tf.nest.flatten(array)
    [array([[1, 2],
            [3, 4]])]
  1. tf.Tensor (will not flatten):
tensor = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
tf.nest.flatten(tensor)
    [<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
      array([[1., 2., 3.],
             [4., 5., 6.],
             [7., 8., 9.]], dtype=float32)>]
Args
structure an arbitrarily nested structure. Note, numpy arrays are considered atoms and are not flattened.
expand_composites If true, then composite tensors such as tf.sparse.SparseTensor and tf.RaggedTensor are expanded into their component tensors.
Returns
A Python list, the flattened version of the input.
Raises
TypeError The nest is or contains a dict with non-sortable keys.

© 2020 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.
https://www.tensorflow.org/versions/r2.4/api_docs/python/tf/nest/flatten