深度学习 / 55.5

用PyTorch从零构建线性回归

张量、模型与训练过程。 用PyTorch从零构建线性回归。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

Tutorial inspired from FastAI development notebooks

Machine Learning

监督学习关系: 输入特征X与观测目标Y → 选择模型和损失 → 根据训练数据调整参数 → 用独立数据评价预测,而不是直接把输入映射公式当作已知规律。

Tensors & Gradients

PYTHON · 仅供阅读
# Import Numpy & PyTorch
import numpy as np
import torch

A tensor is a number, vector, matrix or any n-dimensional array.

PYTHON · 仅供阅读
# Create tensors.
x = torch.tensor(3.)
w = torch.tensor(4., requires_grad=True)
b = torch.tensor(5., requires_grad=True)
PYTHON · 仅供阅读
# Print tensors
print(x)
print(w)
print(b)
原笔记输出 · 本次未执行
tensor(3.)
tensor(4., requires_grad=True)
tensor(5., requires_grad=True)

We can combine tensors with the usual arithmetic operations.

PYTHON · 仅供阅读
# Arithmetic operations
y = w * x + b
print(y)
原笔记输出 · 本次未执行
tensor(17., grad_fn=<AddBackward0>)

What makes PyTorch special, is that we can automatically compute the derivative of y w.r.t. the tensors that have requires_grad set to True i.e. w and b.

PYTHON · 仅供阅读
# Compute gradients
y.backward()
PYTHON · 仅供阅读
# Display gradients
print('dy/dw:', w.grad)
print('dy/db:', b.grad)
原笔记输出 · 本次未执行
dy/dw: tensor(3.)
dy/db: tensor(1.)

Problem Statement

We’ll create a model that predicts crop yeilds for apples and oranges (target variables) by looking at the average temperature, rainfall and humidity (input variables or features) in a region. Here’s the training data:

本例数据与模型: 五行输入(73,67,43),(91,88,64),(87,134,58),(102,43,37),(69,96,70)分别对应目标(56,70),(81,101),(119,133),(22,37),(103,119);三列输入为温度/降雨/湿度,两列输出为苹果/橙子产量。这是教学表,不是实际农业预测保证。每个输出是输入的仿射组合,多个输入时形成超平面。

In a linear regression model, each target variable is estimated to be a weighted sum of the input variables, offset by some constant, known as a bias :

PLAINTEXT · 仅供阅读
yeild_apple  = w11 * temp + w12 * rainfall + w13 * humidity + b1
yeild_orange = w21 * temp + w22 * rainfall + w23 * humidity + b2

Visually, it means that the yield of apples is a linear or planar function of the temperature, rainfall & humidity.

Our objective: Find a suitable set of weights and biases using the training data, to make accurate predictions.

Training Data

The training data can be represented using 2 matrices (inputs and targets), each with one row per observation and one column per variable.

PYTHON · 仅供阅读
# Input (temp, rainfall, humidity)
inputs = np.array([[73, 67, 43], 
                   [91, 88, 64], 
                   [87, 134, 58], 
                   [102, 43, 37], 
                   [69, 96, 70]], dtype='float32')
PYTHON · 仅供阅读
# Targets (apples, oranges)
targets = np.array([[56, 70], 
                    [81, 101], 
                    [119, 133], 
                    [22, 37], 
                    [103, 119]], dtype='float32')

Before we build a model, we need to convert inputs and targets to PyTorch tensors.

PYTHON · 仅供阅读
# Convert inputs and targets to tensors
inputs = torch.from_numpy(inputs)
targets = torch.from_numpy(targets)
print(inputs)
print(targets)
原笔记输出 · 本次未执行
tensor([[ 73.,  67.,  43.],
        [ 91.,  88.,  64.],
        [ 87., 134.,  58.],
        [102.,  43.,  37.],
        [ 69.,  96.,  70.]])
