用python写一个基于minist数据集利用lstm模型实现手写字符识别的代码
时间: 2024-05-04 12:16:29 浏览: 117
基于pytorch搭建CNN神经网络实现MINIST数据集手写字识别python源码+模型.zip
以下是一个基于python编写的基于MNIST数据集利用LSTM模型实现手写字符识别的代码样例,仅供参考:
```
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
from keras.datasets import mnist
from keras.callbacks import TensorBoard
from keras.utils import to_categorical
batch_size = 128
num_classes = 10
epochs = 5
hidden_size = 128
# 输入图片维度
img_rows, img_cols = 28, 28
# 加载mnist数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 改变形状,以适配LSTM模型
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols)
input_shape = (img_rows, img_cols)
# 将数据转换为浮点类型,并转换为0到1之间的浮点数
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
# 将标签转换为独热编码
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
# 创建LSTM模型
model = Sequential()
model.add(LSTM(hidden_size, input_shape=input_shape, dropout=0.2))
model.add(Dense(num_classes, activation='softmax'))
# 编译并训练模型
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
tb_callback = TensorBoard(log_dir='./logs', write_graph=True)
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[tb_callback])
# 评估模型
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
希望这个代码样例能够对您有所帮助。如果您有任何其他问题,可以继续向我提问。
阅读全文