将模型保存在keras中是否有先决条件?

时间:2019-04-04 12:32:14

标签: keras model save

我想在训练后保存我的keras模型。 model.fit函数有效,但不幸的是model.save('path')或model.save_weights('path')命令无效。

我也尝试过用pickle或np.save保存模型,但是它也不起作用。

我的模型如下构建:

model_resnet = Model(inputs=RESNET.input, outputs=RESNET.output)

model = Sequential()
model.add(model_resnet)
model.add(BatchNormalization())
model.add(Reshape((1,256)))

model.add(Bidirectional(GRU(512,return_sequences=True)))
model.add(Bidirectional(GRU(512)))

model.add(Dense(11,activation='softmax'))

其中RESNET是使用keras功能API定义的3D resnet32模型。 可以这样写相同的代码:

model_ = Sequential()
model_.add(BatchNormalization())
model_.add(Reshape((1,256)))

model_.add(Bidirectional(GRU(512,return_sequences=True)))
model_.add(Bidirectional(GRU(512)))

model_.add(Dense(11,activation='softmax'))

model = Model(input = RESNET.input, outputs = model_(RESNET.output))

我正在尝试保存以下代码:

model.save(root_dir+'\\models\\model.h5')

我也尝试过:

x = model.get_weights()
with open(root_dir+'\\models\\model.pickle', 'wb') as f:
    pickle.dump(x, f)

这些方法都不起作用。

使用keras保存功能,我遇到以下错误:(不要在错误中注意模型名称)

  File ".../train.py", line 110, in <module>
    model_video.save(root_dir+'\\models\\model_video.h5')
  File "...\anaconda3\envs\tensorflow_env\lib\site-packages\keras\engine\network.py", line 1090, in save
    save_model(self, filepath, overwrite, include_optimizer)
  File "...\anaconda3\envs\tensorflow_env\lib\site-packages\keras\engine\saving.py", line 382, in save_model
    _serialize_model(model, f, include_optimizer)
  File "...\anaconda3\envs\tensorflow_env\lib\site-packages\keras\engine\saving.py", line 114, in _serialize_model
    layer_group[name] = val
  File "...\anaconda3\envs\tensorflow_env\lib\site-packages\keras\utils\io_utils.py", line 218, in __setitem__
    dataset = self.data.create_dataset(attr, val.shape, dtype=val.dtype)
  File "...\anaconda3\envs\tensorflow_env\lib\site-packages\h5py\_hl\group.py", line 136, in create_dataset
    dsid = dataset.make_new_dset(self, shape, dtype, data, **kwds)
  File "...\anaconda3\envs\tensorflow_env\lib\site-packages\h5py\_hl\dataset.py", line 117, in make_new_dset
    dtype = numpy.dtype(dtype)
TypeError: data type not understood

用泡菜我有以下错误:

Traceback (most recent call last):
  File ".../train.py", line 113, in <module>
    pickle.dump(x, f)
_pickle.PicklingError: Can't pickle <class 'numpy.ndarray'>: it's not the same object as numpy.ndarray

1 个答案:

答案 0 :(得分:0)

“ conda install numpy”解决了该问题。