原文做者:aircrafthtml
原文連接:https://www.cnblogs.com/DOMLX/p/9769301.html前端
Keras是什麼?python
若是尚未配置keras能夠這個博客配置:c++
Dense
()函數--全鏈接層keras.layers.core.Dense ( units, activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None )
若不懂卷積概念可看:深度學習(二)神經網絡中的卷積和反捲積原理編程
keras.layers.Conv2D(filters, kernel_size,
strides=(1, 1),
padding='valid',
data_format=None,
dilation_rate=(1, 1),
activation=None, use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None)
2D 卷積層 (例如對圖像的空間卷積)。json
該層建立了一個卷積核, 該卷積覈對層輸入進行卷積, 以生成輸出張量。 若是 use_bias
爲 True, 則會建立一個偏置向量並將其添加到輸出中。 最後,若是 activation
不是 None
,它也會應用於輸出。後端
當使用該層做爲模型第一層時,須要提供 input_shape
參數 (整數元組,不包含樣本表示的軸),例如, input_shape=(128, 128, 3)
表示 128x128 RGB 圖像, 在 data_format="channels_last"
時。網絡
參數機器學習
dilation_rate
值 != 1 二者不兼容。"valid"
或 "same"
(大小寫敏感)。channels_last
(默認) 或 channels_first
之一,表示輸入中維度的順序。 channels_last
對應輸入尺寸爲 (batch, height, width, channels)
, channels_first
對應輸入尺寸爲 (batch, channels, height, width)
。 它默認爲從 Keras 配置文件 ~/.keras/keras.json
中 找到的 image_data_format
值。 若是你從未設置它,將使用 "channels_last"。dilation_rate
值 != 1 與 指定 stride 值 != 1 二者不兼容。a(x) = x
)。kernel
權值矩陣的初始化器 (詳見 initializers)。kernel
權值矩陣的正則化函數 (詳見 regularizer)。kernel
權值矩陣的約束函數 (詳見 constraints)。輸入尺寸ide
(samples, channels, rows, cols)
。(samples, rows, cols, channels)
。輸出尺寸
(samples, filters, new_rows, new_cols)
。(samples, new_rows, new_cols, filters)
。
別看上面的參數一堆嚇死人,其實咱們在實際運用的時候用的就只有幾個而已:
inputs = Input(shape=(n_ch,patch_height,patch_width)) conv1 = Conv2D(32, (3, 3), activation='relu', padding='same',data_format='channels_first')(inputs) #這個小括號填inputs是表明這層模型鏈接在inputs以後
固然還能夠用kears內置的序貫模型add添加構成模型圖:
model = Sequential() # Dense(64) is a fully-connected layer with 64 hidden units. # in the first layer, you must specify the expected input data shape: # here, 20-dimensional vectors. model.add(Dense(64, activation='relu', input_dim=20))
若不懂池化概念可看:深度學習(一)神經網絡中的池化與反池化原理
keras.layers.pooling.MaxPooling2D( pool_size=(2, 2), strides=None, padding='valid', data_format=None )
仍是同樣的好多東西默認就好了,下面就是一個2*2的池化層:
pool1 = MaxPooling2D((2, 2))(conv1)
model.compile
()函數--配置模型
model.compile(optimizer, loss, metrics=None, sample_weight_mode=None)
編譯用來配置模型的學習過程,其參數有
optimizer:字符串(預約義優化器名)或優化器對象,參考優化器
loss:字符串(預約義損失函數名)或目標函數,參考損失函數
metrics:列表,包含評估模型在訓練和測試時的網絡性能的指標,典型用法是metrics=['accuracy']
sample_weight_mode:若是你須要按時間步爲樣本賦權(2D權矩陣),將該值設爲「temporal」。默認爲「None」,表明按樣本賦權(1D權)。在下面fit函數的解釋中有相關的參考內容。
kwargs:使用TensorFlow做爲後端請忽略該參數,若使用Theano做爲後端,kwargs的值將會傳遞給 K.function
示例代碼:
model.compile(optimizer='sgd', loss='categorical_crossentropy',metrics=['accuracy'])
fit
()函數--模型運行函數
fit(self, x, y, batch_size=32, epochs=10, verbose=1, callbacks=None, validation_split=0.0,
validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0 )
x:輸入數據。若是模型只有一個輸入,那麼x的類型是numpy array,若是模型有多個輸入,那麼x的類型應當爲list,list的元素是對應於各個輸入的numpy array
y:標籤,numpy array
batch_size:整數,指定進行梯度降低時每一個batch包含的樣本數。訓練時一個batch的樣本會被計算一次梯度降低,使目標函數優化一步。
epochs:整數,訓練的輪數,每一個epoch會把訓練集輪一遍。
verbose:日誌顯示,0爲不在標準輸出流輸出日誌信息,1爲輸出進度條記錄,2爲每一個epoch輸出一行記錄
callbacks:list,其中的元素是keras.callbacks.Callback的對象。這個list中的回調函數將會在訓練過程當中的適當時機被調用,參考回調函數
validation_split:0~1之間的浮點數,用來指定訓練集的必定比例數據做爲驗證集。驗證集將不參與訓練,並在每一個epoch結束後測試的模型的指標,如損失函數、精確度等。注意,validation_split的劃分在shuffle以前,所以若是你的數據自己是有序的,須要先手工打亂再指定validation_split,不然可能會出現驗證集樣本不均勻。
validation_data:形式爲(X,y)的tuple,是指定的驗證集。此參數將覆蓋validation_spilt。
shuffle:布爾值或字符串,通常爲布爾值,表示是否在訓練過程當中隨機打亂輸入樣本的順序。若爲字符串「batch」,則是用來處理HDF5數據的特殊狀況,它將在batch內部將數據打亂。
class_weight:字典,將不一樣的類別映射爲不一樣的權值,該參數用來在訓練過程當中調整損失函數(只能用於訓練)
sample_weight:權值的numpy array,用於在訓練時調整損失函數(僅用於訓練)。能夠傳遞一個1D的與樣本等長的向量用於對樣本進行1對1的加權,或者在面對時序數據時,傳遞一個的形式爲(samples,sequence_length)的矩陣來爲每一個時間步上的樣本賦不一樣的權。這種狀況下請肯定在編譯模型時添加了sample_weight_mode='temporal'。
initial_epoch: 從該參數指定的epoch開始訓練,在繼續以前的訓練時有用。
參數雖多,可是不少均可以省略看代碼示例:
model.fit(patches_imgs_train, patches_masks_train, epochs=N_epochs, batch_size=batch_size, verbose=1, shuffle=True, validation_split=0.1, callbacks=[checkpointer])
kears predict()函數--測試數據
predictions = model.predict(patches_imgs_test, batch_size=32, verbose=2) print("predicted images size :") print(predictions.shape)
# 加載訓練好的模型
model.load_weights('./weights.h5')
Dropout(x)
X能夠取0--1之間,表明百分比拋棄數據
Dropout(0.5)隨機拋棄百分之五十的數據
UpSampling2D(size=(2, 2))
size(x,y)
x表明行放大倍數 這裏取2的話表明原來的一行變成了兩行 (就是一行那麼粗,變成了兩行那麼粗)
y表明列放大倍數 這裏取2的話表明原來的一列變成了兩行 (就是一列那麼粗,變成了兩列那麼粗)
size(2,2)其實就等於將原圖放大四倍(水平兩倍,垂直兩倍) 32*32 變成 62*64的圖像
inputs = Input((n_ch, patch_height, patch_width)) conv1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(inputs) conv1 = Dropout(0.2)(conv1) conv1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv1) up1 = UpSampling2D(size=(2, 2))(conv1) # conv2 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(up1) conv2 = Dropout(0.2)(conv2) conv2 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(conv2) pool1 = MaxPooling2D(pool_size=(2, 2))(conv2) # conv3 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(pool1) conv3 = Dropout(0.2)(conv3) conv3 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv3) pool2 = MaxPooling2D(pool_size=(2, 2))(conv3) # conv4 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(pool2) conv4 = Dropout(0.2)(conv4) conv4 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(conv4) pool3 = MaxPooling2D(pool_size=(2, 2))(conv4) # conv5 = Convolution2D(128, 3, 3, activation='relu', border_mode='same')(pool3) conv5 = Dropout(0.2)(conv5) conv5 = Convolution2D(128, 3, 3, activation='relu', border_mode='same')(conv5) # up2 = merge([UpSampling2D(size=(2, 2))(conv5), conv4], mode='concat', concat_axis=1) conv6 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(up2) conv6 = Dropout(0.2)(conv6) conv6 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(conv6) # up3 = merge([UpSampling2D(size=(2, 2))(conv6), conv3], mode='concat', concat_axis=1) conv7 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(up3) conv7 = Dropout(0.2)(conv7) conv7 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv7) # up4 = merge([UpSampling2D(size=(2, 2))(conv7), conv2], mode='concat', concat_axis=1) conv8 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(up4) conv8 = Dropout(0.2)(conv8) conv8 = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(conv8) # pool4 = MaxPooling2D(pool_size=(2, 2))(conv8) conv9 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(pool4) conv9 = Dropout(0.2)(conv9) conv9 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')(conv9) # conv10 = Convolution2D(2, 1, 1, activation='relu', border_mode='same')(conv9) conv10 = core.Reshape((2,patch_height*patch_width))(conv10) conv10 = core.Permute((2,1))(conv10) ############
conv10 = core.Activation('softmax')(conv10) model = Model(input=inputs, output=conv10)
將模型的輸入和輸出給model函數就會本身組建模型運行圖結構
keras.layers.embeddings.Embedding( input_dim, output_dim, embeddings_initializer='uniform',
embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None)
關於embeding做用的詳細介紹:http://spaces.ac.cn/archives/4122/
keras.layers.normalization.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True,
scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros',
moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None,
beta_constraint=None, gamma_constraint=None)
該層在每一個batch上將前一層的激活值從新規範化,即便得其輸出數據的均值接近0,其標準差接近1
data_format="channels_first
的2D卷積後,通常會設axis=1。
任意,當使用本層爲模型首層時,指定input_shape
參數時有意義。
與輸入shape相同
plot(model, to_file='./'+name_experiment+'/'+name_experiment + '_model.png')
checkpointer = ModelCheckpoint(filepath='./'+name_experiment+'/'+name_experiment +'_best_weights.h5', verbose=1, monitor='val_loss', mode='auto', save_best_only=True) model.fit(patches_imgs_train, patches_masks_train, epochs=N_epochs, batch_size=batch_size, verbose=1, shuffle=True, validation_split=0.1, callbacks=[checkpointer])
ModelCheckpoint函數能夠指定必定訓練次數後保存中間訓練的最佳參數
ModelCheckpoint函數做爲model.fit()函數中回調函數使用
Merge層提供了一系列用於融合兩個層或兩個張量的層對象和方法。以大寫首字母開頭的是Layer類,以小寫字母開頭的是張量的函數。小寫字母開頭的張量函數在內部其實是調用了大寫字母開頭的層。
keras.layers.Add()用法
keras.layers.Add()
添加輸入列表的圖層。
該層接收一個相同shape列表張量,並返回它們的和,shape不變。
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) added = keras.layers.Add()([x1, x2]) # equivalent to added = keras.layers.add([x1, x2]) out = keras.layers.Dense(4)(added) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.Subtract()用法
keras.layers.Subtract()
兩個輸入的層相減。
它將大小至少爲2,相同Shape的列表張量做爲輸入,並返回一個張量(輸入[0] - 輸入[1]),也是相同的Shape。
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) # Equivalent to subtracted = keras.layers.subtract([x1, x2]) subtracted = keras.layers.Subtract()([x1, x2]) out = keras.layers.Dense(4)(subtracted) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.Multiply()用法
keras.layers.Multiply()
該層接收一個列表的同shape張量,並返回它們的逐元素積的張量,shape不變。
keras.layers.Average()用法
keras.layers.Average()
該層接收一個列表的同shape張量,並返回它們的逐元素均值,shape不變。
keras.layers.Maximum()用法
keras.layers.Maximum()
該層接收一個列表的同shape張量,並返回它們的逐元素最大值,shape不變。
keras.layers.Concatenate(axis=-1)參數
keras.layers.Concatenate(axis=-1)
該層接收一個列表的同shape張量,並返回它們的按照給定軸相接構成的向量。
keras.layers.Dot(axes, normalize=False)參數
keras.layers.Dot(axes, normalize=False)
計算兩個tensor中樣本的張量乘積。例如,若是兩個張量a
和b
的shape都爲(batch_size, n),則輸出爲形如(batch_size,1)的張量,結果張量每一個batch的數據都是a[i,:]和b[i,:]的矩陣(向量)點積。
keras.layers.add(inputs)參數
keras.layers.add(inputs)
Add層的函數式包裝
輸入列表張量之和
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) added = keras.layers.add([x1, x2]) out = keras.layers.Dense(4)(added) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.subtract(inputs)參數
keras.layers.subtract(inputs)
Subtract層的函數式包裝
輸入張量列表的差異
import keras input1 = keras.layers.Input(shape=(16,)) x1 = keras.layers.Dense(8, activation='relu')(input1) input2 = keras.layers.Input(shape=(32,)) x2 = keras.layers.Dense(8, activation='relu')(input2) subtracted = keras.layers.subtract([x1, x2]) out = keras.layers.Dense(4)(subtracted) model = keras.models.Model(inputs=[input1, input2], outputs=out)
keras.layers.multiply(inputs)參數
keras.layers.multiply(inputs)
Multiply的函數式包裝
輸入列表張量之逐元素積
keras.layers.average(inputs)參數
keras.layers.average(inputs)
Average的函數包裝
輸入列表張量之逐元素均值
keras.layers.maximum(inputs)參數
keras.layers.maximum(inputs)
Maximum的函數包裝
輸入列表張量之逐元素均值
keras.layers.concatenate(inputs, axis=-1)參數
keras.layers.concatenate(inputs, axis=-1)
Concatenate的函數包裝
keras.layers.dot(inputs, axes, normalize=False)參數
keras.layers.dot(inputs, axes, normalize=False)
Dot的函數包裝
keras.layers.core.Activation(activation)
激活層對一個層的輸出施加激活函數
任意,當使用激活層做爲第一層時,要指定input_shape
與輸入shape相同
keras.layers.core.Dropout(rate, noise_shape=None, seed=None)
爲輸入數據施加Dropout。Dropout將在訓練過程當中每次更新參數時按必定機率(rate)隨機斷開輸入神經元,Dropout層用於防止過擬合。
rate:0~1的浮點數,控制須要斷開的神經元的比例
noise_shape:整數張量,爲將要應用在輸入上的二值Dropout mask的shape,例如你的輸入爲(batch_size, timesteps, features),而且你但願在各個時間步上的Dropout mask都相同,則可傳入noise_shape=(batch_size, 1, features)。
seed:整數,使用的隨機數種子
keras.layers.core.Flatten()
Flatten層用來將輸入「壓平」,即把多維的輸入一維化,經常使用在從卷積層到全鏈接層的過渡。Flatten不影響batch的大小。
model = Sequential() model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 32, 32))) # now: model.output_shape == (None, 64, 32, 32) model.add(Flatten()) # now: model.output_shape == (None, 65536)
keras.layers.core.Reshape(target_shape)
Reshape層用來將輸入shape轉換爲特定的shape
任意,但輸入的shape必須固定。當使用該層爲模型首層時,須要指定input_shape
參數
(batch_size,)+target_shape
# as first layer in a Sequential model model = Sequential() model.add(Reshape((3, 4), input_shape=(12,))) # now: model.output_shape == (None, 3, 4) # note: `None` is the batch dimension # as intermediate layer in a Sequential model model.add(Reshape((6, 2))) # now: model.output_shape == (None, 6, 2) # also supports shape inference using `-1` as dimension model.add(Reshape((-1, 2, 2))) # now: model.output_shape == (None, 3, 2, 2)
keras.layers.core.Permute(dims)
Permute層將輸入的維度按照給定模式進行重排,例如,當須要將RNN和CNN網絡鏈接時,可能會用到該層。
model = Sequential() model.add(Permute((2, 1), input_shape=(10, 64))) # now: model.output_shape == (None, 64, 10) # note: `None` is the batch dimension
任意,當使用激活層做爲第一層時,要指定input_shape
與輸入相同,可是其維度按照指定的模式從新排列
keras.layers.core.RepeatVector(n)
RepeatVector層將輸入重複n次
形如(nb_samples, features)的2D張量
形如(nb_samples, n, features)的3D張量
model = Sequential() model.add(Dense(32, input_dim=32)) # now: model.output_shape == (None, 32) # note: `None` is the batch dimension model.add(RepeatVector(3)) # now: model.output_shape == (None, 3, 32)
keras.layers.core.Lambda(function, output_shape=None, mask=None, arguments=None)
本函數用以對上一層的輸出施以任何Theano/TensorFlow表達式
function:要實現的函數,該函數僅接受一個變量,即上一層的輸出
output_shape:函數應該返回的值的shape,能夠是一個tuple,也能夠是一個根據輸入shape計算輸出shape的函數
mask: 掩膜
arguments:可選,字典,用來記錄向函數中傳遞的其餘關鍵字參數
# add a x -> x^2 layer model.add(Lambda(lambda x: x ** 2))
# add a layer that returns the concatenation # of the positive part of the input and # the opposite of the negative part def antirectifier(x): x -= K.mean(x, axis=1, keepdims=True) x = K.l2_normalize(x, axis=1) pos = K.relu(x) neg = K.relu(-x) return K.concatenate([pos, neg], axis=1) def antirectifier_output_shape(input_shape): shape = list(input_shape) assert len(shape) == 2 # only valid for 2D tensors shape[-1] *= 2 return tuple(shape) model.add(Lambda(antirectifier, output_shape=antirectifier_output_shape))
任意,當使用該層做爲第一層時,要指定input_shape
由output_shape
參數指定的輸出shape,當使用tensorflow時可自動推斷
keras.layers.core.ActivityRegularization(l1=0.0, l2=0.0)
通過本層的數據不會有任何變化,但會基於其激活值更新損失函數值
l1:1範數正則因子(正浮點數)
l2:2範數正則因子(正浮點數)
任意,當使用該層做爲第一層時,要指定input_shape
與輸入shape相同
keras.layers.core.Masking(mask_value=0.0)
使用給定的值對輸入的序列信號進行「屏蔽」,用以定位須要跳過的時間步
對於輸入張量的時間步,即輸入張量的第1維度(維度從0開始算,見例子),若是輸入張量在該時間步上都等於mask_value
,則該時間步將在模型接下來的全部層(只要支持masking)被跳過(屏蔽)。
若是模型接下來的一些層不支持masking,卻接受到masking過的數據,則拋出異常。
考慮輸入數據x
是一個形如(samples,timesteps,features)的張量,現將其送入LSTM層。由於你缺乏時間步爲3和5的信號,因此你但願將其掩蓋。這時候應該:
賦值x[:,3,:] = 0.
,x[:,5,:] = 0.
在LSTM層以前插入mask_value=0.
的Masking
層
model = Sequential() model.add(Masking(mask_value=0., input_shape=(timesteps, features))) model.add(LSTM(32))
參考網址連接:https://keras-cn.readthedocs.io/en/latest/
如有興趣交流分享技術,可關注本人公衆號,裏面會不按期的分享各類編程教程,和共享源碼,諸如研究分享關於c/c++,python,前端,後端,opencv,halcon,opengl,機器學習深度學習之類有關於基礎編程,圖像處理和機器視覺開發的知識