tf.nest.flatten
Stay organized with collections
Save and categorize content based on your preferences.
Returns a flat list from a given structure.
tf.nest.flatten(
structure, expand_composites=False
)
Used in the notebooks
Used in the guide |
Used in the tutorials |
|
|
Refer to tf.nest
for the definition of a structure.
If the structure is an atom, then returns a single-item list: [structure].
This is the inverse of the nest.pack_sequence_as
method that takes in a
flattened list and re-packs it into the nested structure.
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 nest.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:
Python dict (ordered by key):
dict = { "key3": "value3", "key1": "value1", "key2": "value2" }
tf.nest.flatten(dict)
['value1', 'value2', 'value3']
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]
For a nested dictionary of dictionaries:
dict = { "key3": {"c": (1.0, 2.0), "a": (3.0)},
"key1": {"m": "val1", "g": "val2"} }
tf.nest.flatten(dict)
['val2', 'val1', 3.0, 1.0, 2.0]
Numpy array (will not flatten):
array = np.array([[1, 2], [3, 4]])
tf.nest.flatten(array)
[array([[1, 2],
[3, 4]])]
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)>]
tf.RaggedTensor
: This is a composite tensor thats representation consists
of a flattened list of 'values' and a list of 'row_splits' which indicate how
to chop up the flattened list into different rows. For more details on
tf.RaggedTensor
, please visit
https://www.tensorflow.org/api_docs/python/tf/RaggedTensor.
with expand_composites=False
, we just return the RaggedTensor as is.
tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]])
tf.nest.flatten(tensor, expand_composites=False)
[<tf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2]]>]
with expand_composites=True
, we return the component Tensors that make up
the RaggedTensor representation (the values and row_splits tensors)
tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]])
tf.nest.flatten(tensor, expand_composites=True)
[<tf.Tensor: shape=(7,), dtype=int32, numpy=array([3, 1, 4, 1, 5, 9, 2],
dtype=int32)>,
<tf.Tensor: shape=(4,), dtype=int64, numpy=array([0, 4, 4, 7])>]
Args |
structure
|
an atom or a 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.
|
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Some content is licensed under the numpy license.
Last updated 2024-04-26 UTC.
[null,null,["Last updated 2024-04-26 UTC."],[],[],null,["# tf.nest.flatten\n\n\u003cbr /\u003e\n\n|-------------------------------------------------------------------------------------------------------------------------|\n| [View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.16.1/tensorflow/python/util/nest.py#L198-L295) |\n\nReturns a flat list from a given structure.\n\n#### View aliases\n\n\n**Compat aliases for migration**\n\nSee\n[Migration guide](https://www.tensorflow.org/guide/migrate) for\nmore details.\n\n[`tf.compat.v1.nest.flatten`](https://www.tensorflow.org/api_docs/python/tf/nest/flatten)\n\n\u003cbr /\u003e\n\n tf.nest.flatten(\n structure, expand_composites=False\n )\n\n### Used in the notebooks\n\n| Used in the guide | Used in the tutorials |\n|--------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| - [Import a JAX model using JAX2TF](https://www.tensorflow.org/guide/jax2tf) - [Working with RNNs](https://www.tensorflow.org/guide/keras/working_with_rnns) | - [Custom Federated Algorithms, Part 2: Implementing Federated Averaging](https://www.tensorflow.org/federated/tutorials/custom_federated_algorithms_2) - [Bayesian Modeling with Joint Distribution](https://www.tensorflow.org/probability/examples/Modeling_with_JointDistribution) - [Variational Inference on Probabilistic Graphical Models with Joint Distributions](https://www.tensorflow.org/probability/examples/Variational_Inference_and_Joint_Distributions) - [TensorFlow 2 TPUEmbeddingLayer: Quick Start](https://www.tensorflow.org/recommenders/examples/tpu_embedding_layer) - [Networks](https://www.tensorflow.org/agents/tutorials/8_networks_tutorial) |\n\nRefer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)\nfor the definition of a structure.\n\nIf the structure is an atom, then returns a single-item list: \\[structure\\].\n\nThis is the inverse of the [`nest.pack_sequence_as`](../../tf/nest/pack_sequence_as) method that takes in a\nflattened list and re-packs it into the nested structure.\n\nIn the case of dict instances, the sequence consists of the values, sorted by\nkey to ensure deterministic behavior. This is true also for OrderedDict\ninstances: their sequence order is ignored, the sorting order of keys is used\ninstead. The same convention is followed in [`nest.pack_sequence_as`](../../tf/nest/pack_sequence_as). This\ncorrectly repacks dicts and OrderedDicts after they have been flattened, and\nalso allows flattening an OrderedDict and then repacking it back using a\ncorresponding plain dict, or vice-versa. Dictionaries with non-sortable keys\ncannot be flattened.\n\nUsers must not modify any collections used in nest while this function is\nrunning.\n\n#### Examples:\n\n1. Python dict (ordered by key):\n\n dict = { \"key3\": \"value3\", \"key1\": \"value1\", \"key2\": \"value2\" }\n tf.nest.flatten(dict)\n ['value1', 'value2', 'value3']\n \n2. For a nested python tuple:\n\n tuple = ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0)\n tf.nest.flatten(tuple)\n [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]\n \n3. For a nested dictionary of dictionaries:\n\n dict = { \"key3\": {\"c\": (1.0, 2.0), \"a\": (3.0)},\n \"key1\": {\"m\": \"val1\", \"g\": \"val2\"} }\n tf.nest.flatten(dict)\n ['val2', 'val1', 3.0, 1.0, 2.0]\n \n4. Numpy array (will not flatten):\n\n array = np.array([[1, 2], [3, 4]])\n tf.nest.flatten(array)\n [array([[1, 2],\n [3, 4]])]\n \n5. [`tf.Tensor`](../../tf/Tensor) (will not flatten):\n\n tensor = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])\n tf.nest.flatten(tensor)\n [\u003ctf.Tensor: shape=(3, 3), dtype=float32, numpy=\n array([[1., 2., 3.],\n [4., 5., 6.],\n [7., 8., 9.]], dtype=float32)\u003e]\n \n6. [`tf.RaggedTensor`](../../tf/RaggedTensor): This is a composite tensor thats representation consists\n of a flattened list of 'values' and a list of 'row_splits' which indicate how\n to chop up the flattened list into different rows. For more details on\n [`tf.RaggedTensor`](../../tf/RaggedTensor), please visit\n https://www.tensorflow.org/api_docs/python/tf/RaggedTensor.\n\nwith `expand_composites=False`, we just return the RaggedTensor as is.\n\n\u003cbr /\u003e\n\n tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]])\n tf.nest.flatten(tensor, expand_composites=False)\n [\u003ctf.RaggedTensor [[3, 1, 4, 1], [], [5, 9, 2]]\u003e]\n \n \n\u003cbr /\u003e\n\nwith `expand_composites=True`, we return the component Tensors that make up\nthe RaggedTensor representation (the values and row_splits tensors)\n\n\u003cbr /\u003e\n\n tensor = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2]])\n tf.nest.flatten(tensor, expand_composites=True)\n [\u003ctf.Tensor: shape=(7,), dtype=int32, numpy=array([3, 1, 4, 1, 5, 9, 2],\n dtype=int32)\u003e,\n \u003ctf.Tensor: shape=(4,), dtype=int64, numpy=array([0, 4, 4, 7])\u003e]\n \n \n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ---- ||\n|---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `structure` | an atom or a nested structure. Note, numpy arrays are considered atoms and are not flattened. |\n| `expand_composites` | If true, then composite tensors such as [`tf.sparse.SparseTensor`](../../tf/sparse/SparseTensor) and [`tf.RaggedTensor`](../../tf/RaggedTensor) are expanded into their component tensors. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Returns ------- ||\n|---|---|\n| A Python list, the flattened version of the input. ||\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Raises ------ ||\n|-------------|--------------------------------------------------------|\n| `TypeError` | The nest is or contains a dict with non-sortable keys. |\n\n\u003cbr /\u003e"]]