如何在Keras中从HDF5文件加载模型?


94

如何在Keras中从HDF5文件加载模型?

我试过的

model = Sequential()

model.add(Dense(64, input_dim=14, init='uniform'))
model.add(LeakyReLU(alpha=0.3))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Dropout(0.5))

model.add(Dense(64, init='uniform'))
model.add(LeakyReLU(alpha=0.3))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Dropout(0.5))

model.add(Dense(2, init='uniform'))
model.add(Activation('softmax'))


sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)

checkpointer = ModelCheckpoint(filepath="/weights.hdf5", verbose=1, save_best_only=True)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose = 2, callbacks=[checkpointer])

上面的代码成功将最佳模​​型保存到名为weights.hdf5的文件中。然后,我要加载该模型。以下代码显示了我如何尝试这样做:

model2 = Sequential()
model2.load_weights("/Users/Desktop/SquareSpace/weights.hdf5")

这是我得到的错误:

IndexError                                Traceback (most recent call last)
<ipython-input-101-ec968f9e95c5> in <module>()
      1 model2 = Sequential()
----> 2 model2.load_weights("/Users/Desktop/SquareSpace/weights.hdf5")

/Applications/anaconda/lib/python2.7/site-packages/keras/models.pyc in load_weights(self, filepath)
    582             g = f['layer_{}'.format(k)]
    583             weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
--> 584             self.layers[k].set_weights(weights)
    585         f.close()
    586 

IndexError: list index out of range

Answers:


84

load_weights仅设置网络的权重。您仍然需要在调用之前定义其体系结构load_weights

def create_model():
   model = Sequential()
   model.add(Dense(64, input_dim=14, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5)) 
   model.add(Dense(64, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(2, init='uniform'))
   model.add(Activation('softmax'))
   return model

def train():
   model = create_model()
   sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
   model.compile(loss='binary_crossentropy', optimizer=sgd)

   checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
   model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])

def load_trained_model(weights_path):
   model = create_model()
   model.load_weights(weights_path)

37
如果您想加载完整模型,而不仅仅是权重:from keras.models import load_model那么model = load_model('model.h5')
cgnorthcutt

1
@mikael,您能给我这篇技巧贴士吗?stackoverflow.com/questions/55050339/…–
HenryHub,

207

如果您将完整的模型(不仅是权重)存储在HDF5文件中,那么它就很简单

from keras.models import load_model
model = load_model('model.h5')

在计算模型的内存占用量时,模型还包括实际的训练数据吗?如何加载大于可用内存的模型?
user798719

模型不(明确地)包含训练数据。您不能加载比可用内存大的模型(好吧,可以,但是这将非常困难,您需要自己检查一下……但是如果模型太大而无法加载,应该(a)获得更多记忆或(b)训练较小的模型)
马丁·托马

@MartinThoma我正在使用您建议的方法。我正在尝试从加载的模型中提取一层,并尝试通过以下方法查看其权重: encoder = autoencoder.layers[0] encoder.get_weights() 但我得到: FailedPreconditionError: Attempting to use uninitialized value lstm_1/kernel
shubhamsingh

1
我感谢您的赞美:-)指出接受的答案:我可以想象仅存储权重会更可靠。如果keras发生变化,权重仍然可以导入,而完整的东西不能导入。另一方面,可以安装旧版本,卸载砝码,然后执行与以前相同的操作。
Martin Thoma

@ pr338请考虑更新您接受的答案。
克里斯(Kris)

28

有关如何构建基本Keras神经网络模型,保存模型(JSON)和权重(HDF5)并加载它们的信息,请参见以下示例代码:

# create model
model = Sequential()
model.add(Dense(X.shape[1], input_dim=X.shape[1], activation='relu')) #Input Layer
model.add(Dense(X.shape[1], activation='relu')) #Hidden Layer
model.add(Dense(output_dim, activation='softmax')) #Output Layer

# Compile & Fit model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X,Y,nb_epoch=5,batch_size=100,verbose=1)    

# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))

# serialize weights to HDF5
model.save_weights("Data/model.h5")
print("Saved model to disk")

# load json and create model
json_file = open('Data/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("Data/model.h5")
print("Loaded model from disk")

# evaluate loaded model on test data 
# Define X_test & Y_test data first
loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
score = loaded_model.evaluate(X_test, Y_test, verbose=0)
print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

1
这对我来说是从json和h5加载模型的工作。确保如果使用@InheritedGeek的示例,请记住model.compile()。必须先调用它,然后才能调用model.evaluate。很好的例子,谢谢!
CodeGuyRoss

6

根据官方文件 https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras

你可以做 :

首先通过运行以下命令测试是否已安装h5py

import h5py

如果导入h5py时没有错误,则可以保存:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

如果您需要安装h5py http://docs.h5py.org/en/latest/build.html


3
在带有h5py 2.9.0的Keras 2.2.4中,这似乎不起作用。我收到以下错误:Anaconda3 \ envs \ synthetic \ lib \ site-packages \ keras \ utils \ io_utils.py“,第302行,在getitem中 引发ValueError(“无法以只读模式创建组。”)
csteel

0

我是这样做的

from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

没有model.save()。只有model.model.save()。加载回该模型并以原始创建的模型方式使用它会导致错误。加载的对象是<keras.engine.sequential.Sequential。而我们创建的对象是keras.wrappers.scikit_learn.KerasRegressor。我该如何更改?
沙,


我得到了这个链接404


@TRINADH NAGUBADI,请更新链接,该页面不再存在。
Catalina Chircu
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.