40题刷爆Keras,人生苦短我选Keras
零、導入
1.導入 Keras 庫,并打印版本信息
import keras print(keras.__version__)一、一個簡單的例子
使用MLP模型實現手寫數字圖像MNIST的分類?
1.1 選擇模型
2.初始化一個順序模型(Sequential)
model = Sequential()1.2 構建網絡
3.為model加入一個784輸入,784個輸出的隱藏層,激活函數使用relu
model.add(Dense(units=784, activation='relu', input_dim=784))4.在之前的基礎上為model加入10個輸出的輸出層,激活函數使用softmax
model.add(Dense(units=10, activation='softmax'))5.通過.summary()查看模型參數情況
model.summary()1.3 編譯模型
6.使用.compile() 來配置學習過程,代價函數loss使用categorical_crossentropy,優化算法optimizer使用sgd,性能的指標使用accuracy
model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])1.4 訓練
讀入數據(略)
7.將y值進行one-hot編碼
y_train = to_categorical(y_train) y_test = to_categorical(y_test)8.將數據送入模型訓練
model.fit(x_train, y_train, epochs=5, batch_size=32)9.評估模型性能
score = model.evaluate(x_test, y_test, batch_size=128) print("loss:",score[0]) print("accu:",score[1])1.5 預測
10.使用模型進行預測
model.predict_classes(x_test, batch_size=128)二、稍微復雜的順序模型
使用LeNet5實現CIFAR10數據集的分類
2.1 選擇模型
11.新建一個順序模型
model = Sequential()2.2 構建網絡
12.完成INPUT-C1:添加一個二維卷積層,輸入為32x32x3,卷積核大小為5x5,核種類6個,并且假設我們不小心漏了relu
model.add(Conv2D(6, (5, 5), input_shape=(32, 32,3)))13.剛剛不小心漏了relu,現在可以另外加上
model.add(Activation('relu'))14.完成C1-S2:2x2下采樣層
model.add(MaxPooling2D(pool_size=(2, 2)))15.完成S2-C3:二維卷積,16個內核,5x5的大小,別忘記relu
model.add(Conv2D(16, (5, 5), activation='relu'))16.完成C3-S4:2x2下采樣層
model.add(MaxPooling2D(pool_size=(2, 2)))17.完成S4-C5:先添加平坦層
model.add(Flatten())18.再添加全連接層,輸出120維,激活函數relu
model.add(Dense(120, activation='relu'))19.完成C5-F6:添加全連接層,84個輸出,激活函數relu
model.add(Dense(84, activation='relu'))20.完成F6-OUTPUT:添加全連接層,10個輸出,激活函數softmax
model.add(Dense(10, activation='softmax'))2.3 編譯
21.設置隨機梯度下降SGD優化算法的參數,learning_rate=0.01,epoch=25,decay=learning_rate/epoch,momentum=0.9,nesterov=False
from keras.optimizers import SGDlrate = 0.01 epoch = 10 decay = lrate/epoch sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)23.編譯模型,代價函數loss使用categorical_crossentropy,優化算法前面已經定義了,性能的指標使用accuracy
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])2.4 訓練
讀入數據 & 預處理(略)
24.將數據送入模型,并且設置20%為驗證集
history=model.fit(x=train_X, y=train_Y,validation_split=0.2, epochs=10, batch_size=32, verbose=1)25.可視化歷史訓練的 訓練集 及 驗證集 的準確率值 可視化歷史訓練的 訓練集 及 驗證集 的損失值
plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'val'], loc='upper left') plt.show() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'val'], loc='upper left') plt.show()26.模型評估
scores = model.evaluate(test_X, test_Y, verbose=0) print(model.metrics_names) print(scores)2.5 預測
27.預測結果
prediction=model.predict_classes(test_X) prediction[:10]可視化預測結果?
顯示混淆矩陣
import pandas as pd print(classes) pd.crosstab(y_gt.reshape(-1),prediction,rownames=['label'],colnames=['predict'])三、Model式模型
這部分會實現一個多輸入多輸出的模型?
3.1 構建網絡
這里我們選擇函數式模型(model),所以不需要提前實例化,先將網絡結構實現
28.定義①,主要輸入層,接收新聞標題本身,即一個整數序列(每個整數編碼一個詞)。這些整數在 1 到 10,000 之間(10,000 個詞的詞匯表),且序列長度為 100 個詞。命名main_input
main_input = Input(shape=(100,), dtype='int32', name='main_input')29.定義②,將輸入序列編碼為一個稠密向量的序列,輸出每個向量維度為 512。
x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input)30.定義③,LSTM 層把向量序列轉換成單個向量,它包含整個序列的上下文信息,輸出維度32
lstm_out = LSTM(32)(x)31.定義⑩,其作為輔助損失,使得即使在模型主損失很高的情況下,LSTM 層和 Embedding 層都能被平穩地訓練。輸出維度1,激活函數sigmoid,命名aux_output
auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)32.定義⑨,輸入輔助數據,5維向量,命名aux_input
auxiliary_input = Input(shape=(5,), name='aux_input')33.定義④,將輔助輸入數據與 LSTM 層的輸出連接起來,輸入到模型中
x = keras.layers.concatenate([lstm_out, auxiliary_input])34.定義⑤⑥⑦,堆疊多個全連接網絡層,輸出均為64維
x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x)35.定義⑧,輸出層,激活函數sigmoid,命名main_output
main_output = Dense(1, activation='sigmoid', name='main_output')(x)3.2 定義模型
36.定義一個具有兩個輸入和兩個輸出的模型
model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])3.3 編譯
37.編譯模型,給輔助損失分配0.2的權重
model.compile(optimizer='rmsprop',loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'},loss_weights={'main_output': 1., 'aux_output': 0.2})3.4 訓練
讀取數據(略)
38.把數據送入模型訓練
model.fit({'main_input': headline_data, 'aux_input': additional_data},{'main_output': headline_labels, 'aux_output': additional_labels},epochs=50, batch_size=32,verbose=0)3.5 預測
model.predict({'main_input': headline_data, 'aux_input': additional_data})四、模型的保存與讀取
39.保存模型及其權重
# 保存模型 model_json = model.to_json() json_file = open("model.json", "w") json_file.write(model_json) json_file.close() # 保存權重 model.save_weights("model.h5")40.讀取模型及其權重
from keras.models import model_from_json # 讀取模型 json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # 讀取權重 loaded_model.load_weights("model.h5") # 使用之前記得要編譯一下 model.compile(optimizer='rmsprop',loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'},loss_weights={'main_output': 1., 'aux_output': 0.2})往期精彩回顧適合初學者入門人工智能的路線及資料下載機器學習在線手冊深度學習在線手冊AI基礎下載(pdf更新到25集)本站qq群1003271085,加入微信群請回復“加群”獲取一折本站知識星球優惠券,請回復“知識星球”喜歡文章,點個在看
總結
以上是生活随笔為你收集整理的40题刷爆Keras,人生苦短我选Keras的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Yoshua Bengio等图神经网络的
- 下一篇: 头条+腾讯 双杀面经(NLP实习)