iT邦幫忙

2022 iThome 鐵人賽

DAY 23
0
AI & Data

【30天之新手學習筆記】PyTorch系列 第 23

Day 23-循環神經網路的分類問題

  • 分享至 

  • xImage
  •  

以PyTorch實作循環神經網路模型(分類)

  1. MNIST手寫數據載入
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)

EPOCH = 10 #訓練數據10次
BATCH_SIZE = 64
TIME_STEP = 28
INPUT_SIZE = 28
LR = 0.01 #學習率
DOWNLOAD_MNIST = True

train_data = torchvision.datasets.MNIST(
    root='./mnist/',
    train=True,
    transform=torchvision.transforms.ToTensor(),
    download=DOWNLOAD_MNIST
)
#對(50,1,28,28)進行批次訓練
train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)
test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
#測試前1000個樣本
test_x = torch.unsqueeze(test_data.test_data, dim=1).type(torch.FloatTensor)[:1000]/255.
test_y = test_data.test_labels[:1000]
  1. RNN模型(分類)
class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.LSTM(
            input_size=28,
            hidden_size=64,
            num_layers=1,
            batch_first=True,
        )

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

    def forward(self, x):
        r_out, (h_n, h_c) = self.rnn(x, None)

        out = self.out(r_out[:, -1, :])
        return out
rnn = RNN()
print(rnn)
  1. 訓練
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)
loss_func = nn.CrossEntropyLoss()

for epoch in range(EPOCH):
    for step, (x, b_y) in enumerate(train_loader):
        b_x = x.view(-1, 28, 28)

        output = rnn(b_x)
        loss = loss_func(output, b_y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
  1. 取二十個數據來驗證預測的值是否正確
test_output = rnn(test_x[:20].view(-1, 28, 28))
pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze()
print(pred_y, 'prediction number')
print(test_y[:20], 'real number')

https://ithelp.ithome.com.tw/upload/images/20221013/20152671mtCb7F4k9I.png


參考資料:


上一篇
Day 22 - 循環神經網路(RNN)的介紹
下一篇
Day 24 - 循環神經網路的迴歸問題
系列文
【30天之新手學習筆記】PyTorch30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言