MultiLSTM预测Mnist

使用MultiLSTM预测MNIST手写数字
本文使用TensorFlow实现了一个基于MultiLSTM的模型,用于预测MNIST数据集的手写数字。通过动态RNN搭建LSTM网络,设置LSTM层数、隐藏单元数等参数,并使用Adam优化器进行训练。最终模型在测试集上进行预测并展示结果。
#!/usr/bin/python3
# -*-coding:utf-8 -*-
# @Time   :2018/3/14 
# @Author :machuanbin

"""
tensorflow :1.3.0
pandas:    0.19.2

"""
import tensorflow as tf
import os
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib import rnn
import numpy as np

config=tf.ConfigProto()
# config.gup_options.allow_growth=True
sess=tf.Session(config=config)


current_dir = os.path.abspath('.\MNIST_data')

mnist=input_data.read_data_sets(current_dir,one_hot=True)

# print(mnist.train.images.shape)
lr=1e-3

#在训练和测试的时候,我们想用不同的batch_size所以采用占位符

batch_size=tf.placeholder(tf.int32,[])
keep_prob=tf.placeholder(tf.float32,[])

# 每个时刻的输入特征是28维的,就是每个时刻输入一行,一行有 28 个像素
input_size=28
# 时序持续长度为28,即每做一次预测,需要先输入
使用LSTM训练MNIST数据集,主要思路是将MNIST数据集中图片的每一行或每一列当作一个序列,借助LSTM识别每一行的变化模式从而对数据集进行分类。具体方法步骤如下: 1. **载入数据集**:获取MNIST数据集。 2. **创建模型**:构建LSTM模型结构。 3. **定义优化器**:选择合适的优化器,如Adam等。 4. **编译模型**:配置模型的损失函数、优化器和评估指标。 5. **训练模型**:使用训练集对模型进行训练。 6. **打印模型摘要**:查看模型的结构和参数信息。 7. **绘制acc和loss曲线**:直观展示模型训练过程中的准确率和损失变化情况 [^1]。 以下是一个简单的示例代码(基于Keras): ```python import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.utils import to_categorical # 1. 载入数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 数据预处理 x_train = x_train.reshape(-1, 28, 28) / 255.0 x_test = x_test.reshape(-1, 28, 28) / 255.0 y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) # 2. 创建模型 model = Sequential() model.add(LSTM(128, input_shape=(28, 28))) model.add(Dense(10, activation='softmax')) # 3. 定义优化器 optimizer = tf.keras.optimizers.Adam() # 4. 编译模型 model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # 5. 训练模型 history = model.fit(x_train, y_train, epochs=5, batch_size=64, validation_data=(x_test, y_test)) # 6. 打印模型摘要 model.summary() # 7. 绘制acc和loss曲线(此处仅给出思路,需使用matplotlib库) import matplotlib.pyplot as plt plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], 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', 'Test'], loc='upper left') plt.show() ```
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值