pytorch白话入门笔记1.10-RNN循环神经网络(分类)

1.显示数据

代码

import torch
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt


# torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 1               # 训练整批数据多少次train the training data n times, to save time, we just train 1 epoch
BATCH_SIZE = 64         # 批训练的数据个数
TIME_STEP = 28          # 图像高度 rnn time step / image height
INPUT_SIZE = 28         # 图像宽度 rnn input size / image width
LR = 0.01               # learning rate学习效率
DOWNLOAD_MNIST = False   # True = 下载文件,此处已下载用False


# Mnist digital dataset
train_data = dsets.MNIST(
    root='./mnist/',                    # 保存位置
    train=True,                         # 训练数据;
    transform=transforms.ToTensor(),    # 转换成 PIL.Image or numpy.ndarray
                                        # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
    download=DOWNLOAD_MNIST,            # 下载数据
)

# plot one example
print(train_data.data.size())     # (60000, 28, 28)
print(train_data.targets.size())   # (60000)
plt.imshow(train_data.data[0].numpy(), cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()

运行结果

torch.Size([60000, 28, 28])
torch.Size([60000])

pytorch白话入门笔记1.10-RNN循环神经网络(分类)_第1张图片

2.打印RNN

代码

import torch
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt


# torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 1               # 训练整批数据多少次train the training data n times, to save time, we just train 1 epoch
BATCH_SIZE = 64         # 批训练的数据个数
TIME_STEP = 28          # 图像高度 rnn time step / image height
INPUT_SIZE = 28         # 图像宽度 rnn input size / image width
LR = 0.01               # learning rate学习效率
DOWNLOAD_MNIST = False   # True = 下载文件,此处已下载用False


# Mnist digital dataset
train_data = dsets.MNIST(
    root='./mnist/',                    # 保存位置
    train=True,                         # 训练数据;
    transform=transforms.ToTensor(),    # 转换成 PIL.Image or numpy.ndarray
                                        # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
    download=DOWNLOAD_MNIST,            # 下载数据
)

# plot one example
print(train_data.data.size())     # (60000, 28, 28)
print(train_data.targets.size())   # (60000)
plt.imshow(train_data.data[0].numpy(), cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()

# Data Loader for easy mini-batch return in training
train_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

# 验证有没有学好convert test data into Variable, pick 2000 samples to speed up testing
test_data = dsets.MNIST(root='./mnist/', train=False, transform=transforms.ToTensor())
test_x = test_data.data.type(torch.FloatTensor)[:2000]/255.   # shape (2000, 28, 28) value in range(0,1)
test_y = test_data.targets.numpy()[:2000]    # covert to numpy array

class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.LSTM(         #用nn.RNN()准确率很低,LSTM=Long Short Term Memory networks
            input_size=INPUT_SIZE,
            hidden_size=64,         # rnn hidden unit
            num_layers=1,           # number of rnn layer
            batch_first=True,       # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
            #(如果time_step,batch, time_step, input_size)等batch不在第一个维度,batch_first=False
        )

        self.out = nn.Linear(64, 10)

    def forward(self, x):
        # x shape (batch, time_step, input_size)
        # r_out shape (batch, time_step, output_size)
        # h_n shape (n_layers, batch, hidden_size)
        # h_c shape (n_layers, batch, hidden_size)
        r_out, (h_n, h_c) = self.rnn(x, None)   # None represents zero initial hidden state
        #(h_n, h_c)分别为分线程、主线程hidden state
        # choose r_out at the last time step
        out = self.out(r_out[:, -1, :])
        return out


rnn = RNN()
print(rnn)

结果

RNN(
  (rnn): LSTM(28, 64, batch_first=True)
  (out): Linear(in_features=64, out_features=10, bias=True)
)

Process finished with exit code 0

3.rnn运行精度

代码

import torch
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt


# torch.manual_seed(1)    # reproducible

# Hyper Parameters
EPOCH = 1               # 训练整批数据多少次train the training data n times, to save time, we just train 1 epoch
BATCH_SIZE = 64         # 批训练的数据个数
TIME_STEP = 28          # 图像高度 rnn time step / image height
INPUT_SIZE = 28         # 图像宽度 rnn input size / image width
LR = 0.01               # learning rate学习效率
DOWNLOAD_MNIST = False   # True = 下载文件,此处已下载用False


# Mnist digital dataset
train_data = dsets.MNIST(
    root='./mnist/',                    # 保存位置
    train=True,                         # 训练数据;
    transform=transforms.ToTensor(),    # 转换成 PIL.Image or numpy.ndarray
                                        # torch.FloatTensor of shape (C x H x W) and normalize in the range [0.0, 1.0]
    download=DOWNLOAD_MNIST,            # 下载数据
)

# plot one example
print(train_data.data.size())     # (60000, 28, 28)
print(train_data.targets.size())   # (60000)
plt.imshow(train_data.data[0].numpy(), cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()

# Data Loader for easy mini-batch return in training
train_loader = torch.utils.data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

# 验证有没有学好convert test data into Variable, pick 2000 samples to speed up testing
test_data = dsets.MNIST(root='./mnist/', train=False, transform=transforms.ToTensor())
test_x = test_data.data.type(torch.FloatTensor)[:2000]/255.   # shape (2000, 28, 28) value in range(0,1)
test_y = test_data.targets.numpy()[:2000]    # covert to numpy array

class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.LSTM(         #用 nn.RNN()准确率很低,LSTM=Long Short Term Memory networks
            input_size=INPUT_SIZE,
            hidden_size=64,         # rnn hidden unit
            num_layers=1,           # number of rnn layer
            batch_first=True,       # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
            #(如果time_step,batch, time_step, input_size)等batch不在第一个维度,batch_first=False
        )

        self.out = nn.Linear(64, 10)

    def forward(self, x):
        # x shape (batch, time_step, input_size)
        # r_out shape (batch, time_step, output_size)
        # h_n shape (n_layers, batch, hidden_size)
        # h_c shape (n_layers, batch, hidden_size)
        r_out, (h_n, h_c) = self.rnn(x, None)   # None represents zero initial hidden state
        #(h_n, h_c)分别为分线程、主线程hidden state
        # choose r_out at the last time step
        out = self.out(r_out[:, -1, :])#最后一个时间点r_out输出、r_out[:, -1, :]的值也是h_n的值
        return out


rnn = RNN()
print(rnn)

#训练模型啦~~~~

optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)   # 优化 cnn 参数
loss_func = nn.CrossEntropyLoss()                       # 交叉熵误差target 不是one-hotted 000100,而是7之类

# training and testing
for epoch in range(EPOCH):
    for step, (b_x, b_y) in enumerate(train_loader):        # batch data
        b_x = b_x.view(-1, 28, 28)              # reshape x to (batch, time_step, input_size)

        output = rnn(b_x)                               # rnn output
        loss = loss_func(output, b_y)                   # cross entropy loss
        optimizer.zero_grad()                           # clear gradients for this training step
        loss.backward()                                 # backpropagation, compute gradients
        optimizer.step()                                # apply gradients

        if step % 50 == 0:
            test_output = rnn(test_x)                   # (samples, time_step, input_size)
            pred_y = torch.max(test_output, 1)[1].data.numpy()
            accuracy = float((pred_y == test_y).astype(int).sum()) / float(test_y.size)
            print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)

# print 10 predictions from test data
test_output = rnn(test_x[:10].view(-1, 28, 28))
pred_y = torch.max(test_output, 1)[1].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:10], 'real number')