tensor([[ 56.,  70.],
        [ 81., 101.],
        [119., 133.],
        [ 22.,  37.],
        [103., 119.]])

Linear Regression Model (from scratch)

The weights and biases can also be represented as matrices, initialized with random values. The first row of w and the first element of b are use to predict the first target variable i.e. yield for apples, and similarly the second for oranges.

PYTHON · 仅供阅读
# Weights and biases
w = torch.randn(2, 3, requires_grad=True)
b = torch.randn(2, requires_grad=True)
print(w)
print(b)
原笔记输出 · 本次未执行
tensor([[-0.7291,  0.5011, -0.2855],
        [-0.0435, -2.6902,  0.4429]], requires_grad=True)
tensor([0.1452, 0.7294], requires_grad=True)

The model is simply a function that performs a matrix multiplication of the input x and the weights w (transposed) and adds the bias b (replicated for each observation).

X×WT+b\hspace{2.5cm} X \hspace{1.1cm} \times \hspace{1.2cm} W^T \hspace{1.2cm} + \hspace{1cm} b \hspace{2cm} [736743918864⋮⋮⋮699670]×[w11w21w12w22w13w23]+[b1b2b1b2⋮⋮b1b2]\left[ \begin{array}{ccc} 73 & 67 & 43 \\ 91 & 88 & 64 \\ \vdots & \vdots & \vdots \\ 69 & 96 & 70 \end{array} \right] % \times % \left[ \begin{array}{cc} w_{11} & w_{21} \\ w_{12} & w_{22} \\ w_{13} & w_{23} \end{array} \right] % + % \left[ \begin{array}{cc} b_{1} & b_{2} \\ b_{1} & b_{2} \\ \vdots & \vdots \\ b_{1} & b_{2} \\ \end{array} \right]
PYTHON · 仅供阅读
# Define the model
def model(x):
    return x @ w.t() + b
    # return torch.mm(x, w.t()) + b

The matrix obtained by passing the input data to the model is a set of predictions for the target variables.

PYTHON · 仅供阅读
# Generate predictions
preds = model(inputs)
print(preds)
原笔记输出 · 本次未执行
tensor([[ -31.7851, -163.6474],
        [ -40.3820, -211.6246],
        [ -12.7034, -337.8554],
        [ -63.2426, -103.0030],
        [ -22.0455, -229.5310]], grad_fn=<AddBackward0>)
PYTHON · 仅供阅读
# Compare with targets
print(targets)
原笔记输出 · 本次未执行
tensor([[ 56.,  70.],
        [ 81., 101.],
        [119., 133.],
        [ 22.,  37.],
        [103., 119.]])

Because we’ve started with random weights and biases, the model does not a very good job of predicting the target varaibles.

Loss Function

We can compare the predictions with the actual targets, using the following method:

  • Calculate the difference between the two matrices (preds and targets).
  • Square all elements of the difference matrix to remove negative values.
  • Calculate the average of the elements in the resulting matrix.

The result is a single number, known as the mean squared error (MSE).

PYTHON · 仅供阅读
# MSE loss
def mse(t1, t2):
    diff = t1 - t2
    return torch.sum(diff * diff) / diff.numel()
PYTHON · 仅供阅读
# Compute loss
loss = mse(preds, targets)
print(loss)
原笔记输出 · 本次未执行
tensor(57779.3008, grad_fn=<DivBackward0>)

The resulting number is called the loss, because it indicates how bad the model is at predicting the target variables. Lower the loss, better the model.

Compute Gradients

With PyTorch, we can automatically compute the gradient or derivative of the loss w.r.t. to the weights and biases, because they have requires_grad set to True.

PYTHON · 仅供阅读
# Compute gradients
loss.backward()

The gradients are stored in the .grad property of the respective tensors.

PYTHON · 仅供阅读
# Gradients for weights
print(w)
print(w.grad)
原笔记输出 · 本次未执行
tensor([[-0.7291,  0.5011, -0.2855],
        [-0.0435, -2.6902,  0.4429]], requires_grad=True)
