gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:38:02 27 4
gpt4 key购买 nike

如何在 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

最佳答案

如果你在 HDF5 文件中存储了完整的模型,而不仅仅是权重,那么它就像

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

关于python - 如何在 Keras 中从 HDF5 文件加载模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com