【问题标题】:Keras model load_weights for Neural Net神经网络的 Keras 模型 load_weights
【发布时间】:2017-01-25 19:26:45
【问题描述】:

我正在使用 Keras 库在 python 中创建神经网络。我已经加载了训练数据(txt 文件),启动了网络并“拟合”了神经网络的权重。然后我编写了代码来生成输出文本。代码如下:

#!/usr/bin/env python

# load the network weights
filename = "weights-improvement-19-2.0810.hdf5"
model.load_weights(filename)
model.compile(loss='categorical_crossentropy', optimizer='adam')

我的问题是:执行时会产生以下错误:

 model.load_weights(filename)
 NameError: name 'model' is not defined

我添加了以下内容,但错误仍然存​​在:

from keras.models import Sequential
from keras.models import load_model

任何帮助将不胜感激。

【问题讨论】:

    标签: python neural-network keras


    【解决方案1】:

    您需要首先创建名为model 的网络对象,并在调用model.load_weights(fname) 之后对其进行编译

    工作示例:

    from keras.models import Sequential
    from keras.layers import Dense, Activation
    
    
    def build_model():
        model = Sequential()
    
        model.add(Dense(output_dim=64, input_dim=100))
        model.add(Activation("relu"))
        model.add(Dense(output_dim=10))
        model.add(Activation("softmax"))
    
        # you can either compile or not the model
        model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
        return model
    
    
    model1 = build_model()
    model1.save_weights('my_weights.model')
    
    
    model2 = build_model()
    model2.load_weights('my_weights.model')
    
    # do stuff with model2 (e.g. predict())
    

    保存并加载整个模型

    在 Keras 中,我们可以像这样保存和加载整个模型(更多信息 here):

    from keras.models import load_model
    
    model1 = build_model()
    model1.save('my_model.hdf5')
    
    model2 = load_model('my_model.hdf5')
    # do stuff with model2 (e.g. predict()
    

    【讨论】:

    • 非常感谢您,这非常有效。但是我不得不从 keras.layers import Dense, Activation 更改为:from keras.layers.core import Dense。
    • 根据 keras docs keras,无需编译模型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    相关资源
    最近更新 更多