我使用 python 3.7 和 Tensorflow 2.2.0。我想从头开始训练 MobileNet-V2,因此我采用已经构建的模型并向所有所需层添加正则化器。该模型编译得很好,我能够拟合它。但是,在保存模型时,遇到以下错误:
File "/mnt/disk1/anaconda3/envs/py37/lib/python3.7/site-packages/tensorflow/python/saved_model/nested_structure_coder.py", line 82, in _map_structure
"No encoder for object [%s] of type [%s]." % (str(pyobj), type(pyobj)))
tensorflow.python.saved_model.nested_structure_coder.NotEncodableError: No encoder for object [<tensorflow.python.keras.layers.convolutional.Conv2D object at 0x7fd2f00469d0>] of type [<class 'tensorflow.python.keras.layers.convolutional.Conv2D'>].
如果不添加正则化(下面代码中的 config.regularizer.name = ""),模型可以成功拟合并保存。我想知道这是一个错误还是我在这里做错了什么?
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
model = MobileNetV2(input_shape=ds_info["shape"], classes=ds_info["n_classes"], weights=None, include_top=True)
if config.regularizer.name == "l2":
l2_reg = config.regularizer.weight
for layer in model.layers:
if isinstance(layer, tf.keras.layers.DepthwiseConv2D):
layer.add_loss(lambda la=layer: tf.keras.regularizers.l2(l2_reg)(la.depthwise_kernel))
elif isinstance(layer, tf.keras.layers.Conv2D) or isinstance(layer, tf.keras.layers.Dense):
layer.add_loss(lambda la=layer: tf.keras.regularizers.l2(l2_reg)(la.kernel))
潇湘沐
相关分类