pytorch的双向循环神经网络

 

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


# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Hyper-parameters
sequence_length = 28
input_size = 28
hidden_size = 128
num_layers = 2
num_classes = 10
batch_size = 100
num_epochs = 2
learning_rate = 0.003

# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='../../data/',
                                           train=True, 
                                           transform=transforms.ToTensor(),
                                           download=True)

test_dataset = torchvision.datasets.MNIST(root='../../data/',
                                          train=False, 
                                          transform=transforms.ToTensor())

# Data loader
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)

# Bidirectional recurrent neural network (many-to-one)
class BiRNN(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(BiRNN, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True)
        self.fc = nn.Linear(hidden_size*2, num_classes)  # 2 for bidirection
    
    def forward(self, x):
        # Set initial states
        # [100, 28, 28],(2*2, batch_size, hidden_size)
        h0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device)  # 2 for bidirection
        c0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device)
        
        # Forward propagate LSTM
        # [100, 28, 28]->[100, 28, 128*2]
        out, _ = self.lstm(x, (h0, c0))  # out: tensor of shape (batch_size, seq_length, hidden_size*2)
        
        # Decode the hidden state of the last time step
        # [100, 28, 128*2], [128*2, 10], remove the second dim
        # print(out[:, -1, :].shape)  # [100, 256]
        out = self.fc(out[:, -1, :])
        # [batch_size, 10]
        return out
# a[:, -1, :]
# Out[25]:
# array([[ 4.,  1.,  1.,  1.],
#        [ 1.,  1., 44.,  1.]])
# a.shape
# Out[26]: (2, 3, 4)
# a[0,-1,1]
# Out[27]: 1.0
# a[0,-1,:]
# Out[28]: array([4., 1., 1., 1.])
# a[:,-1,:]
# Out[29]:
# array([[ 4.,  1.,  1.,  1.],
#        [ 1.,  1., 44.,  1.]])

# [100, 28, 28] input_size=28, hidden_size=128, num_layers=2, num_classes=10
model = BiRNN(input_size, hidden_size, num_layers, num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
    
# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        # [100, 28, 28]
        images = images.reshape(-1, sequence_length, input_size).to(device)
        # print(images.shape)
        labels = labels.to(device)
        
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' 
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

# Test the model
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')

Epoch [1/2], Step [100/600], Loss: 0.4161
Epoch [1/2], Step [200/600], Loss: 0.1323
Epoch [1/2], Step [300/600], Loss: 0.1572
Epoch [1/2], Step [400/600], Loss: 0.2138
Epoch [1/2], Step [500/600], Loss: 0.1405
Epoch [1/2], Step [600/600], Loss: 0.0717
Epoch [2/2], Step [100/600], Loss: 0.0246
Epoch [2/2], Step [200/600], Loss: 0.1136
Epoch [2/2], Step [300/600], Loss: 0.1119
Epoch [2/2], Step [400/600], Loss: 0.0704
Epoch [2/2], Step [500/600], Loss: 0.0214
Epoch [2/2], Step [600/600], Loss: 0.1808
Test Accuracy of the model on the 10000 test images: 98.1 %

 

 

上一篇:CSS常用颜色


下一篇:Nginx解决跨域