keras中最經常使用深度學習的API

 

衆所周知,利用Keras-Python庫能夠快速、輕鬆地建立屬於本身的深度學習的模型,今天咱們就來介紹一些咱們經常使用的API函數。數組

序貫模型(Sequential)API容許你爲大多數問題逐層的建立模型。它的侷限性在於它不容許你建立共享層或者是具備多個輸入或輸出的模型。網絡

Keras中的API函數是建立更多靈活性模型的替代方法,其中也包括建立更復雜的模型。app

在本篇博客中,你將發現如何在Keras中使用靈活的API函數來定義深度學習模型。函數

閱讀完成後,你將知道:學習

1.連續的API和API函數之間的區別。3d

2.如何使用API函數定義簡單的多層感知器,卷積神經網絡和循環神經網絡模型。code

3.如何使用共享層和多個輸入和輸出定義更復雜的模型。blog

OK,讓咱們開始吧。教程

教程概述ip

本教程分爲6部分:

1.Keras序貫模型。

2.Keras功能函數模型。

3.標準網絡模型。

4.共享層模型。

5.多個輸入和輸出模型。

6.最佳練習。

1.Keras序貫模型

Keras提供了一個Sequential模型的API。

這是建立深度學習模型的一種方法,其中建立了Sequential類的實例,並建立了模型圖層並將其添加其中。

例如,能夠將層定義並傳遞給Sequential做爲數組:

 

from keras.models import Sequential
from keras.layers import Dense
model = Sequential([Dense(2, input_dim=1), Dense(1)])

 

層也能夠分段添加:

 

from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(2, input_dim=1))
model.add(Dense(1))

 

序貫模型的API在大多數狀況下很是適合開發深度學習模型,但也有一些限制。例如,它不能定義具備多個不一樣輸入源的模型,由於那樣會產生多個輸出目標。

2.Keras功能函數模型

Keras功能API爲定義模型提供了更靈活的方式。

它容許你定義多個輸入或輸出的模型以及能夠共享圖層的模型。除此以外,它還容許你定義臨時的非循環網絡圖。

模型經過建立層的實例並將它們直接彼此成對鏈接來定義,而後定義一個模型,該模型的指定層做爲模型的輸入和輸出。

咱們來看看Keras功能API的三個獨特方面:

2.1定義輸入

與Sequential模型不一樣,你必須建立並定義一個獨立的輸入層,該層指定輸入數據的形狀。

輸入層採用一個模型參數,它是一個表明輸入數據維度的元組。

當輸入數據爲一維時,例如對於多層感知器,該模型必須明確留出在訓練網絡分割數據時所使用的小批量大小的形狀。所以,模型元組始終以掛起的最後一維(2)定義,例如:

from keras.layers import Input

visible = Input(shape=(2,))

2.2鏈接層

模型中的層能夠成對鏈接,這是經過在定義每一個新圖層時指定輸入來自哪裏。使用括號符號,使得在建立圖層以後,指定從當前圖層的輸入到即將到達的圖層。

讓咱們用一個簡單的例子來講明這一點。咱們能夠建立如上所述的輸入層,而後建立一個隱藏層,做爲僅從輸入層接收輸入的密集層。

 

from keras.layers import Input
from keras.layers import Dense
visible = Input(shape=(2,))
hidden = Dense(2)(visible)

 

正是經過這種鏈接層的方法,使功能API更具備靈活性。你能夠看到開始定義ad-hoc圖層的特殊圖形變得多麼的容易。

2.3建立模型

建立模型所需的全部圖層並將其鏈接在一塊兒後,接下來必須定義模型。與Sequential API同樣,該模型是你能夠概述、擬合、評估和使用作出預測。

Keras提供了一個Model類,你可使用它從建立的圖層時建立模型。它要求你須要指定輸入和輸出層。例如:

 

from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
visible = Input(shape=(2,))
hidden = Dense(2)(visible)
model = Model(inputs=visible, outputs=hidden)

 

既然如今咱們知道了Keras功能API的全部關鍵部分,咱們經過定義一套不一樣的模型實踐一下咱們的學習成果。

