Keras 如何利用訓練好的神經網絡進行預測


分成兩種情況,一種是公開的訓練好的模型,下載后可以使用的,一類是自己訓練的模型,需要保存下來,以備今后使用。

如果是第一種情況,則參考    http://keras-cn.readthedocs.io/en/latest/other/application/

使用的是Application應用,文檔中的例子如下

利用ResNet50網絡進行ImageNet分類

from keras.applications.resnet50 import ResNet50 from keras.preprocessing import image from keras.applications.resnet50 import preprocess_input, decode_predictions import numpy as np model = ResNet50(weights='imagenet') #僅僅這樣就可以 img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode the results into a list of tuples (class, description, probability) # (one such list for each sample in the batch) print('Predicted:', decode_predictions(preds, top=3)[0]) # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458

 

 

如果是自己的模型想保存下來,參考http://keras-cn.readthedocs.io/en/latest/for_beginners/FAQ/#keras_1

又有兩種方式,一種是:

你可以使用model.save(filepath)將Keras模型和權重保存在一個HDF5文件中,該文件將包含:

  • 模型的結構,以便重構該模型
  • 模型的權重
  • 訓練配置(損失函數,優化器等)
  • 優化器的狀態,以便於從上次訓練中斷的地方開始

使用keras.models.load_model(filepath)來重新實例化你的模型,如果文件中存儲了訓練配置的話,該函數還會同時完成模型的編譯

另外一種方式,可以分開保存模型結構和模型參數:

如果你只是希望保存模型的結構,而不包含其權重或配置信息,可以使用:

# save as JSON json_string = model.to_json() # save as YAML yaml_string = model.to_yaml() 

這項操作將把模型序列化為json或yaml文件,這些文件對人而言也是友好的,如果需要的話你甚至可以手動打開這些文件並進行編輯。

當然,你也可以從保存好的json文件或yaml文件中載入模型:

# model reconstruction from JSON: from keras.models import model_from_json model = model_from_json(json_string) # model reconstruction from YAML model = model_from_yaml(yaml_string) 

如果需要保存模型的權重,可通過下面的代碼利用HDF5進行保存。注意,在使用前需要確保你已安裝了HDF5和其Python庫h5py

model.save_weights('my_model_weights.h5') 

如果你需要在代碼中初始化一個完全相同的模型,請使用:

model.load_weights('my_model_weights.h5') 

如果你需要加載權重到不同的網絡結構(有些層一樣)中,例如fine-tune或transfer-learning,你可以通過層名字來加載模型:

model.load_weights('my_model_weights.h5', by_name=True)


例子:
  1. json_string = model.to_json()  
  2. open('my_model_architecture.json','w').write(json_string)  
  3. model.save_weights('my_model_weights.h5')  
  4.    
  5. model = model_from_json(open('my_model_architecture.json').read())  
  6. model.load_weights('my_model_weights.h5')  




http://blog.csdn.net/johinieli/article/details/69367176
http://blog.csdn.net/johinieli/article/details/69367434


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM