pytorch学习教程(三)逻辑回归

本文介绍了如何使用pytorch实现逻辑回归,这里采用MNIST数据集实现,可以对比逻辑回归和线性回归的区别

步骤:

导入必要的包

1
2
3
4
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

超参数设置

1
2
3
4
5
6
# hyper-parameters
input_size = 784
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001

数据集加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# MNIST dataset (image 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())
# 数据加载器(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)

创建逻辑回归模型,loss和优化器

1
2
3
4
5
6
model = nn.Linear(input_size, num_class)

# Loss and optimizer
# nn.CrossEntropyLoss() computes softmax internally
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

训练模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)

# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)

# 反向传播和优化
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()))

关于:enumerate的使用

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

测试模型

1
2
3
4
5
6
7
8
9
10
11
12
# 在测试阶段,我们不需要计算梯度(为了计算效率)
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))

保存模型

1
torch.save(model.state_dict(), 'model.ckpt')

https://github.com/yunjey/pytorch-tutorial/tree/master/tutorials/01-basics/logistic_regression

Contents
|