如下每一個示例都是可執行的,並打印結構並建立圖表。我建議爲你本身的模型作這個,這樣可讓你清楚你的定義。

我但願這些示例能夠爲你在之後使用功能API定義本身的模型時提供了模板。

3.標準網絡模型

當開始使用功能API時,最好先了解一些關於標準神經網絡模型的定義。在本節中,咱們將介紹定義一個簡單的多層感知器,卷積神經網絡和循環神經網絡。

這些例子將爲之後理解更詳細的例子奠基基礎。

3.1多層感知器

在本節中,咱們爲二進制分類定義了一個多層Perceptron模型。該模型有10個輸入,3個隱藏層,10個神經元,輸出層有1個輸出。在每一個隱藏層中使用整流線性激活函數,在輸出層使用S形激活函數進行二進制分類。

 

# Multilayer Perceptron
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
visible = Input(shape=(10,))
hidden1 = Dense(10, activation='relu')(visible)
hidden2 = Dense(20, activation='relu')(hidden1)
hidden3 = Dense(10, activation='relu')(hidden2)
output = Dense(1, activation='sigmoid')(hidden3)
model = Model(inputs=visible, outputs=output)
# summarize layers
print(model.summary())
# plot graph
plot_model(model, to_file='multilayer_perceptron_graph.png')

 

運行示例打印網絡的結構:

 

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 10)                0
_________________________________________________________________
dense_1 (Dense)              (None, 10)                110
_________________________________________________________________
dense_2 (Dense)              (None, 20)                220
_________________________________________________________________
dense_3 (Dense)              (None, 10)                210
_________________________________________________________________
dense_4 (Dense)              (None, 1)                 11
=================================================================
Total params: 551
Trainable params: 551
Non-trainable params: 0
_________________________________________________________________

 

模型圖的建立並保存到文件:

622c42ea60f572c1af51073d1c7ddb53b147be1a

3.2卷積神經網絡

在本節中,咱們將定義一個用於圖像分類的卷積神經網絡。

該模型接收黑白64×64圖像做爲輸入,而後兩個卷積層和聚集層的序列做爲特徵提取器,隨後是徹底鏈接的層來解釋特徵,而且輸出層是具備S形激活函數。

 

# Convolutional Neural Network
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
visible = Input(shape=(64,64,1))
conv1 = Conv2D(32, kernel_size=4, activation='relu')(visible)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(16, kernel_size=4, activation='relu')(pool1)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
hidden1 = Dense(10, activation='relu')(pool2)
output = Dense(1, activation='sigmoid')(hidden1)
model = Model(inputs=visible, outputs=output)
# summarize layers
print(model.summary())
# plot graph
plot_model(model, to_file='convolutional_neural_network.png')

 

運行示例:

 

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 64, 64, 1)         0
••••••
Total params: 8,933
Trainable params: 8,933
Non-trainable params: 0
________________________________________________________________

 

模型圖的圖建立並保存到文件:

31c09d23a42c2d87403048ca32046fae5b997327

3.3循環神經網絡

在本節中,咱們將定義一個LSTM循環神經網絡用於序列分類。

該模型是100個時間步長做爲輸入,該模型具備單個LSTM隱藏層,用於從序列中提取特徵,而後是徹底鏈接的層以解釋LSTM輸出,隨後是用於進行二進制預測的輸出層。

 

# Recurrent Neural Network
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers.recurrent import LSTM
visible = Input(shape=(100,1))
hidden1 = LSTM(10)(visible)
hidden2 = Dense(10, activation='relu')(hidden1)
output = Dense(1, activation='sigmoid')(hidden2)
model = Model(inputs=visible, outputs=output)
# summarize layers
print(model.summary())
# plot graph
plot_model(model, to_file='recurrent_neural_network.png')

 

運行示例總結模型層。

 

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
•••••••
=================================================================
Total params: 601
Trainable params: 601
Non-trainable params: 0
_________________________________________________________________

 

模型圖的建立並保存到文件:

f9a5c24c9e81d960df7aeecbf91215547ec9825b

4.共享層模型

多層能夠共享一層的輸出。

