如何使用pytorch建立逻辑回归模型

-- coding:utf-8 --

import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable

模型参数

单个图像大小28*28=784

input_size = 784

输出维度

num_classes = 10

训练轮数

num_epochs = 10

加载批训练数据个数

batch_size = 50

学习率

learning_rate = 0.001

训练集(数据集如果已经下载了,就不会在运行时下载,root参数指向的是数据集目录)

train_dataset = dsets.MNIST(root=’./data’, train=True, transform=transforms.ToTensor(),
download=True)

测试集

test_dataset = dsets.MNIST(root=’./data’, train=False, transform=transforms.ToTensor())

数据加载

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)

定义逻辑回归模型

class LogisticRegression(nn.Module):
def init(self, input_size, num_classes):
super(LogisticRegression, self).init()
self.linear = nn.Linear(input_size, num_classes)

def forward(self, x):
    out = self.linear(x)
    return out

model = LogisticRegression(input_size, num_classes)

定义交叉熵损失函数

criterion = nn.CrossEntropyLoss()

定义参数优化器

optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

模型训练

for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = Variable(images.view(-1, 28*28))
labels = Variable(labels)
# 梯度归零
optimizer.zero_grad()
# 向前运算
outputs = model(images)
# 损失计算
loss = criterion(outputs, labels)
# 向后运算
loss.backward()
# 参数优化更新
optimizer.step()
if (i+1) % 100 == 0:
print(‘Epoch: [%d/%d], Step: [%d/%d], Loss: %.4f’
% (epoch+1, num_epochs, i+1, len(train_dataset)//batch_size, loss.item()))

测试模型

correct = 0
total = 0
for images, labels in test_loader:
images = Variable(images.view(-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: %d %%’ % (100 * correct / total))

模型保存

torch.save(model.state_dict(), ‘model.pkl’)如何使用pytorch建立逻辑回归模型_第1张图片

你可能感兴趣的:(python,深度学习,pytorch)