tf.nest.pack_sequence_as
Stay organized with collections
Save and categorize content based on your preferences.
Returns a given flattened sequence packed into a given structure.
tf.nest.pack_sequence_as(
structure, flat_sequence, expand_composites=False
)
Used in the notebooks
Refer to tf.nest
for the definition of a structure.
If structure
is an atom, flat_sequence
must be a single-item list;
in this case the return value is flat_sequence[0]
.
If structure
is or contains a dict instance, the keys will be sorted to
pack the flat sequence in deterministic order. 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 flatten
.
This correctly repacks dicts and OrderedDict
s 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.
Examples:
Python dict:
structure = { "key3": "", "key1": "", "key2": "" }
flat_sequence = ["value1", "value2", "value3"]
tf.nest.pack_sequence_as(structure, flat_sequence)
{'key3': 'value3', 'key1': 'value1', 'key2': 'value2'}
For a nested python tuple:
structure = (('a','b'), ('c','d','e'), 'f')
flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
tf.nest.pack_sequence_as(structure, flat_sequence)
((1.0, 2.0), (3.0, 4.0, 5.0), 6.0)
For a nested dictionary of dictionaries:
structure = { "key3": {"c": ('alpha', 'beta'), "a": ('gamma')},
"key1": {"e": "val1", "d": "val2"} }
flat_sequence = ['val2', 'val1', 3.0, 1.0, 2.0]
tf.nest.pack_sequence_as(structure, flat_sequence)
{'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'} }
Numpy array (considered a scalar):
structure = ['a']
flat_sequence = [np.array([[1, 2], [3, 4]])]
tf.nest.pack_sequence_as(structure, flat_sequence)
[array([[1, 2],
[3, 4]])]
tf.Tensor (considered a scalar):
structure = ['a']
flat_sequence = [tf.constant([[1., 2., 3.], [4., 5., 6.]])]
tf.nest.pack_sequence_as(structure, flat_sequence)
[<tf.Tensor: shape=(2, 3), dtype=float32,
numpy= array([[1., 2., 3.], [4., 5., 6.]], 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 treat RaggedTensor as a scalar.
structure = { "foo": tf.ragged.constant([[1, 2], [3]]),
"bar": tf.constant([[5]]) }
flat_sequence = [ "one", "two" ]
tf.nest.pack_sequence_as(structure, flat_sequence,
expand_composites=False)
{'foo': 'two', 'bar': 'one'}
With expand_composites=True
, we expect that the flattened input contains
the tensors making up the ragged tensor i.e. the values and row_splits
tensors.
structure = { "foo": tf.ragged.constant([[1., 2.], [3.]]),
"bar": tf.constant([[5.]]) }
tensors = tf.nest.flatten(structure, expand_composites=True)
print(tensors)
[<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]],
dtype=float32)>,
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 2., 3.],
dtype=float32)>,
<tf.Tensor: shape=(3,), dtype=int64, numpy=array([0, 2, 3])>]
verified_tensors = [tf.debugging.check_numerics(t, 'invalid tensor: ')
if t.dtype==tf.float32 else t
for t in tensors]
tf.nest.pack_sequence_as(structure, verified_tensors,
expand_composites=True)
{'foo': <tf.RaggedTensor [[1.0, 2.0], [3.0]]>,
'bar': <tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]],
dtype=float32)>}
Args |
structure
|
Nested structure, whose structure is given by nested lists,
tuples, and dicts. Note: numpy arrays and strings are considered
scalars.
|
flat_sequence
|
flat sequence to pack.
|
expand_composites
|
If true, then composite tensors such as
tf.sparse.SparseTensor and tf.RaggedTensor are expanded into their
component tensors.
|
Returns |
packed
|
flat_sequence converted to have the same recursive structure as
structure .
|
Raises |
ValueError
|
If flat_sequence and structure have different
atom counts.
|
TypeError
|
structure 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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-04-26 UTC."],[],[],null,["# tf.nest.pack_sequence_as\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#L423-L539) |\n\nReturns a given flattened sequence packed into 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.pack_sequence_as`](https://www.tensorflow.org/api_docs/python/tf/nest/pack_sequence_as)\n\n\u003cbr /\u003e\n\n tf.nest.pack_sequence_as(\n structure, flat_sequence, expand_composites=False\n )\n\n### Used in the notebooks\n\n| Used in the tutorials |\n|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| - [Variational Inference on Probabilistic Graphical Models with Joint Distributions](https://www.tensorflow.org/probability/examples/Variational_Inference_and_Joint_Distributions) - [Substantial Undocumented Infection Facilitates the Rapid Dissemination of Novel Coronavirus (SARS-CoV2)](https://www.tensorflow.org/probability/examples/Undocumented_Infection_and_the_Dissemination_of_SARS-CoV2) - [Networks](https://www.tensorflow.org/agents/tutorials/8_networks_tutorial) - [Random noise generation in TFF](https://www.tensorflow.org/federated/tutorials/random_noise_generation) - [Bayesian Modeling with Joint Distribution](https://www.tensorflow.org/probability/examples/Modeling_with_JointDistribution) |\n\nRefer to [tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)\nfor the definition of a structure.\n\nIf `structure` is an atom, `flat_sequence` must be a single-item list;\nin this case the return value is `flat_sequence[0]`.\n\nIf `structure` is or contains a dict instance, the keys will be sorted to\npack the flat sequence in deterministic order. This is true also for\n`OrderedDict` instances: their sequence order is ignored, the sorting order of\nkeys is used instead. The same convention is followed in `flatten`.\nThis correctly repacks dicts and `OrderedDict`s after they have been\nflattened, and also allows flattening an `OrderedDict` and then repacking it\nback using a corresponding plain dict, or vice-versa.\nDictionaries with non-sortable keys cannot be flattened.\n\n#### Examples:\n\n1. Python dict:\n\n structure = { \"key3\": \"\", \"key1\": \"\", \"key2\": \"\" }\n flat_sequence = [\"value1\", \"value2\", \"value3\"]\n tf.nest.pack_sequence_as(structure, flat_sequence)\n {'key3': 'value3', 'key1': 'value1', 'key2': 'value2'}\n \n2. For a nested python tuple:\n\n structure = (('a','b'), ('c','d','e'), 'f')\n flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]\n tf.nest.pack_sequence_as(structure, flat_sequence)\n ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0)\n \n3. For a nested dictionary of dictionaries:\n\n structure = { \"key3\": {\"c\": ('alpha', 'beta'), \"a\": ('gamma')},\n \"key1\": {\"e\": \"val1\", \"d\": \"val2\"} }\n flat_sequence = ['val2', 'val1', 3.0, 1.0, 2.0]\n tf.nest.pack_sequence_as(structure, flat_sequence)\n {'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'} }\n \n4. Numpy array (considered a scalar):\n\n structure = ['a']\n flat_sequence = [np.array([[1, 2], [3, 4]])]\n tf.nest.pack_sequence_as(structure, flat_sequence)\n [array([[1, 2],\n [3, 4]])]\n \n5. tf.Tensor (considered a scalar):\n\n structure = ['a']\n flat_sequence = [tf.constant([[1., 2., 3.], [4., 5., 6.]])]\n tf.nest.pack_sequence_as(structure, flat_sequence)\n [\u003ctf.Tensor: shape=(2, 3), dtype=float32,\n numpy= array([[1., 2., 3.], [4., 5., 6.]], 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 treat RaggedTensor as a scalar.\n\n\u003cbr /\u003e\n\n structure = { \"foo\": tf.ragged.constant([[1, 2], [3]]),\n \"bar\": tf.constant([[5]]) }\n flat_sequence = [ \"one\", \"two\" ]\n tf.nest.pack_sequence_as(structure, flat_sequence,\n expand_composites=False)\n {'foo': 'two', 'bar': 'one'}\n \n \n\u003cbr /\u003e\n\nWith `expand_composites=True`, we expect that the flattened input contains\nthe tensors making up the ragged tensor i.e. the values and row_splits\ntensors.\n\n\u003cbr /\u003e\n\n structure = { \"foo\": tf.ragged.constant([[1., 2.], [3.]]),\n \"bar\": tf.constant([[5.]]) }\n tensors = tf.nest.flatten(structure, expand_composites=True)\n print(tensors)\n [\u003ctf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]],\n dtype=float32)\u003e,\n \u003ctf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 2., 3.],\n dtype=float32)\u003e,\n \u003ctf.Tensor: shape=(3,), dtype=int64, numpy=array([0, 2, 3])\u003e]\n verified_tensors = [tf.debugging.check_numerics(t, 'invalid tensor: ')\n if t.dtype==tf.float32 else t\n for t in tensors]\n tf.nest.pack_sequence_as(structure, verified_tensors,\n expand_composites=True)\n {'foo': \u003ctf.RaggedTensor [[1.0, 2.0], [3.0]]\u003e,\n 'bar': \u003ctf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[5.]],\n dtype=float32)\u003e}\n \n \n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ---- ||\n|---------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `structure` | Nested structure, whose structure is given by nested lists, tuples, and dicts. Note: numpy arrays and strings are considered scalars. |\n| `flat_sequence` | flat sequence to pack. |\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| `packed` | `flat_sequence` converted to have the same recursive structure as `structure`. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Raises ------ ||\n|--------------|----------------------------------------------------------------|\n| `ValueError` | If `flat_sequence` and `structure` have different atom counts. |\n| `TypeError` | `structure` is or contains a dict with non-sortable keys. |\n\n\u003cbr /\u003e"]]