1.Abstract

2.Background

3.Task

PyTorch实现Logistic regression 1.PyTorch基础实现代码 2.用PyTorch类实现Logistic regression,torch.nn.module写网络结构

4.Work

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

# Hyper-parameters 
input_size = 784
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001

# MNIST dataset (images and labels)
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 (input pipeline)
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)

# Logistic regression model
model = nn.Linear(input_size, num_classes)

# Loss and optimizer
# nn.CrossEntropyLoss() computes softmax internally
criterion = nn.CrossEntropyLoss()  
optimizer = torch.optim.SGD(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):
        # Reshape images to (batch_size, input_size)
        images = images.reshape(-1, 28*28)
        
        # 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
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 28*28)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum()

    print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))
 

执行结果为:

Epoch [1/5], Step [100/600], Loss: 2.1976
Epoch [1/5], Step [200/600], Loss: 2.0826
Epoch [1/5], Step [300/600], Loss: 1.9902
Epoch [1/5], Step [400/600], Loss: 1.9301
Epoch [1/5], Step [500/600], Loss: 1.8415
Epoch [1/5], Step [600/600], Loss: 1.7816
Epoch [2/5], Step [100/600], Loss: 1.8129
Epoch [2/5], Step [200/600], Loss: 1.6383
Epoch [2/5], Step [300/600], Loss: 1.6415
Epoch [2/5], Step [400/600], Loss: 1.5879
Epoch [2/5], Step [500/600], Loss: 1.4823
Epoch [2/5], Step [600/600], Loss: 1.4792
Epoch [3/5], Step [100/600], Loss: 1.3526
Epoch [3/5], Step [200/600], Loss: 1.3466
Epoch [3/5], Step [300/600], Loss: 1.4207
Epoch [3/5], Step [400/600], Loss: 1.3898
Epoch [3/5], Step [500/600], Loss: 1.2873
Epoch [3/5], Step [600/600], Loss: 1.2161
Epoch [4/5], Step [100/600], Loss: 1.1674
Epoch [4/5], Step [200/600], Loss: 1.1537
Epoch [4/5], Step [300/600], Loss: 1.1710
Epoch [4/5], Step [400/600], Loss: 1.1549
Epoch [4/5], Step [500/600], Loss: 1.0865
Epoch [4/5], Step [600/600], Loss: 1.0440
Epoch [5/5], Step [100/600], Loss: 1.1113
Epoch [5/5], Step [200/600], Loss: 1.0440
Epoch [5/5], Step [300/600], Loss: 1.0347
Epoch [5/5], Step [400/600], Loss: 0.9653
Epoch [5/5], Step [500/600], Loss: 1.0128
Epoch [5/5], Step [600/600], Loss: 1.0965
Accuracy of the model on the 10000 test images: 82 %