RNN识别mnist数据集

用tensorflow跑RNN实现手写体的识别,下面上两个RNN的结构图



import tensorflow as tf
from tensorflow.contrib import rnn 
import input_data
import numpy as np
import matplotlib.pyplot as plt
print ("Packages imported")

mnist = input_data.read_data_sets("data/", one_hot=True)
trainimgs, trainlabels, testimgs, testlabels \
 = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels 
ntrain, ntest, dim, nclasses \
 = trainimgs.shape[0], testimgs.shape[0], trainimgs.shape[1], trainlabels.shape[1]
print ("MNIST loaded")
diminput  = 28
dimhidden = 128
dimoutput = nclasses
nsteps    = 28
weights = {
    'hidden': tf.Variable(tf.random_normal([diminput, dimhidden])), 
    'out': tf.Variable(tf.random_normal([dimhidden, dimoutput]))
}
biases = {
    'hidden': tf.Variable(tf.random_normal([dimhidden])),
    'out': tf.Variable(tf.random_normal([dimoutput]))
}
def _RNN(_X,_W,_b,_nsteps,_name):  
#第一步:转换输入,输入_X是还有batchSize=5的5张28*28图片,需要将输入从  
#[batchSize,nsteps,diminput]==>[nsteps,batchSize,diminput]  
    _X = tf.transpose(_X,[1,0,2])  
#第二步:reshape _X为[nsteps*batchSize,diminput]  
    _X = tf.reshape(_X,[-1,diminput])  
#第三步:input layer -> hidden layer  
    _H = tf.matmul(_X,_W['hidden'])+_b['hidden']  
#第四步:将数据切分为‘nsteps’个切片,第i个切片为第i个batch data  
    #tensoflow >0.12  
    _Hsplit = tf.split(_H,_nsteps,0)  
    #tensoflow <0.12  _Hsplit = tf.split(0,_nsteps,_H)  
#第五步:计算LSTM final output(_LSTM_O) 和 state(_LSTM_S)  
#_LSTM_O和_LSTM_S都有‘batchSize’个元素  
#_LSTM_O用于预测输出  
    with tf.variable_scope(_name) as scope:  
        #scope.reuse_variables()  
    # forget_bias = 1.0不忘记数据     
    ###tensorflow <1.0  
       # lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(dimhidden,forget_bias = 1.0)  
        #_LSTM_O,_SLTM_S = tf.nn.rnn(lstm_cell,_Hsplit,dtype=tf.float32)  
    ###tensorflow 1.0  
        lstm_cell = rnn.BasicLSTMCell(dimhidden)  
        _LSTM_O,_LSTM_S = rnn.static_rnn(lstm_cell,_Hsplit,dtype=tf.float32)  
#第六步:输出,需要最后一个RNN单元作为预测输出所以取_LSTM_O[-1]  
        _O = tf.matmul(_LSTM_O[-1],_W['out'])+_b['out']  
    return {  
        'X':_X,  
        'H':_H,  
        '_Hsplit':_Hsplit,  
        'LSTM_O':_LSTM_O,  
        'LSTM_S':_LSTM_S,  
        'O':_O  
}  
print("Network Ready!")  
learning_rate = 0.001  
x = tf.placeholder("float",[None,nsteps,diminput])  
y = tf.placeholder("float",[None,dimoutput])  
myrnn = _RNN(x,weights,biases,nsteps,'basic1')  
pred = myrnn['O']  
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred,labels=y))  
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)#Adam  
accr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred,1),tf.argmax(y,1)),tf.float32))  
init = tf.global_variables_initializer()  
print("Network Ready!")  
training_epochs = 5  
batch_size      = 16  
display_step    = 1  
sess = tf.Session()  
sess.run(init)  
print ("Start optimization")  
for epoch in range(training_epochs):  
    avg_cost = 0.  
    #total_batch = int(mnist.train.num_examples/batch_size)  
    total_batch = 100  
    # Loop over all batches  
    for i in range(total_batch):  
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)  
        batch_xs = batch_xs.reshape((batch_size, nsteps, diminput))  
        #print(batch_xs.shape)  
        #print(batch_ys.shape)  
        #batch_ys = batch_ys.reshape((batch_size, dimoutput))  
        # Fit training using batch data  
        feeds = {x: batch_xs, y: batch_ys}  
        sess.run(optm, feed_dict=feeds)  
        # Compute average loss  
        avg_cost += sess.run(cost, feed_dict=feeds)/total_batch  
    # Display logs per epoch step  
    if epoch % display_step == 0:   
        print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))  
        feeds = {x: batch_xs, y: batch_ys}  
        train_acc = sess.run(accr, feed_dict=feeds)  
        print (" Training accuracy: %.3f" % (train_acc))  
        testimgs = testimgs.reshape((ntest, nsteps, diminput))  
        feeds = {x: testimgs, y: testlabels}  
        test_acc = sess.run(accr, feed_dict=feeds)  
        print (" Test accuracy: %.3f" % (test_acc))  
print ("Optimization Finished.")  

打印结果:

Start optimization
Epoch: 000/005 cost: 1.964034666
 Training accuracy: 0.438
 Test accuracy: 0.410
Epoch: 001/005 cost: 1.420921708
 Training accuracy: 0.562
 Test accuracy: 0.475
Epoch: 002/005 cost: 1.189191381
 Training accuracy: 0.750
 Test accuracy: 0.482
Epoch: 003/005 cost: 1.054024348
 Training accuracy: 0.875
 Test accuracy: 0.597
Epoch: 004/005 cost: 0.930983863
 Training accuracy: 0.562
 Test accuracy: 0.606
Optimization Finished.

好的,以下是使用RNN识别MNIST数据集的详细代码。我们将使用PyTorch来实现这个任务。 ```python import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, transforms # 定义超参数 input_size = 28 sequence_length = 28 hidden_size = 128 num_layers = 2 num_classes = 10 batch_size = 100 num_epochs = 5 learning_rate = 0.001 # 加载MNIST数据集并进行预处理 train_dataset = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor()) # 使用DataLoader加载数据 train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) # 定义RNN模型 class RNN(nn.Module): def __init__(self, input_size, hidden_size, num_layers, num_classes): super(RNN, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, num_classes) def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) out, _ = self.rnn(x, h0) out = self.fc(out[:, -1, :]) return out # 将模型加载到GPU上 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = RNN(input_size, hidden_size, num_layers, num_classes).to(device) # 定义损失函数和优化器 criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) # 训练模型 total_step = len(train_loader) for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = images.reshape(-1, sequence_length, input_size).to(device) labels = labels.to(device) # 前向传播 outputs = model(images) loss = criterion(outputs, labels) # 反向传播和优化 optimizer.zero_grad() loss.backward() optimizer.step() # 每100个批次打印一次日志 if (i+1) % 100 == 0: print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item())) # 测试模型 with torch.no_grad(): correct = 0 total = 0 for images, labels in test_loader: images = images.reshape(-1, sequence_length, input_size).to(device) labels = labels.to(device) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total)) ``` 这段代码首先加载MNIST数据集并进行预处理。然后定义了一个RNN模型,将其加载到GPU上,并定义了损失函数和优化器。接下来进行训练和测试,最后输出测试结果。 需要注意的是,在训练和测试阶段,每个输入图像都被reshape为形状为(batch_size, sequence_length, input_size)的张量,其中sequence_length表示序列长度(即图像的高度),input_size表示每个时间步的输入大小(即图像的宽度)。这样做是为了适应RNN的输入要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值