tensor([[ -9247.0293,  -9976.2520,  -6217.8320],
        [-24959.6934, -29147.8125, -17388.3438]])
PYTHON · 仅供阅读
# Gradients for bias
print(b)
print(b.grad)
原笔记输出 · 本次未执行
tensor([0.1452, 0.7294], requires_grad=True)
tensor([-110.2317, -301.1323])

A key insight from calculus is that the gradient indicates the rate of change of the loss, or the slope of the loss function w.r.t. the weights and biases.

  • If a gradient element is postive,
    • increasing the element’s value slightly will increase the loss.
    • decreasing the element’s value slightly will decrease the loss.

梯度符号示意: 对可微损失,某参数偏导为正时,小幅增大该参数使损失一阶增加;偏导为负时方向相反。梯度下降总取负梯度方向,并由学习率控制幅度;曲率会限制这份局部近似的有效范围。

  • If a gradient element is negative,
    • increasing the element’s value slightly will decrease the loss.
    • decreasing the element’s value slightly will increase the loss.

The increase or decrease is proportional to the value of the gradient.

Finally, we’ll reset the gradients to zero before moving forward, because PyTorch accumulates gradients.

PYTHON · 仅供阅读
w.grad.zero_()
b.grad.zero_()
print(w.grad)
print(b.grad)
原笔记输出 · 本次未执行
tensor([[0., 0., 0.],
        [0., 0., 0.]])
tensor([0., 0.])

Adjust weights and biases using gradient descent

We’ll reduce the loss and improve our model using the gradient descent algorithm, which has the following steps:

  1. Generate predictions
  2. Calculate the loss
  3. Compute gradients w.r.t the weights and biases
  4. Adjust the weights by subtracting a small quantity proportional to the gradient
  5. Reset the gradients to zero
PYTHON · 仅供阅读
# Generate predictions
preds = model(inputs)
print(preds)
原笔记输出 · 本次未执行
tensor([[ -31.7851, -163.6474],
        [ -40.3820, -211.6246],
        [ -12.7034, -337.8554],
        [ -63.2426, -103.0030],
        [ -22.0455, -229.5310]], grad_fn=<AddBackward0>)
PYTHON · 仅供阅读
# Calculate the loss
loss = mse(preds, targets)
print(loss)
原笔记输出 · 本次未执行
tensor(57779.3008, grad_fn=<DivBackward0>)
PYTHON · 仅供阅读
# Compute gradients
loss.backward()
PYTHON · 仅供阅读
# Adjust weights & reset gradients
with torch.no_grad():
    w -= w.grad * 1e-5
    b -= b.grad * 1e-5
    w.grad.zero_()
    b.grad.zero_()
PYTHON · 仅供阅读
print(w)
原笔记输出 · 本次未执行
tensor([[-0.6367,  0.6008, -0.2233],
        [ 0.2061, -2.3987,  0.6167]], requires_grad=True)

With the new weights and biases, the model should have a lower loss.

整理注: 足够小的学习率下梯度下降通常可降低当前损失,但任意步长、随机初始值不保证每一步都下降。

PYTHON · 仅供阅读
# Calculate loss
preds = model(inputs)
loss = mse(preds, targets)
print(loss)
原笔记输出 · 本次未执行
tensor(39579.5859, grad_fn=<DivBackward0>)

Train for multiple epochs

To reduce the loss further, we repeat the process of adjusting the weights and biases using the gradients multiple times. Each iteration is called an epoch.

PYTHON · 仅供阅读
# Train for 100 epochs
for i in range(100):
    preds = model(inputs)
    loss = mse(preds, targets)
    loss.backward()
    with torch.no_grad():
        w -= w.grad * 1e-5
        b -= b.grad * 1e-5
        w.grad.zero_()
        b.grad.zero_()
