基于LSTM的Mnist数字识别(tensorflow实现)

# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
# 导入 MINST 数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

n_input = 28            # MNIST data 输入 (img shape: 28*28)
n_steps = 28        # timesteps
n_hidden = 128      # hidden layer num of features
n_classes = 10      # MNIST 列别 (0-9 ,一共10类)
batch_size = 128

tf.reset_default_graph()
# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
y = tf.placeholder("float", [None, n_classes])

stacked_rnn = []
for i in range(3):
    stacked_rnn.append(tf.contrib.rnn.LSTMCell(n_hidden))
mcell = tf.contrib.rnn.MultiRNNCell(stacked_rnn)

x1 = tf.unstack(x, n_steps, 1)
outputs, states = tf.contrib.rnn.static_rnn(mcell, x1, dtype=tf.float32)
pred = tf.contrib.layers.fully_connected(outputs[-1],n_classes,activation_fn = None)

learning_rate = 0.001
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

training_iters = 100000
display_step = 10

# 启动session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    step = 1
    # Keep training until reach max iterations
    while step * batch_size < training_iters:
        batch_x, batch_y = mnist.train.next_batch(batch_size)
        # Reshape data to get 28 seq of 28 elements
        batch_x = batch_x.reshape((batch_size, n_steps, n_input))
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
        if step % display_step == 0:
            # 计算批次数据的准确率
            acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
            print ("Iter " + str(step*batch_size) + ", Minibatch Loss= " +  "{:.6f}".format(loss) + ", Training Accuracy= " +  "{:.5f}".format(acc))
        step += 1
    print (" Finished!")

    # 计算准确率 for 128 mnist test images
    test_len = 100
    test_data = mnist.test.images[:test_len].reshape((-1, n_steps, n_input))
    test_label = mnist.test.labels[:test_len]
    print ("Testing Accuracy:", sess.run(accuracy, feed_dict={x: test_data, y: test_label}))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,以下是使用BiLSTM和单向LSTMMNIST手写数字数据集进行识别的Python代码实现和比较。 ```python import tensorflow as tf from tensorflow import keras import numpy as np # 加载数据集 (x_train, y_train), (x_test, y_test) = keras.datasets.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模型 model_lstm = keras.Sequential([ keras.layers.LSTM(units=128, input_shape=(28, 28)), keras.layers.Dense(units=10, activation='softmax') ]) model_lstm.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 搭建BiLSTM模型 model_bilstm = keras.Sequential([ keras.layers.Bidirectional(keras.layers.LSTM(units=128, input_shape=(28, 28))), keras.layers.Dense(units=10, activation='softmax') ]) model_bilstm.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model_lstm.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test)) model_bilstm.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test)) # 模型性能比较 loss, acc = model_lstm.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模型可以利用上下文信息,提高了模型的识别能力。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

东心十

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

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

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

打赏作者

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

抵扣说明:

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

余额充值