Keras搭建序贯式模型
生活随笔
收集整理的這篇文章主要介紹了
Keras搭建序贯式模型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習Keras搭建序貫式模型,并學習使用MNIST手寫數字識別例子
from tensorflow.keras import layers, models# 創建一個序貫式模型對象 model = models.Sequential()# 添加第一個網絡層(作為輸入層) # 參數1:本層神經元個數,2:激活函數類型,3:輸入樣本的形狀 model.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))# 添加第二個網絡層(作為輸出層) # 參數1:輸出個數,2:激活函數類型 model.add(layers.Dense(10, activation='softmax'))# 輸出模型的概覽 model.summary()使用MNIST手寫數字識別例子,MNIST是經典的手寫數字圖片數據集,下載地址:https://s3.amazonaws.com/img-datasets/mnist.npz,下載后存放于python代碼的目錄下
from tensorflow.keras import datasets# 1.加載MNIST數據集# 加載數據集 (X_train, y_train),(X_test, y_test)=datasets.mnist.load_data()# 查看拆分結果 print(X_train.shape, y_train.shape) print(X_test.shape, y_test.shape)# 2.使用Matplotlib查看圖片 import matplotlib.pyplot as plt# 查看訓練集前10張圖片 fig = plt.figure(figsize=(12,4)) #定義畫板 for i in range(10):ax = fig.add_subplot(2,5, i+1)ax.matshow(X_train[i]) plt.show()# 3.數據預處理,搭建前饋神經網絡 #搭建序貫式模型,第一個網絡層作為輸入層,使用512個神經元(可以自定義),第二個網絡層作為輸出層,使用10個神經元(對應10個類別),激活函數使用softmax from tensorflow.keras import layers, models# 轉換數據集的形狀,(轉成二維) X_train = X_train.reshape(60000, 28*28) X_test = X_test.reshape(10000, 28*28) print(X_train.shape)# 創建一個序貫式模型對象 model = models.Sequential()# 添加第一個網絡層(作為輸入層) # 參數1:本層神經元個數,2:激活函數類型,3:輸入樣本的形狀 model.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))# 添加第二個網絡層(作為輸出層) model.add(layers.Dense(10, activation='softmax'))# 輸出模型的概覽 model.summary()# 4.編譯、訓練模型,評估準確率 # 編譯參數包括優化器、損失函數、評價指標 # 編譯模型 model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy',metrics=['accuracy'])# 訓練模型 # 訓練參數包括:訓練集數據、訓練集標簽、訓練迭代次數、批尺寸 model.fit(X_train, y_train, epochs = 5, batch_size = 128)# 在測試集上評估模型 # 評估參數包括:測試集數據、測試集標簽 test_loss,test_acc = model.evaluate(X_test, y_test) print(test_acc)# 5.使用模型識別手寫數字圖片 import numpy as np index = 9plt.matshow(X_test[index].reshape(28,28)) # 查看圖片 plt.show()# 使用模型識別該圖片 result = model.predict(X_test[index].reshape(-1,28*28)) print(np.around(result)) print(np.argmax(result))# 保存模型 # 策略一:保存全模型(網絡結構+權重+編譯配置) # model.save('mnist_model.h5') # model = models.load_model('mnist_model.h5') # 策略二:僅保存權重 # model.save_weights('mnist_weight_model.h5') # model.load_weights('mnist_weight_model.h5') # 策略三:僅保存網絡結構 # json_string = model.to_json() # with open('mnist_model_json.json', 'w') as f: # f.write(json_string) # with open('mnist_model_json.json', 'r') as f: # json_string = f.read() # model = models.model_from_json(json_string)總結
以上是生活随笔為你收集整理的Keras搭建序贯式模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【物联网毕设】基于Arduino与树莓派
- 下一篇: 负荷需求响应模型 基于Logistic函