【问题标题】:How to load a model trained on google colab如何加载在 google colab 上训练的模型
【发布时间】:2020-09-14 13:13:50
【问题描述】:

在训练我保存的模型后,我正在关注tutorial 尝试使用谷歌的 BERT 进行文本分类

# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")

我下载了模型并尝试如下加载它们

json_file = open(os.path.join(self.root, 'model.json'), 'r')
        loaded_model_json = json_file.read()
        json_file.close()

        cs = get_custom_objects()
        cs['GlorotNormal'] = tf.keras.initializers.glorot_normal()
        cs['GlorotUniform'] = tf.keras.initializers.glorot_uniform()

        model = model_from_json(loaded_model_json, custom_objects=cs)
        print('loaded model json')
        # load weights into new model
        model.load_weights(os.path.join(self.root, 'model.h5'))

如果我从模型中删除“衣衫褴褛”,则函数 mdoel_from_json 挂起 和tf.keras.models.model_from_json 抛出ValueError: Unknown initializer: GlorotNormal 加载模型的正确方法是什么?

【问题讨论】:

  • 为什么不只使用model.save("model.h5") 而使用keras.models.load_model
  • 我记得我很久以前尝试过,但遇到了不同的问题,建议分别保存模型和权重

标签: tensorflow keras google-colaboratory


【解决方案1】:

我必须在导入 tensorflow 之前添加 os.environ['TF_KERAS'] = '1'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2019-08-11
    • 2021-12-05
    • 2020-03-31
    • 2020-12-15
    相关资源
    最近更新 更多