如何加载在Google Colab上训练的模型

时间:2020-09-14 13:13:50

标签: tensorflow keras google-colaboratory

在训练了我使用{@ 3}保存的模型后,按照tutorial尝试使用Google的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'))

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

1 个答案:

答案 0 :(得分:0)

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