簡體   English   中英

神經網絡的Keras模型load_weights

[英]Keras model load_weights for Neural Net

我正在使用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

任何幫助,將不勝感激。

你需要先創建一個名為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,我們可以像這樣保存和加載整個模型(更多信息在這里 ):

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM