【深度学习】用LSTM识别手写数字MNIST数据集(tensorflow1.x实现)

网络结构:

网络结构

就是LSTM后面再加一层全连接层。

输入输出分析:

数据集特征

MNIST数据集详解:点击查看MNIST详解

  • 数据集中的手写数字是个(28,28)的灰度像素二维数组。
  • 在此可以将其行向量看做是连续的28个时间序列,故代码中TIME_STEP=28,每一行就是LSTM在时间t的输入其输入数据的维度INPUT_SIZE
    = 28
  • 代码中NUM_UNITS = 128 表示LSTM的输出h_t的维度是128,具体见下图,其中num_units就是输出维度。

在这里插入图片描述

代码:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# property:train test validation  -->images(n,784) labels(n,10)
"""加载数据"""
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

"""参数设置"""
BATCH_SIZE = 128        # BATCH的大小,相当于一次处理128个image
TIME_STEP = 28          # 一个LSTM中,输入序列的长度,image有28行
INPUT_SIZE = 28         # x_i 的向量长度,image有28列
LR = 0.001               # 学习率
NUM_UNITS = 128         # 多少个LTSM单元
ITERATIONS = 8000         # 迭代次数
N_CLASSES = 10            # 输出大小,0-9十个数字的概率
"""定义计算"""
# 定义 placeholders 以便接收x,y
# 维度是[BATCH_SIZE,TIME_STEP * INPUT_SIZE]
train_x = tf.placeholder(tf.float32, [None, TIME_STEP * INPUT_SIZE])
# 输入的是二维数据,将其还原为三维,维度是[BATCH_SIZE, TIME_STEP, INPUT_SIZE]
image = tf.reshape(train_x, [-1, TIME_STEP, INPUT_SIZE])
train_y = tf.placeholder(tf.int32, [None, N_CLASSES])
# 定义RNN(LSTM)结构
rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=NUM_UNITS)
outputs, final_state = tf.nn.dynamic_rnn(
    cell=rnn_cell,              # 选择传入的cell
    inputs=image,               # 传入的数据
    initial_state=None,         # 初始状态
    dtype=tf.float32,           # 数据类型
    # False: (batch, time_step, x_input); True: (time_step,batch,x_input),
    # 这里根据image结构选择False
    # If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.
    time_major=False,
)
# output = outputs[:, -1, :]
output = tf.layers.dense(
    inputs=outputs[:, -1, :], units=N_CLASSES)  # 取最后一路输出送入全连接层

"""定义损失和优化方法"""
loss = tf.losses.softmax_cross_entropy(
    onehot_labels=train_y,
    logits=output)      # 计算loss

train_op = tf.train.AdamOptimizer(LR).minimize(loss)  # 选择优化方法

correct_prediction = tf.equal(
    tf.argmax(
        train_y, axis=1), tf.argmax(
            output, axis=1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))  # 计算正确率
"""训练"""
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())     # 初始化计算图中的变量
    for step in range(ITERATIONS):    # 开始训练
        x, y = mnist.train.next_batch(BATCH_SIZE)
        _, loss_ = sess.run([train_op, loss], {train_x: x, train_y: y})
        if step % 500 == 0:      # test(validation)
            test_x, test_y = mnist.test.next_batch(5000)
            accuracy_ = sess.run(accuracy, {train_x: test_x, train_y: test_y})
            print('train loss: %f' % loss_, '| validation accuracy: %f' % accuracy_)

参考引用:

https://www.cnblogs.com/sandy-t/p/6930608.html [搭建RNN(LSTM)进行MNIST 手写数字辨识]

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是使用BiLSTM和单向LSTMMNIST手写数字数据集进行识别的代码实现和比较。 ## 数据集处理 首先,我们需要对MNIST手写数字数据集进行处理。我们可以使用Keras自带的`mnist`模块进行下载和处理。 ```python from keras.datasets import mnist # 加载数据集 (x_train, y_train), (x_test, y_test) = mnist.load_data() # 将像素值缩放到0-1之间 x_train = x_train / 255.0 x_test = x_test / 255.0 # 将标签转换为one-hot编码 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) # 调整输入数据的形状 x_train = np.reshape(x_train, (60000, 28, 28)) x_test = np.reshape(x_test, (10000, 28, 28)) ``` ## 搭建单向LSTM模型 ```python from keras.models import Sequential from keras.layers import LSTM, Dense model = Sequential() model.add(LSTM(units=128, input_shape=(28, 28))) model.add(Dense(units=10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ``` ## 搭建BiLSTM模型 ```python from keras.layers import Bidirectional model = Sequential() model.add(Bidirectional(LSTM(units=128, input_shape=(28, 28)))) model.add(Dense(units=10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ``` ## 训练模型 ```python model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test)) ``` ## 模型性能比较 我们可以将单向LSTM和BiLSTM模型在测试集上进行性能比较。 ```python loss, acc = model.evaluate(x_test, y_test) print('单向LSTM模型:') print('测试集上的损失:', loss) print('测试集上的准确率:', acc) loss, acc = model_bilstm.evaluate(x_test, y_test) print('BiLSTM模型:') print('测试集上的损失:', loss) print('测试集上的准确率:', acc) ``` 根据实验结果可以发现,使用BiLSTM模型的准确率要高于单向LSTM模型,这是因为BiLSTM模型可以利用上下文信息,提高了模型的识别能力。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值