python 循环神经网络RNN实例——手写数字识别

数据集官网:http://yann.lecun.com/exdb/mnist/
参考:https://github.com/MorvanZhou/PyTorch-Tutorial/blob/master/tutorial-contents/402_RNN_classifier.py
代码包含自动下载数据集

import torch
from torch import nn,optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision import datasets
import os

batch_size = 200    #分批训练数据、每批数据量
learning_rate = 1e-2    #学习率
num_epoches = 10       #训练次数
DOWNLOAD_MNIST = False    #是否网上下载数据

# Mnist digits dataset
if not(os.path.exists('./mnist/')) or not os.listdir('./mnist/'):
    # not mnist dir or mnist is empyt dir
    DOWNLOAD_MNIST = True

train_dataset = datasets.MNIST(
    root = './mnist',
    train= True,        #download
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
手写体数字识别是一个经典的图像识别问题,可以使用循环神经网络RNN)进行解决。在本文中,我们将使用Python和Tensorflow来实现一个RNN模型,用于识别手写数字。 首先,我们需要准备手写数字数据集。我们可以使用MNIST数据集,这是一个常用的手写数字数据集,包含了60000张训练图片和10000张测试图片。我们可以使用Tensorflow中的keras库来加载数据集。 ```python from tensorflow import keras # 加载数据集 (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # 将图像数据归一化到[0, 1] x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. # 将标签转换为one-hot编码 num_classes = 10 y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) ``` 接下来,我们需要将图像数据转换为序列数据,以便输入到RNN模型中。我们可以将每个图像的行作为一个序列,每个序列中的元素是该行的像素。 ```python # 将图像数据转换为序列数据 seq_length = x_train.shape[1] # 图像的行数 input_dim = x_train.shape[2] # 每行的像素数 x_train_seq = x_train.reshape((x_train.shape[0], seq_length, input_dim)) x_test_seq = x_test.reshape((x_test.shape[0], seq_length, input_dim)) ``` 接下来,我们可以构建RNN模型。在这里,我们使用一个简单的LSTM网络,该网络将每个序列中的所有行作为输入,并将最后一个LSTM单元的输出传递给一个全连接层进行分类。 ```python from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense # 构建RNN模型 model = Sequential() model.add(LSTM(128, input_shape=(seq_length, input_dim))) model.add(Dense(num_classes, activation='softmax')) model.summary() ``` 我们可以使用Adam优化器和交叉熵损失函数来训练模型。 ```python # 编译模型 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(x_train_seq, y_train, epochs=10, batch_size=128, validation_data=(x_test_seq, y_test)) ``` 在训练完成后,我们可以使用测试数据集来评估模型的性能。 ```python # 在测试数据集上评估模型性能 score, acc = model.evaluate(x_test_seq, y_test, batch_size=128) print('Test score:', score) print('Test accuracy:', acc) ``` 完整的代码如下: ```python from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense # 加载数据集 (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # 将图像数据归一化到[0, 1] x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. # 将标签转换为one-hot编码 num_classes = 10 y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) # 将图像数据转换为序列数据 seq_length = x_train.shape[1] # 图像的行数 input_dim = x_train.shape[2] # 每行的像素数 x_train_seq = x_train.reshape((x_train.shape[0], seq_length, input_dim)) x_test_seq = x_test.reshape((x_test.shape[0], seq_length, input_dim)) # 构建RNN模型 model = Sequential() model.add(LSTM(128, input_shape=(seq_length, input_dim))) model.add(Dense(num_classes, activation='softmax')) model.summary() # 编译模型 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(x_train_seq, y_train, epochs=10, batch_size=128, validation_data=(x_test_seq, y_test)) # 在测试数据集上评估模型性能 score, acc = model.evaluate(x_test_seq, y_test, batch_size=128) print('Test score:', score) print('Test accuracy:', acc) ``` 通过运行上面的代码,我们可以得到一个简单的RNN模型,用于手写数字识别
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值