例如,可能存在來自輸入的多個不一樣的特徵提取層,或者用於解釋特徵提取層輸出的多個層。

咱們來看看這兩個例子。

4.1共享輸入層

在本節中,咱們使用不一樣大小的內核定義多個卷積層來解釋圖像輸入。

該模型輸入採用大小爲64×64像素的黑白圖像。有兩個CNN特徵提取子模型共享該輸入:第一個內核大小爲4,第二個內核大小爲8。這些特徵提取子模型的輸出被平坦化爲向量,並鏈接成一個長向量,並傳遞到徹底鏈接的層,以便在最終輸出層以前進行二進制分類。

 

# Shared Input Layer
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.layers.merge import concatenate
# input layer
visible = Input(shape=(64,64,1))
# first feature extractor
conv1 = Conv2D(32, kernel_size=4, activation='relu')(visible)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
flat1 = Flatten()(pool1)
# second feature extractor
conv2 = Conv2D(16, kernel_size=8, activation='relu')(visible)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
flat2 = Flatten()(pool2)
# merge feature extractors
merge = concatenate([flat1, flat2])
# interpretation layer
hidden1 = Dense(10, activation='relu')(merge)
# prediction output
output = Dense(1, activation='sigmoid')(hidden1)
model = Model(inputs=visible, outputs=output)
# summarize layers
print(model.summary())
# plot graph
plot_model(model, to_file='shared_input_layer.png')

運行示例總結模型層。

___________________________________________________________________
Layer (type)           Output Shape        Param #     Connected to
===================================================================
•••••••••••••••••••••••
Total params: 415,045
Trainable params: 415,045
Non-trainable params: 0
___________________________________________________________________

模型圖的被建立並保存到文件:

61f610709ce56e472a1dcdfa92b8dd5da0ab2392

4.2共享特徵提取層

在本節中,咱們使用兩個並行子模型解釋LSTM特徵提取器的輸出以進行序列分類。

模型的輸入是一個特徵爲100的時間步長,具備10個存儲單元的LSTM層解釋該序列。第一種解釋模式是淺層的單層徹底鏈接層,第二種是深層的3層模型。兩個解釋模型的輸出都被鏈接成一個長向量,傳遞給用於進行二進制預測的輸出層。

# Shared Feature Extraction Layer
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers.recurrent import LSTM
from keras.layers.merge import concatenate
# define input
visible = Input(shape=(100,1))
# feature extraction
extract1 = LSTM(10)(visible)
# first interpretation model
interp1 = Dense(10, activation='relu')(extract1)
# second interpretation model
interp11 = Dense(10, activation='relu')(extract1)
interp12 = Dense(20, activation='relu')(interp11)
interp13 = Dense(10, activation='relu')(interp12)
# merge interpretation
merge = concatenate([interp1, interp13])
# output
output = Dense(1, activation='sigmoid')(merge)
model = Model(inputs=visible, outputs=output)
# summarize layers
print(model.summary())
# plot graph
plot_model(model, to_file='shared_feature_extractor.png')

運行示例總結模型層。

___________________________________________________________________
Layer (type)    Output Shape          Param #     Connected to
•••••••
Total params: 1,151
Trainable params: 1,151
Non-trainable params: 0
___________________________________________________________________

模型圖被建立並保存到文件。

fc78183eba1bcab08fd3f359948f49fca84ffebd

5.多個輸入和輸出模型

功能API也可用於開發具備多個輸入的更復雜的模型,可能具備不一樣的模態。它也能夠用於開發產生多個輸出的模型。

咱們將在本節中查看每一個示例。

5.1多輸入模型

咱們將開發一個圖像分類模型,它將兩個版本的圖像做爲輸入,每一個版本的大小不一樣。具體是黑白64×64版,彩色32×32版。單獨的特徵提取CNN模型在每一個模型上運行,而後將兩個模型的結果鏈接起來進行解釋和最終預測。

請注意,在建立Model()實例時,咱們將兩個輸入圖層定義爲數組。

model = Model(inputs=[visible1, visible2], outputs=output)

完整的示例以下所示。