PYTHON · 仅供阅读
# Calculate loss
preds = model(inputs)
loss = mse(preds, targets)
print(loss)
原笔记输出 · 本次未执行
tensor(595.5133, grad_fn=<DivBackward0>)
PYTHON · 仅供阅读
# Print predictions
preds
原笔记输出 · 本次未执行
tensor([[ 57.9261,  80.2788],
        [ 78.0996, 113.4238],
        [126.8115,  87.9272],
        [ 24.8921,  94.8474],
        [ 92.5811, 107.7223]], grad_fn=<AddBackward0>)
PYTHON · 仅供阅读
# Print targets
targets
原笔记输出 · 本次未执行
tensor([[ 56.,  70.],
        [ 81., 101.],
        [119., 133.],
        [ 22.,  37.],
        [103., 119.]])

Linear Regression Model using PyTorch built-ins

Let’s re-implement the same model using some built-in functions and classes from PyTorch.

PYTHON · 仅供阅读
# Imports
import torch.nn as nn
PYTHON · 仅供阅读
# Input (temp, rainfall, humidity)
inputs = np.array([[73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70], [73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70], [73, 67, 43], [91, 88, 64], [87, 134, 58], [102, 43, 37], [69, 96, 70]], dtype='float32')
# Targets (apples, oranges)
targets = np.array([[56, 70], [81, 101], [119, 133], [22, 37], [103, 119], 
                    [56, 70], [81, 101], [119, 133], [22, 37], [103, 119], 
                    [56, 70], [81, 101], [119, 133], [22, 37], [103, 119]], dtype='float32')
PYTHON · 仅供阅读
inputs = torch.from_numpy(inputs)
targets = torch.from_numpy(targets)

Dataset and DataLoader

We’ll create a TensorDataset, which allows access to rows from inputs and targets as tuples. We’ll also create a DataLoader, to split the data into batches while training. It also provides other utilities like shuffling and sampling.

PYTHON · 仅供阅读
# Import tensor dataset & data loader
from torch.utils.data import TensorDataset, DataLoader
PYTHON · 仅供阅读
# Define dataset
train_ds = TensorDataset(inputs, targets)
train_ds[0:3]
原笔记输出 · 本次未执行
(tensor([[ 73.,  67.,  43.],
         [ 91.,  88.,  64.],
         [ 87., 134.,  58.]]),
 tensor([[ 56.,  70.],
         [ 81., 101.],
         [119., 133.]]))
PYTHON · 仅供阅读
# Define data loader
batch_size = 5
train_dl = DataLoader(train_ds, batch_size, shuffle=True)
next(iter(train_dl))
原笔记输出 · 本次未执行
[tensor([[ 73.,  67.,  43.],
         [ 87., 134.,  58.],
         [102.,  43.,  37.],
         [102.,  43.,  37.],
         [ 73.,  67.,  43.]]),
 tensor([[ 56.,  70.],
         [119., 133.],
         [ 22.,  37.],
         [ 22.,  37.],
         [ 56.,  70.]])]

nn.Linear

Instead of initializing the weights & biases manually, we can define the model using nn.Linear.

PYTHON · 仅供阅读
# Define model
model = nn.Linear(3, 2)
print(model.weight)
print(model.bias)
原笔记输出 · 本次未执行
Parameter containing:
tensor([[-0.2848,  0.4273,  0.2880],
        [ 0.1554,  0.3343,  0.2723]], requires_grad=True)
Parameter containing:
tensor([-0.1626,  0.1232], requires_grad=True)

Optimizer

Instead of manually manipulating the weights & biases using gradients, we can use the optimizer optim.SGD.

PYTHON · 仅供阅读
# Define optimizer
opt = torch.optim.SGD(model.parameters(), lr=1e-5)

Loss Function

Instead of defining a loss function manually, we can use the built-in loss function mse_loss.

