问题描述
我用Keras构建了一个神经网络,可以训练,也可以用model.save("model.h5")保存模型,但是当我用model = load_model('model.h5')载入模型时就有如下报错:
Traceback (most recent call last):
File "C:/programming/pycharm/cnn_attention_lstm/cnn_attention_lstm/train7.py", line 31, in
main()
File "C:/programming/pycharm/cnn_attention_lstm/cnn_attention_lstm/train7.py", line 23, in main
history = classifier.fit(data_dir_path=input_dir_path, model_dir_path=output_dir_path, data_set_name=data_set_name)
File "C:\programming\pycharm\cnn_attention_lstm\cnn_attention_lstm\model7again.py", line 113, in fit
model = self.create_model()
File "C:\programming\pycharm\cnn_attention_lstm\cnn_attention_lstm\model7again.py", line 66, in create_model
model = load_model('model.h5')
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 263, in load_model
load_weights_from_hdf5_group(f['model_weights'], model.layers)
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 915, in load_weights_from_hdf5_group
reshape=reshape)
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 554, in preprocess_weights_for_loading
weights = convert_nested_time_distributed(weights)
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 513, in convert_nested_time_distributed
layer.layer, weights, original_keras_version, original_backend)
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 556, in preprocess_weights_for_loading
weights = convert_nested_model(weights)
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 532, in convert_nested_model
original_backend=original_backend))
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 556, in preprocess_weights_for_loading
weights = convert_nested_model(weights)
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 544, in convert_nested_model
original_backend=original_backend))
File "C:\Users\tong\AppData\Local\Programs\Python\Python36\Lib\site-packages\keras\engine\saving.py", line 673, in preprocess_weights_for_loading
elif layer_weights_shape != weights[0].shape:
IndexError: list index out of range
Process finished with exit code 1
最近我也遇到了这个问题,并且已经解决,不知道您是不是遇到同样的问题。
可以注意看一下keras的文档 多GPU模型最后一句
keras文档—_multi-gpu_model
On model saving
To save the multi-gpu model, use .save(fname) or .save_weights(fname) with the template model (the argument you passed to multi_gpu_model), rather than the model returned by multi_gpu_model.
我估计你保存的是并行处理后的gpu模型,所以在Load这个model的时候会出问题。应该保存送入函数前的model
举个例子:
parralel_model = multi_gpu_model(model, multi_gpu)
您应该save的是model 而不是parralel_model,此外保存前这两个模型都需要编译一下,否则Load还会出错