最近在學習keras,它有一些實現好的特征提取的模型:resNet、vgg。而且是帶權重的。用來做特診提取比較方便
首先要知道keras有兩種定義模型的方式:
1、 序列模型 The Sequential model
2、 函數式模型 the Keras functional
主要關注函數式模型:
函數式模型用來構造比較復雜的模型 ,比如說有多個輸出的模型,有向非循環圖,或者有共享層的模型
入門例子:密集連接的網絡。可能這樣的網絡用Sequential模型實現起來更好,但是為了入門,就先做這樣的一個簡單的網絡。
1、 每個layer實例都是可以調用的,它返回一個tensor
2、 輸入tensor和輸出tensor可以用來定義一個Model
3、 函數式的模型也可以像 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)