通过将 func 应用于 structure 中的每个原子来创建新结构。
用法
tf.nest.map_structure(
func, *structure, **kwargs
)参数
-
func接受与结构一样多的参数的可调用对象。 -
*structure原子或嵌套结构。 -
**kwargs有效的关键字参数是:check_types:如果设置为True(默认),则结构中的迭代类型必须相同(例如map_structure(func, [1], (1,))引发TypeError异常)。要允许这样做,请将此参数设置为False。请注意,具有相同名称和字段的命名元组始终被认为具有相同的浅层结构。expand_composites:如果设置为True,则复合张量如tf.sparse.SparseTensor和tf.RaggedTensor将扩展为它们的分量张量。如果False(默认),则复合张量不展开。
返回
-
与
structure[0]具有相同数量的新结构,其原子对应于func(x[0], x[1], ...)其中x[i]是structure[i]中相应位置的原子。如果有不同的结构类型并且check_types是False,则将使用第一个结构的结构类型。
抛出
-
TypeError如果func不可调用,或者结构不通过深度树相互匹配。 -
ValueError如果没有提供结构或者结构在类型上不匹配。 -
ValueError如果提供了错误的关键字参数。
有关结构的定义,请参阅tf.nest。
应用 func(x[0], x[1], ...) 其中 x[i] 枚举 structure[i] 中的所有原子。 structure 中的所有项目必须具有相同的数量,并且返回值将包含具有相同结构布局的结果。
例子:
- 一个 Python 字典:
a = {"hello":24, "world":76}
tf.nest.map_structure(lambda p:p * 2, a)
{'hello':48, 'world':152}
- 多个 Python 字典:
d1 = {"hello":24, "world":76}
d2 = {"hello":36, "world":14}
tf.nest.map_structure(lambda p1, p2:p1 + p2, d1, d2)
{'hello':60, 'world':90}
- 一个 Python 列表:
a = [24, 76, "ab"]
tf.nest.map_structure(lambda p:p * 2, a)
[48, 152, 'abab']
- 标量:
tf.nest.map_structure(lambda x, y:x + y, 3, 4)
7
- 空结构:
tf.nest.map_structure(lambda x:x + 1, ())
()
- 检查可迭代的类型:
s1 = (((1, 2), 3), 4, (5, 6))
s1_list = [[[1, 2], 3], 4, [5, 6]]
tf.nest.map_structure(lambda x, y:None, s1, s1_list)
Traceback (most recent call last):
TypeError:The two structures don't have the same nested structure
- 类型检查设置为 False:
s1 = (((1, 2), 3), 4, (5, 6))
s1_list = [[[1, 2], 3], 4, [5, 6]]
tf.nest.map_structure(lambda x, y:None, s1, s1_list, check_types=False)
(((None, None), None), None, (None, None))
相关用法
- Python tf.nest.is_nested用法及代码示例
- Python tf.nest.assert_same_structure用法及代码示例
- Python tf.nest.flatten用法及代码示例
- Python tf.nest.pack_sequence_as用法及代码示例
- Python tf.nn.embedding_lookup_sparse用法及代码示例
- Python tf.nn.RNNCellResidualWrapper.set_weights用法及代码示例
- Python tf.nn.dropout用法及代码示例
- Python tf.nn.gelu用法及代码示例
- Python tf.nn.RNNCellDeviceWrapper.set_weights用法及代码示例
- Python tf.no_gradient用法及代码示例
- Python tf.nn.embedding_lookup用法及代码示例
- Python tf.numpy_function用法及代码示例
- Python tf.nn.RNNCellDeviceWrapper.get_weights用法及代码示例
- Python tf.nn.local_response_normalization用法及代码示例
- Python tf.nn.scale_regularization_loss用法及代码示例
- Python tf.nn.RNNCellResidualWrapper.add_loss用法及代码示例
- Python tf.nn.max_pool用法及代码示例
- Python tf.nn.RNNCellDropoutWrapper.set_weights用法及代码示例
- Python tf.nn.l2_loss用法及代码示例
- Python tf.nn.log_softmax用法及代码示例
注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.nest.map_structure。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
