1. 程式人生 > >基於Theano的深度學習(Deep Learning)框架Keras學習隨筆-01-FAQ

基於Theano的深度學習(Deep Learning)框架Keras學習隨筆-01-FAQ

本文主要介紹一下Keras的問答部分,其實很簡單,後邊可能不會詳細說到,提前涼一下,便於翻看。

Keras介紹:

Keras是一個極度簡化、高度模組化的神經網路第三方庫。基於Python+Theano開發,充分發揮了GPU和CPU操作。其開發目的是為了更快的做神經網路實驗。適合前期的網路原型設計、支援卷積網路和反覆性網路以及兩者的結果、支援人工設計的其他網路、在GPU和CPU上執行能夠無縫連線。

No.0 windows使用者如何安裝Keras框架?

        用pip方式安裝很簡單。即開啟cmd,輸入pip install keras,然後等待安裝完畢即可。會自動安裝需要的元件。如果pip命令失敗,則建議按照

win7安裝Theano詳細教程去安裝Python+Theano。然後再安裝Keras即可。其他安裝方式見這裡

No.1怎麼儲存Keras模型?

不推薦使用pickle或cPickle。

(1) 如果只儲存模型結構,程式碼如下:

# save as JSON
json_string = model.to_json()
# save as YAML
yaml_string = model.to_yaml()
# model reconstruction from JSON:
from keras.modelsimport model_from_json
model = model_from_json(json_string)
 
# model reconstruction from YAML
model =model_from_yaml(yaml_string)

(2) 如果需要儲存資料:

model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5')

(3) 綜合運用:

json_string = model.to_json()
open('my_model_architecture.json','w').write(json_string)
model.save_weights('my_model_weights.h5')
 
model = model_from_json(open('my_model_architecture.json').read())
model.load_weights('my_model_weights.h5')

No.2為什麼訓練損失比測試損失要大?

Keras有兩種模型:訓練和測試。規則化,比如Dropout和L1/L2,在測試時關閉了。

另外,訓練損失是每一次訓練batch的平均損失。模型因為在時刻變化,最開始的batch損失肯定要比最後的batches損失要高。另一方面,每一次epoch損失使用最後的epoch計算,因此返回的結果就比較小。

No.3如何將中間層的輸出視覺化?

通過Theano function的output。示例如下:

# with a Sequential model
get_3rd_layer_output =theano.function([model.layers[0].input],
 model.layers[3].get_output(train=False))
layer_output =get_3rd_layer_output(X)
 
# with a Graph model
get_conv_layer_output =theano.function([model.inputs[i].inputfor iin model.input_order],model.outputs['conv'].get_output(train=False), on_unused_input='ignore')
conv_output = get_conv_output(input_data_dict)

No.4如何用Keras處理不適合存放在記憶體中的資料集?

Batch trainingusingmodel.train_on_batch(X, y)model.test_on_batch(X, y)參考文件:modelsdocumentation

You can also see batch training in action inour CIFAR10example.

No.5當驗證損失不再繼續降低時,如何中斷訓練?

用EarlyStopping回撥函式,程式碼如下:

from keras.callbacksimport EarlyStopping
early_stopping =EarlyStopping(monitor='val_loss', patience=2)
model.fit(X, y, validation_split=0.2, callbacks=[early_stopping])

No.6在訓練時,資料會被隨機打亂嗎?

如果model.fit中的引數suffle=True時,會隨機打算每一次epoch的資料。(預設打亂)

但是驗證資料預設不會打亂。

No.7如何記錄每一次epoch訓練/驗證損失/準確度?

Model.fit函式會返回一個 History 回撥,該回調有一個屬性history包含一個封裝有連續損失/準確的lists。程式碼如下:

hist = model.fit(X, y,validation_split=0.2)
print(hist.history)

No.8如何讓我的Keras指令碼每次產生確定的資料?

在引入Kerans之前,引入numpy,並且用其random.seed(種子)產生一個隨機數物件。這樣在相同硬體的機器上執行時,每次產生的隨機數的順序都是一樣的。

import numpyas np
np.random.seed(1234)
 
# Keras imports start here
from kerasimport ...