# Multiple Inputs
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.layers.merge import concatenate
# first input model
visible1 = Input(shape=(64,64,1))
conv11 = Conv2D(32, kernel_size=4, activation='relu')(visible1)
pool11 = MaxPooling2D(pool_size=(2, 2))(conv11)
conv12 = Conv2D(16, kernel_size=4, activation='relu')(pool11)
pool12 = MaxPooling2D(pool_size=(2, 2))(conv12)
flat1 = Flatten()(pool12)
# second input model
visible2 = Input(shape=(32,32,3))
conv21 = Conv2D(32, kernel_size=4, activation='relu')(visible2)
pool21 = MaxPooling2D(pool_size=(2, 2))(conv21)
conv22 = Conv2D(16, kernel_size=4, activation='relu')(pool21)
pool22 = MaxPooling2D(pool_size=(2, 2))(conv22)
flat2 = Flatten()(pool22)
# merge input models
merge = concatenate([flat1, flat2])
# interpretation model
hidden1 = Dense(10, activation='relu')(merge)
hidden2 = Dense(10, activation='relu')(hidden1)
output = Dense(1, activation='sigmoid')(hidden2)
model = Model(inputs=[visible1, visible2], outputs=output)
# summarize layers
print(model.summary())
# plot graph
plot_model(model, to_file='multiple_inputs.png')

運行示例:

___________________________________________________________________
Layer (type)              Output Shape      Param #     Connected to
•••••••••
input_1 (InputLayer)             (None, 64, 64, 1)     0
Total params: 49,699
Trainable params: 49,699
Non-trainable params: 0
___________________________________________________________________

模型圖被建立並保存到文件。

cf16760c835faad81dd5e9d7feabb419ca02f7da

5.2多輸出模型

在本節中,咱們將開發出一種能夠進行兩種不一樣類型預測的模型。給定一個特徵的100個時間步長的輸入序列,該模型將對序列進行分類並輸出具備相同長度的新序列。

LSTM層解釋輸入序列,並返回每一個時間步長的隱藏狀態。第一個輸出模型建立一個堆棧的LSTM,解釋特徵,並進行二進制預測。第二個輸出模型使用相同的輸出層對每一個輸入時間步長進行實值預測。

 

# Multiple Outputs
from keras.utils import plot_model
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import TimeDistributed
# input layer
visible = Input(shape=(100,1))
# feature extraction
extract = LSTM(10, return_sequences=True)(visible)
# classification output
class11 = LSTM(10)(extract)
class12 = Dense(10, activation='relu')(class11)
output1 = Dense(1, activation='sigmoid')(class12)
# sequence output
output2 = TimeDistributed(Dense(1, activation='linear'))(extract)
# output
model = Model(inputs=visible, outputs=[output1, output2])
# summarize layers
print(model.summary())
# plot graph
plot_model(model, to_file='multiple_outputs.png')

運行示例。

 

___________________________________________________________________
Layer (type)           Output Shape          Param #     Connected to
===================================================================
input_1 (InputLayer)     (None, 100, 1)        0
___________________________________________________________________
········
Total params: 1,452
Trainable params: 1,452
Non-trainable params: 0
___________________________________________________________________

 

模型圖的建立並保存到文件:

3f793b6b74b7a2b7aa1de89f1eb238ce388e5e57

6.最佳作法

在本節中,我給你一些提示,以便在定義本身的模型時充分利用功能性API。

1.一致的變量名。對輸入(可見)和輸出層(輸出)使用相同的變量名稱,甚至可使用隱藏層(hidden1,hidden2)。它將有助於正確地將事物聯繫起來。

2.查看圖層圖。始終打印模型摘要並查看圖層輸出,以確保模型按預期鏈接在一塊兒。

3.查看圖表。建立一個模型圖的情節,並檢查它,以確保全部的東西都按照你的意圖放在一塊兒。

4.命名圖層。你能夠爲查看模型圖的名稱和繪圖時使用的圖層分配名稱。例如:Dense(1,name ='hidden1')。

5.單獨的子模型。考慮分開子模型的發展,並將子模型結合在一塊兒。

原文鏈接http://click.aliyun.com/m/33665/

相關文章
相關標籤/搜索