1 入門html
2 多個輸入和輸出api
3 共享層網絡
最近在學習keras,它有一些實現好的特徵提取的模型:resNet、vgg。並且是帶權重的。用來作特診提取比較方便app
首先要知道keras有兩種定義模型的方式:ide
一、 序列模型 The Sequential model函數
二、 函數式模型 the Keras functional 學習
主要關注函數式模型:ui
函數式模型用來構造比較複雜的模型 ,好比說有多個輸出的模型,有向非循環圖,或者有共享層的模型spa
入門例子:密集鏈接的網絡。可能這樣的網絡用Sequential模型實現起來更好,可是爲了入門,就先作這樣的一個簡單的網絡。code
一、 每一個layer實例都是能夠調用的,它返回一個tensor
二、 輸入tensor和輸出tensor能夠用來定義一個Model
三、 函數式的模型也能夠像 Sequential模型同樣訓練。
from keras.layers import Input, Dense from keras.models import Model # This returns a tensor inputs = Input(shape=(784,)) # a layer instance is callable on a tensor, and returns a tensor x = Dense(64, activation='relu')(inputs) x = Dense(64, activation='relu')(x) predictions = Dense(10, activation='softmax')(x) # This creates a model that includes # the Input layer and three Dense layers model = Model(inputs=inputs, outputs=predictions) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels) # starts training
生成的模型與layer同樣,也是能夠被調用的。
在函數式模型中,對一個模型的重用(reuse)是很簡單的。只要把這個模型當成一個layer,而後在tensor上調用它便可。
要注意的是:這樣調用的modle,不單單是它的結構被調用了,它權重也在被重用。
x = Input(shape=(784,)) # This works, and returns the 10-way softmax we defined above. y = model(x)
這樣的話,咱們就能夠快速的建立可以處理序列化的輸入的模型。好比說,咱們把一個圖片分類模型,應用到一個視頻分類模型中,只須要一行代碼便可
from keras.layers import TimeDistributed # Input tensor for sequences of 20 timesteps, # each containing a 784-dimensional vector input_sequences = Input(shape=(20, 784)) # This applies our previous model to every timestep in the input sequences. # the output of the previous model was a 10-way softmax, # so the output of the layer below will be a sequence of 20 vectors of size 10. processed_sequences = TimeDistributed(model)(input_sequences)