阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
Tutorial inspired from FastAI development notebooks
Machine Learning
监督学习关系: 输入特征X与观测目标Y → 选择模型和损失 → 根据训练数据调整参数 → 用独立数据评价预测,而不是直接把输入映射公式当作已知规律。
Tensors & Gradients
# Import Numpy & PyTorch
import numpy as np
import torchA tensor is a number, vector, matrix or any n-dimensional array.
# Create tensors.
x = torch.tensor(3.)
w = torch.tensor(4., requires_grad=True)
b = torch.tensor(5., requires_grad=True)# 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.
# 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.
# Compute gradients
y.backward()# 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 :
yeild_apple = w11 * temp + w12 * rainfall + w13 * humidity + b1
yeild_orange = w21 * temp + w22 * rainfall + w23 * humidity + b2Visually, 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.
# Input (temp, rainfall, humidity)
inputs = np.array([[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]], dtype='float32')Before we build a model, we need to convert inputs and targets to PyTorch tensors.
# 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.
# 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).
# Define the model
def model(x):
return x @ w.t() + b
# return torch.mm(x, w.t()) + bThe matrix obtained by passing the input data to the model is a set of predictions for the target variables.
# 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>)
# 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 (
predsandtargets). - 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).
# MSE loss
def mse(t1, t2):
diff = t1 - t2
return torch.sum(diff * diff) / diff.numel()# 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.
# Compute gradients
loss.backward()The gradients are stored in the .grad property of the respective tensors.
# 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]])
# 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.
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:
- Generate predictions
- Calculate the loss
- Compute gradients w.r.t the weights and biases
- Adjust the weights by subtracting a small quantity proportional to the gradient
- Reset the gradients to zero
# 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>)
# Calculate the loss
loss = mse(preds, targets)
print(loss)tensor(57779.3008, grad_fn=<DivBackward0>)
# Compute gradients
loss.backward()# Adjust weights & reset gradients
with torch.no_grad():
w -= w.grad * 1e-5
b -= b.grad * 1e-5
w.grad.zero_()
b.grad.zero_()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.
整理注: 足够小的学习率下梯度下降通常可降低当前损失,但任意步长、随机初始值不保证每一步都下降。
# 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.
# 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_()# Calculate loss
preds = model(inputs)
loss = mse(preds, targets)
print(loss)tensor(595.5133, grad_fn=<DivBackward0>)
# Print predictions
predstensor([[ 57.9261, 80.2788],
[ 78.0996, 113.4238],
[126.8115, 87.9272],
[ 24.8921, 94.8474],
[ 92.5811, 107.7223]], grad_fn=<AddBackward0>)
# Print targets
targetstensor([[ 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.
# Imports
import torch.nn as nn# 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')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.
# Import tensor dataset & data loader
from torch.utils.data import TensorDataset, DataLoader# 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.]]))
# 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.
# 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.
# 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.
# Import nn.functional
import torch.nn.functional as F# Define loss function
loss_fn = F.mse_lossloss = 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.
# 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))# Train the model for 100 epochs
fit(100, model, loss_fn, opt)Training loss: tensor(13.3114, grad_fn=<MseLossBackward>)
# Generate predictions
preds = model(inputs)
predstensor([[ 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>)
# Compare with targets
targetstensor([[ 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.
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 xNow we can define the model, optimizer and loss function exactly as before.
model = SimpleNet()
opt = torch.optim.SGD(model.parameters(), 1e-5)
loss_fn = F.mse_lossFinally, 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代替泛化评估。
fit(100, model, loss_fn, opt)Training loss: tensor(10.1385, grad_fn=<MseLossBackward>)