运行结果

torch.Size([60000, 28, 28])
torch.Size([60000])
RNN(
  (rnn): LSTM(28, 64, batch_first=True)
  (out): Linear(in_features=64, out_features=10, bias=True)
)
Epoch:  0 | train loss: 2.3125 | test accuracy: 0.10
Epoch:  0 | train loss: 1.2878 | test accuracy: 0.57
Epoch:  0 | train loss: 0.9112 | test accuracy: 0.64
Epoch:  0 | train loss: 0.5646 | test accuracy: 0.72
Epoch:  0 | train loss: 0.6127 | test accuracy: 0.80
Epoch:  0 | train loss: 0.3279 | test accuracy: 0.86
Epoch:  0 | train loss: 0.2661 | test accuracy: 0.86
Epoch:  0 | train loss: 0.2428 | test accuracy: 0.88
Epoch:  0 | train loss: 0.1184 | test accuracy: 0.91
Epoch:  0 | train loss: 0.2252 | test accuracy: 0.93
Epoch:  0 | train loss: 0.1278 | test accuracy: 0.93
Epoch:  0 | train loss: 0.0602 | test accuracy: 0.92
Epoch:  0 | train loss: 0.2122 | test accuracy: 0.94
Epoch:  0 | train loss: 0.0953 | test accuracy: 0.95
Epoch:  0 | train loss: 0.2775 | test accuracy: 0.92
Epoch:  0 | train loss: 0.4711 | test accuracy: 0.94
Epoch:  0 | train loss: 0.1225 | test accuracy: 0.95
Epoch:  0 | train loss: 0.1586 | test accuracy: 0.94
Epoch:  0 | train loss: 0.1500 | test accuracy: 0.93
[7 2 1 0 4 1 4 9 5 9] prediction number
[7 2 1 0 4 1 4 9 5 9] real number

Process finished with exit code 0

 

你可能感兴趣的:(pytorch小白笔记,深度学习)