在了解了Pytorch的一些机制后,当然要进行一些实例的学习,毕竟实践出真知嘛。
对于所有的机器学习爱好者来说,第一个要学的模型无疑是线性回归
所谓线性回归,指的就是用对输入数据的每个维度进行线性组合拟合Label-y。最简单的线性回归即是二维平面内的直线拟合。
为此我们可以编造一些数据:
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from torch.autograd import Variable
#toy dataset
x_train = np.linespace(1,0.1,100)
y = 3*x
y_train = [yo + np.random.uniform(0,1) for yo in y]
然后是模型的主体部分,在Pytorch中,所有的模型都要继承自nn.Module这个类(或继承自nn.Module这个类的子类)
# Hyper Parameters
input_size = 1
output_size = 1
num_epochs = 60
learning_rate = 0.001
# Linear Regression Model
class LinearRegression(nn.Module):
def __init__(self, input_size, output_size):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(input_size, output_size)
def forward(self, x):
out = self.linear(x)
return out
model = LinearRegression(input_size, output_size)
# Loss and Optimizer
criterion = nn.MSELoss() #采用最小均方误差是线性回归
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# Train the Model
for epoch in range(num_epochs):
# Convert numpy array to torch Variable
inputs = Variable(torch.from_numpy(x_train))
targets = Variable(torch.from_numpy(y_train))
# Forward + Backward + Optimize
optimizer.zero_grad()
outputs = model(inputs) #forward
loss = criterion(outputs, targets) #loss
loss.backward() #backward
optimizer.step()
if (epoch+1) % 5 == 0:
print ('Epoch [%d/%d], Loss: %.4f'
%(epoch+1, num_epochs, loss.data[0]))
# Plot the graph
predicted = model(Variable(torch.from_numpy(x_train))).data.numpy()
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, predicted, label='Fitted line')
plt.legend()
plt.show()
# Save the Model
torch.save(model.state_dict(), 'model.pkl')
逻辑回归虽然名为回归,但是其是一个分类模型,逻辑回归与线性回归一样是对数据进行线性变换,但是由于其输出时使用了Sigmoid函数,人们往往并不认为它是一个纯的线性模型。得益于Sigmoid函数,逻辑回归可以轻松地进行二分类。在处理多分类问题时,逻辑回归进化为Softmax回归,在强大的Softmax函数的帮助下(其可以将任意向量映射成概率分布),诸多多分类问题得到有效解决,例如图像识别(ImageNet)。
下面是一个用Pytorch进行Mnist手写数据集识别分类的例子,在这个例子中,没有使用CNN,直接把输入打成一个一维向量进行线性运算。
import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable
# 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 = dsets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = dsets.MNIST(root='./data',
train=False,
transform=transforms.ToTensor())
# Dataset Loader (Input Pipline)
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)
# Model
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)
# Loss and Optimizer
# Softmax is internally computed.
# Set parameters to be updated.
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
# Training the Model
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = Variable(images.view(-1, 28*28))
labels = Variable(labels) #这里labels是one_hot编码的
# Forward + Backward + Optimize
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.data[0]))
# Test the Model
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))
# Save the Model
torch.save(model.state_dict(), 'model.pkl')