如何正确复制tf.keras.models.Model的自定义子类模型?
自定义子类化Keras模型的复制问题
现存的复制限制
- 目前没有可以直接通用复制所有Keras模型的实现方案,内置的克隆操作仅能正常处理非
tf.keras.models.Model子类化定义的模型。 - 直接使用
copy.deepcopy()对模型实例执行复制操作时不会抛出即时报错,但后续只要尝试使用复制得到的模型实例,就会触发各类运行错误。 - 直接对继承自
tf.keras.models.Model的自定义子类模型调用tf.keras.models.clone_model,会直接抛出类型校验错误。
可复现问题的示例代码
import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) self.dropout = tf.keras.layers.Dropout(0.5) def call(self, inputs, training=False): x = self.dense1(inputs) if training: x = self.dropout(x, training=training) return self.dense2(x) if __name__ == '__main__': model1 = MyModel() model2 = tf.keras.models.clone_model(model1)
运行触发的报错堆栈
Traceback (most recent call last): File "/Users/emadboctor/Library/Application Support/JetBrains/PyCharm2020.3/scratches/scratch.py", line 600, in <module> model2 = tf.keras.models.clone_model(model1) File "/usr/local/lib/python3.8/site-packages/tensorflow/python/keras/models.py", line 430, in clone_model return _clone_functional_model( File "/usr/local/lib/python3.8/site-packages/tensorflow/python/keras/models.py", line 171, in _clone_functional_model raise ValueError('Expected `model` argument ' ValueError: Expected `model` argument to be a functional `Model` instance, but got a subclass model instead.
内容的提问来源于stack exchange,提问作者watch-this
相关产品推荐
相关产品推荐

