一.序列模型
1.序列模型【寫法一】
序列模型屬於通用模型的一種,這種模型各層之間是依次順序的線性關系。在第k層和第k+1層之間可以加上各種元素來構造神經網絡。這些元素可以通過一個列表來制定,然后作為參數傳遞給序列模型來生成相應的模型。
from keras.models import Sequential from keras.layers import Dense from keras.layers import Activation # input_shape 輸入層,784表示輸入樣式 layers = [Dense(32, input_shape=(784,)), # Dense 全連接層,32表示全連接層上面有32個神經元 Activation('relu'), # 激活函數relu Dense(10), Activation('softmax')] model = Sequential(layers) # 構建序列模型 model.summary() # 打印模型信息
執行結果:
解析:
a.25120=784*32 + 32,表示全連接層要計算的參數個數,32表示截距
b.330=32*10 + 10 解析同上
c.25450=25120+330 表示全部要計算的參數個數
2.序列模型【寫法二】
from keras.models import Sequential from keras.layers import Dense from keras.layers import Activation model = Sequential() model.add(Dense(32, input_shape=(784,))) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('softmax')) model.summary()
執行結果同上!
二.通用模型
通用模型可以用來設計非常復雜、任意拓撲結構的神經網絡。類似於序列模型,通用模型通過函數化的應用接口來定義模型。在通用模型中,從輸入的多維矩陣開始,然后定義各層及其要素,最后定義輸出層。將輸入層和輸出層作為參數納入通用模型中就可以定義一個模型對象。
from keras.models import Model from keras.layers import Input, Dense # 定義輸入層 input = Input(shape=(784,)) # 定義各個連接層,包括兩個全連接層,使用relu和softmax激活函數 layer1 = Dense(64, activation='relu')(input) layer2 = Dense(64, activation='relu')(layer1) # 定義輸出層 out = Dense(10, activation='softmax')(layer2) # 定義模型對象 model = Model(inputs=input, output=out) model.summary()
執行結果: