2017-08-28 66 views

回答

0

這可能不是最好的解決方案,但我認爲這可以解決您的問題。

import pickle 

#set a name for all fully connected layers. 
model.add(Dense(...,name='fc1')) 
model.add(Dense(...,name='fc2')) 
model.add(Dense(...,name='fc3')) 


layers_to_save = ['fc1','fc2','fc3'] # add here any layer you want to save 

# Save weights to a dictionary 
weights_dict = dict([(layer.name, layer.get_weights()) for layer in model.layers if layer.name in layers_to_save]) 

with open('filename.pickle', 'wb') as handle: 
    pickle.dump(weights_dict, handle, protocol=pickle.HIGHEST_PROTOCOL) 




# Load weights 
with open('filename.pickle', 'rb') as handle: 
    weights_dict = pickle.load(handle) 

for name in layers_to_save: 
    model.get_layer(name).set_weights(weights_dict[name]) 

您還可以檢查此keras blog post下半年的另一種方法。

+0

謝謝。我看到負載頂部模型,但我沒有看到如何保存頂部模型。這是我的問題。如果使用'from keras.callbacks import ModelCheckpoint ckp_callback = ModelCheckpoint(model_file,monitor =「val_loss」,save_best_only = True,save_weights_only = True,mode ='min')',所有權重包括vgg都會被保存,對嗎?如何保存頂級模型? – user6101147

+0

對不起,我編輯過我的帖子。在那篇博文中,首先,您需要保存瓶頸功能(最後一個卷積層的輸出),然後用它們訓練一個FC模型。在某些情況下,這可能是個好主意。 – Matin