【Keras】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

写文不容易,请给个赞吧!


  • 7
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茶冻茶茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值