map() 与 nest.map_structure() 的区别及用法

部署运行你感兴趣的模型镜像

map() 是python自带的函数

nest.map_structure() 是tensorflow中定义的功能类似于 map() 的函数

先看一下参数对比
map(func, *iterables)
nest.map_structure(func, *structure, **check_types_dict)
相同:
两者都是对一个可循环结构的元素依次应用函数的过程。
不同的是:
map()返回一个map 类对象,
map_structure()返回一个与参数structure有相同类型的structure。
看下面的小例子,可以很清晰的显示我所说的:


from tensorflow.python.util import nest

def function(x):
    return x**2

map_result = map(function,[1,2,3])
nest_map_result = nest.map_structure(function,[1,2,3])

print("--------map_result_information--------")
print("map_result=",map_result)
print("type(map_result)=",type(map_result))
print("list(map_result)=",list(map_result))

print("\n--------nes_map_result_information--------")
print("nest_map_result=",nest_map_result)
print("type(nest_map_result)=",type(nest_map_result))

运行结果如下:

--------map_result_information--------
map_result= <map object at 0x7fb153eb59b0>
type(map_result)= <class 'map'>
list(map_result)= [1, 4, 9]

--------nes_map_result_information--------
nest_map_result= [1, 4, 9]
type(nest_map_result)= <class 'list'>

也就是说,两个函数都是对list[1,2,3]中的每个元素应用函数function(),
map()返回一个map()对象,我们需要转化为list结构。
map_structure(),因为传入的参数是list,所以返回值也是list结构。


参考:https://blog.youkuaiyun.com/weixin_41700555/article/details/85011957

 

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-5-007174b1c6e7> in <module> 4 base_model=InceptionV3(weights=r'C:\Users\Administrator\Desktop\model\inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5',include_top=False) 5 x=base_model.output ----> 6 x=GlobalAveragePooling2D()(x) 7 predictions=Dense(2,activation='softmax')(x) 8 model=Model(inputs=base_model.input,outputs=predictions) E:\anaconda\envs\Text\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs) 872 kwargs.pop('mask') 873 inputs, outputs = self._set_connectivity_metadata_( --> 874 inputs, outputs, args, kwargs) 875 self._handle_activity_regularization(inputs, outputs) 876 self._set_mask_metadata(inputs, outputs, input_masks) E:\anaconda\envs\Text\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in _set_connectivity_metadata_(self, inputs, outputs, args, kwargs) 2036 # This updates the layer history of the output tensor(s). 2037 self._add_inbound_node( -> 2038 input_tensors=inputs, output_tensors=outputs, arguments=arguments) 2039 return inputs, outputs 2040 E:\anaconda\envs\Text\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in _add_inbound_node(self, input_tensors, output_tensors, arguments) 2052 """ 2053 inbound_layers = nest.map_structure(lambda t: t._keras_history.layer, -> 2054 input_tensors) 2055 node_indices = nest.map_structure(lambda t: t._keras_history.node_index, 2056 input_tensors) E:\anaconda\envs\Text\lib\site-packages\tensorflow_core\python\util\nest.py in map_structure(func, *structure, **kwargs) 533 534 return pack_sequence_as( --> 535 structure[0], [func(*x) for x in entries], 536 expand_composites=expand_composites) 537 E:\anaconda\envs\Text\lib\site-packages\tensorflow_core\python\util\nest.py in <listcomp>(.0) 533 534 return pack_sequence_as( --> 535 structure[0], [func(*x) for x in entries], 536 expand_composites=expand_composites) 537 E:\anaconda\envs\Text\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in <lambda>(t) 2051 `call` method of the layer at the call that created the node. 2052 """ -> 2053 inbound_layers = nest.map_structure(lambda t: t._keras_history.layer, 2054 input_tensors) 2055 node_indices = nest.map_structure(lambda t: t._keras_history.node_index, AttributeError: 'tuple' object has no attribute 'layer'
10-23
源代码import jieba import numpy as np import matplotlib.pyplot as plt from keras.models import Model from keras.layers import Input, Embedding, Bidirectional, LSTM, Dense, Dropout from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras import backend as K from tensorflow import kerasimport warnings from keras.src.api_export import keras_export from keras.src.utils.module_utils import dmtree from keras.src.utils.module_utils import optree if optree.available: from keras.src.tree import optree_impl as tree_impl elif dmtree.available: from keras.src.tree import dmtree_impl as tree_impl else: raise ImportError( "To use Keras, you need to have `optree` installed. " "Install it via `pip install optree`" ) def register_tree_node_class(cls): return tree_impl.register_tree_node_class(cls) @keras_export("keras.tree.MAP_TO_NONE") class MAP_TO_NONE: """Special value for use with `traverse()`.""" pass @keras_export("keras.tree.is_nested") def is_nested(structure): """Checks if a given structure is nested. Examples: >>> keras.tree.is_nested(42) False >>> keras.tree.is_nested({"foo": 42}) True Args: structure: A structure to check. Returns: `True` if a given structure is nested, i.e. is a sequence, a mapping, or a namedtuple, and `False` otherwise. """ return tree_impl.is_nested(structure) @keras_export("keras.tree.traverse") def traverse(func, structure, top_down=True): """Traverses the given nested structure, applying the given function. The traversal is depth-first. If `top_down` is True (default), parents are returned before their children (giving the option to avoid traversing into a sub-tree). Examples: >>> v = [] >>> keras.tree.traverse(v.append, [(1, 2), [3], {"a": 4}], top_down=True) [(1, 2), [3], {'a': 4}] >>> v [[(1
03-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值