import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms # 配置GPU或CPU设置
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 超参数设置
sequence_length = 28
input_size = 28
hidden_size = 128
num_layers = 2
num_classes = 10
batch_size = 100
num_epochs = 2
learning_rate = 0.01 # MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='./data/',
train=True,
transform=transforms.ToTensor(),# 将PIL Image或者 ndarray 转换为tensor,并且归一化至[0-1],归一化至[0-1]是直接除以255
download=True) test_dataset = torchvision.datasets.MNIST(root='./data/',
train=False,
transform=transforms.ToTensor())# 将PIL Image或者 ndarray 转换为tensor,并且归一化至[0-1],归一化至[0-1]是直接除以255 # 训练数据加载,按照batch_size大小加载,并随机打乱
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
# 测试数据加载,按照batch_size大小加载
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False) # Recurrent neural network (many-to-one) 多对一
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(RNN, self).__init__() # 继承 __init__ 功能
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) # if use nn.RNN(), it hardly learns LSTM 效果要比 nn.RNN() 好多了
self.fc = nn.Linear(hidden_size, num_classes) def forward(self, x):
# Set initial hidden and cell states
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) # Forward propagate LSTM
out, _ = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size) # Decode the hidden state of the last time step
out = self.fc(out[:, -1, :])
return out model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)
print(model)
# RNN((lstm): LSTM(28, 128, num_layers=2, batch_first=True)
# (fc): Linear(in_features=128, out_features=10, bias=True)) # 损失函数与优化器设置
# 损失函数
criterion = nn.CrossEntropyLoss()
# 优化器设置 ,并传入RNN模型参数和相应的学习率
optimizer = torch.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
loss = criterion(outputs, labels) # 反向传播与优化
# 清空上一步的残余更新参数值
optimizer.zero_grad()
# 反向传播
loss.backward()
# 将参数更新值施加到RNN model的parameters上
optimizer.step()
# 每迭代一定步骤,打印结果值
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)) # 保存已经训练好的模型
# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')

  

Recurrent neural network (RNN) - Pytorch版的更多相关文章

  1. Convolutional neural network (CNN) - Pytorch版

    import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms # ...

  2. Recurrent Neural Network(循环神经网络)

    Reference:   Alex Graves的[Supervised Sequence Labelling with RecurrentNeural Networks] Alex是RNN最著名变种 ...

  3. 机器学习: Python with Recurrent Neural Network

    之前我们介绍了Recurrent neural network (RNN) 的原理: http://blog.csdn.net/matrix_space/article/details/5337404 ...

  4. Recurrent Neural Network系列2--利用Python,Theano实现RNN

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORKS T ...

  5. Recurrent Neural Network系列3--理解RNN的BPTT算法和梯度消失

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 这是RNN教程的第三部分. 在前面的教程中,我们从头实现了一个循环 ...

  6. 循环神经网络(Recurrent Neural Network,RNN)

    为什么使用序列模型(sequence model)?标准的全连接神经网络(fully connected neural network)处理序列会有两个问题:1)全连接神经网络输入层和输出层长度固定, ...

  7. 4.5 RNN循环神经网络(recurrent neural network)

     自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取: https://www.cnblogs.com/bclshuai/p/11380657.html 1.1  RNN循环神经网络 ...

  8. Recurrent Neural Network系列1--RNN(循环神经网络)概述

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORKS T ...

  9. Recurrent Neural Network系列4--利用Python,Theano实现GRU或LSTM

    yi作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORK ...

随机推荐

  1. 【Python】安装MySQLdb模块centos 6.1 宝塔Linux面板 MySQL5.6

    [Python]安装MySQLdb模块centos 6.1 宝塔Linux面板 MySQL5.6 总之是各种坑 先说一下,宝塔安装在centos 6.1 i368 也就是32位系统上的方法 https ...

  2. JSP迭代标签

    1. 新建LoopTag类,代码如下: package bid.zhazhapan.fims.tag; import java.io.IOException; import java.util.Col ...

  3. [HackTheBox]WEB题目

    0x01 [50 Points] I know Mag1k 问题描述: Can you get to the profile page of the admin? 访问分配的地址,是一个带注册的登入页 ...

  4. 2018-2019-2 20165212《网络对抗技术》Exp9 Web安全基础

    2018-2019-2 20165212<网络对抗技术>Exp9 Web安全基础 基础问题回答 1.SQL注入攻击原理,如何防御? 原理:SQL注入,就是通过把SQL命令插入到Web表单递 ...

  5. ubuntu之路——day10.2单一数字评估指标与满足和优化的评估指标

    单一数字评估指标: 我们在平时常用到的模型评估指标是精度(accuracy)和错误率(error rate),错误率是:分类错误的样本数站样本总数的比例,即E=n/m(如果在m个样本中有n个样本分类错 ...

  6. web前端兼容性问题

    传送门:https://www.cnblogs.com/zhoudawei/p/7497544.html

  7. Thingsboard HTTP连接至服务器

    当布署了Thingsboard服务器后,可以通过在服务器地址后,加入swagger-ui.html来打开API文档

  8. java.lang.ClassNotFoundException: org.apache.jsp.error_jsp

    缺少jar包 第一个:standard-1.1.2.jar 第二个:jstl-1.2.jar

  9. 关于微信手机端IOS系统中input输入框无法输入的问题

    如果网站不需要阻止用户的选择内容的行为就可以使用如下样式: * { -webkit-user-select: text; -user-select: text;}另一种方式: *: not(input ...

  10. php redis set 单机锁(转)

    如果一个请求更新缓存的时间比较长,甚至比锁的有效期还要长,导致在缓存更新过程中,锁就失效了,此时另一个请求会获取锁,但前一个请求在缓存更新完毕的时候,如果不加以判断直接删除锁,就会出现误删除其它请求创 ...