PYTHON · 仅供阅读
# Import nn.functional
import torch.nn.functional as F
PYTHON · 仅供阅读
# Define loss function
loss_fn = F.mse_loss
PYTHON · 仅供阅读
loss = loss_fn(model(inputs), targets)
print(loss)
原笔记输出 · 本次未执行
tensor(2198.9983, grad_fn=<MseLossBackward>)

Train the model

We are ready to train the model now. We can define a utility function fit which trains the model for a given number of epochs.

PYTHON · 仅供阅读
# Define a utility function to train the model
def fit(num_epochs, model, loss_fn, opt):
    for epoch in range(num_epochs):
        for xb,yb in train_dl:
            # Generate predictions
            pred = model(xb)
            loss = loss_fn(pred, yb)
            # Perform gradient descent
            loss.backward()
            opt.step()
            opt.zero_grad()
    print('Training loss: ', loss_fn(model(inputs), targets))
PYTHON · 仅供阅读
# Train the model for 100 epochs
fit(100, model, loss_fn, opt)
原笔记输出 · 本次未执行
Training loss:  tensor(13.3114, grad_fn=<MseLossBackward>)
PYTHON · 仅供阅读
# Generate predictions
preds = model(inputs)
preds
原笔记输出 · 本次未执行
tensor([[ 57.7382,  71.4844],
        [ 81.3507,  98.6836],
        [119.7566, 135.8467],
        [ 24.4143,  43.2414],
        [ 98.4513, 112.0539],
        [ 57.7382,  71.4844],
        [ 81.3507,  98.6836],
        [119.7566, 135.8467],
        [ 24.4143,  43.2414],
        [ 98.4513, 112.0539],
        [ 57.7382,  71.4844],
        [ 81.3507,  98.6836],
        [119.7566, 135.8467],
        [ 24.4143,  43.2414],
        [ 98.4513, 112.0539]], grad_fn=<AddmmBackward>)
PYTHON · 仅供阅读
# Compare with targets
targets
原笔记输出 · 本次未执行
tensor([[ 56.,  70.],
        [ 81., 101.],
        [119., 133.],
        [ 22.,  37.],
        [103., 119.],
        [ 56.,  70.],
        [ 81., 101.],
        [119., 133.],
        [ 22.,  37.],
        [103., 119.],
        [ 56.,  70.],
        [ 81., 101.],
        [119., 133.],
        [ 22.,  37.],
        [103., 119.]])

Bonus: Feedfoward Neural Network

前馈网络独立示意: 3维输入 → Linear(3,3) → ReLU → Linear(3,2) → 2维预测。没有非线性时,堆叠线性层仍等价于一个线性/仿射变换;ReLU使其能够表示分段线性关系。

Conceptually, you think of feedforward neural networks as two or more linear regression models stacked on top of one another with a non-linear activation function applied between them.

To use a feedforward neural network instead of linear regression, we can extend the nn.Module class from PyTorch.

PYTHON · 仅供阅读
class SimpleNet(nn.Module):
    # Initialize the layers
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(3, 3)
        self.act1 = nn.ReLU() # Activation function
        self.linear2 = nn.Linear(3, 2)
    
    # Perform the computation
    def forward(self, x):
        x = self.linear1(x)
        x = self.act1(x)
        x = self.linear2(x)
        return x

Now we can define the model, optimizer and loss function exactly as before.

PYTHON · 仅供阅读
model = SimpleNet()
opt = torch.optim.SGD(model.parameters(), 1e-5)
loss_fn = F.mse_loss

Finally, we can apply gradient descent to train the model using the same fit function defined earlier for linear regression.

训练闭环: 批次输入 → 网络预测 → MSE → backward → SGD.step → zero_grad,重复多个epoch。预测后仍需独立验证,不用训练loss代替泛化评估。

PYTHON · 仅供阅读
fit(100, model, loss_fn, opt)
原笔记输出 · 本次未执行
Training loss:  tensor(10.1385, grad_fn=<MseLossBackward>)

整理参考资料