日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Keras】LSTM和Bi-LSTM神经网络

發布時間:2023/12/10 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Keras】LSTM和Bi-LSTM神经网络 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

KerasLSTM和Bi-LSTM神經網絡

  • 導入安裝包
  • 加載并劃分數據集
  • 數據處理
  • 創建LSTM模型并訓練
  • 評估模型
  • 創建Bi-LSTM模型并訓練
  • 打印Bi-LSTM模型
  • 評估Bi-LSTM模型

導入安裝包

import tensorflow.keras from tensorflow.keras.datasets import mnist from tensorflow.keras.layers import Dense,LSTM,Bidirectional from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential

加載并劃分數據集

使用手寫數字數據

#劃分數據集 (x_train,y_train),(x_test,y_test) = mnist.load_data()

數據處理

數據類型轉換:
x_train和x_test里的數據都是int整數,要把它們轉換成float32浮點數
數據歸一化處理:
要把x_train和x_test里的整數變成0-1之間的浮點數,就要除以255。因為色彩的數值是0-255,所以要變成0-1之間的浮點數,只要簡單的除以255
one-hot處理:
y值0-9數字變成onehot模式,以后就可以把分類數據變成這種形式

#設置數據類型為float32 x_train = x_train.astype('float32') x_test = x_test.astype('float32')# 數據值映射在[0,1]之間 x_train = x_train/255 x_test = x_test/255#數據標簽one-hot處理 y_train = keras.utils.to_categorical(y_train,10) y_test = keras.utils.to_categorical(y_test,10) print(y_train[1])

創建LSTM模型并訓練

nb_lstm_outputs = 30#神經元個數 nb_time_steps = 28 #時間序列長度 nb_input_vector = 28 #輸入序列#創建模型 model = Sequential() model.add(LSTM(nb_lstm_outputs,input_shape=(nb_time_steps,nb_input_vector))) model.add(Dense(10,activation='softmax'))model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc']) model.fit(x_train,y_train,epochs=20,batch_size=128)

#打印模型 model.summary()

評估模型

model.evaluate(x_test, y_test,batch_size=128, verbose=1)

預測結果比前文的簡單神經網絡要好:
準確度從0.9615提升到0.9751

創建Bi-LSTM模型并訓練

# building model model = Sequential() model.add(Bidirectional(LSTM(nb_lstm_outputs,return_sequences=True),input_shape=(nb_time_steps, nb_input_vector))) model.add(Bidirectional(LSTM(nb_lstm_outputs))) model.add(Dense(10,activation='softmax'))#編譯模型 model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc']) #訓練模型 model.fit(x_train,y_train,epochs=20,batch_size=128)

打印Bi-LSTM模型

model.summary()

評估Bi-LSTM模型

model.evaluate(x_test, y_test,batch_size=128)

準確度從0.9751提升到0.9861

寫文不容易,請給個贊吧!


總結

以上是生活随笔為你收集整理的【Keras】LSTM和Bi-LSTM神经网络的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。