【问题标题】:Is there a way to save a Keras model build in tensorflow 2.0 from Model Sub classing API?有没有办法从模型子类 API 中保存在 tensorflow 2.0 中构建的 Keras 模型?
【发布时间】:2020-03-21 10:19:42
【问题描述】:

有没有办法在训练完成后使用 tf.keras 模型子类化 API 保存整个模型构建?我知道我们可以使用 save_weights 只保存权重,但是有没有办法保存整个模型,以便我以后没有可用代码时可以使用它进行预测?

class MyModel(tf.keras.Model):

def __init__(self, num_classes=10):
    super(MyModel, self).__init__(name='my_model')
    self.num_classes = num_classes
    # Define your layers here.
    self.dense_1 = layers.Dense(32, activation='relu')
    self.dense_2 = layers.Dense(num_classes, activation='sigmoid')

def call(self, inputs):
    # Define your forward pass here,
    # using layers you previously defined (in `__init__`).
    x = self.dense_1(inputs)
    return self.dense_2(x)

model = MyModel(num_classes=10)

# The compile step specifies the training configuration.
model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001),
          loss='categorical_crossentropy',
          metrics=['accuracy'])


model.fit(data, labels, batch_size=32, epochs=5)

【问题讨论】:

    标签: python-3.x tensorflow deep-learning tensorflow2.0 tf.keras


    【解决方案1】:

    您可以使用以下步骤在训练、加载和推理后保存模型:

    训练后保存模型

    model.save(filepath="model")
    # OR
    tf.keras.models.save_model(model, filepath="model_")
    

    加载保存的模型

    loaded_model = tf.keras.models.load_model(filepath="model_")
    

    使用加载模型进行预测

    result = loaded_model.predict(test_db)
    

    【讨论】:

    • 这是否也适用于使用模型子类化 API 创建的模型?和上面问题中的例子一样吗?
    • 是的。我已经尝试过您给定的代码。你为什么不去看看?
    • 会做的。谢谢
    • 成功了...非常感谢...由于某种原因,tensorflow 网站 (tensorflow.org/guide/keras/save_and_serialize) 上的文档说您无法保存独立模型以用于子类化 API
    猜你喜欢
    • 2019-08-30
    • 2020-05-27
    • 1970-01-01
    • 2020-06-28
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多