深度学习笔记

为了互导的论文,开始学深度学习了。

pytorch的使用

torch.normal

  • 作用:生成一个正态分布的张量

  • torch.normal(mean, std, size)

    三个参数分别为均值,标准差和size

    1
    2
    3
    4
    >>> torch.normal(3, 0.1, (3, 4))
    tensor([[2.9425, 3.1877, 2.9735, 3.0982],
    [3.0061, 2.9918, 2.7953, 3.0066],
    [2.8219, 2.9578, 2.8813, 2.9014]])
  • torch.normal(mean, stds)

    两个参数分别为:均值和标准差,使用标准差来确定范围size

    1
    2
    3
    4
    >>> torch.normal(3, torch.ones(3, 4)/10)
    tensor([[2.8491, 3.0263, 3.0888, 3.0818],
    [3.1101, 2.7490, 3.1847, 3.0861],
    [2.8530, 2.8666, 2.9634, 3.1875]])

简易深度学习模型的实现(线性回归)

1. 生成正态分布的数据

1
2
3
4
5
def synthetic_data(w, b, num_examples): #@save
X = torch.normal(0, 1, (num_examples, len(w))) # 按数据规模随机生成原始数据
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape) # 加上正态分布噪声
return X, y.reshape((-1, 1))
1
2
3
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)

其中features中的每⼀⾏都包含⼀个⼆维数据样本,labels中的每⼀⾏都包含⼀维标签值(⼀个标量)

简记:feature为自变量(可能多维),lables为函数

2. 读取数据集

1
2
3
4
5
6
7
8
9
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
# 这些样本是随机读取的,没有特定的顺序
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
batch_indices = torch.tensor(
indices[i: min(i + batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]

每次随机返回至多batch_size组数据

使用示例

1
2
3
4
batch_size = 10
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
break

但这种简易的随机读取数据的方式效率不佳

3. 参数的初始化及一队定义

初始化超参数

1
2
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)

线性回归模型

1
2
3
def linreg(X, w, b): #@save
"""线性回归模型"""
return torch.matmul(X, w) + b

当我们⽤⼀个向量加⼀个标量时,标量会被加到向量的每个 分量上。

损失函数

1
2
3
def squared_loss(y_hat, y): #@save
"""均⽅损失"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2

优化算法

1
2
3
4
5
6
def sgd(params, lr, batch_size): #@save
"""⼩批量随机梯度下降"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()

3.训练

1
2
3
4
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
1
2
3
4
5
6
7
8
9
10
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y) # X和y的⼩批量损失
# 因为l形状是(batch_size,1),⽽不是⼀个标量。l中的所有元素被加到⼀起,
# 并以此计算关于[w,b]的梯度
l.sum().backward()
sgd([w, b], lr, batch_size) # 使⽤参数的梯度更新参数
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')

线性模型的简单实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l

def synthetic_data(w, b, num_examples) : #@save
X = torch.normal(0, 1, (num_examples, len(w))) # 按数据规模随机生成原始数据
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape) # 加上正态分布噪声
return X, y.reshape((-1, 1))

true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = d2l.synthetic_data(true_w, true_b, 1000)

# is_train参数表示是否每个迭代周期打乱数据
def load_array(data_arrays, batch_size, is_train=True) : #@save
"""构造⼀个PyTorch数据迭代器"""
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset, batch_size, shuffle=is_train)

"""
next(iter(data_iter))调用这个迭代器
"""

batch_size = 10
data_iter = load_array((features, labels), batch_size)

from torch import nn
# Sequential实现神经网络多层的串联
# Linear全连接层
net = nn.Sequential(nn.Linear(2, 1))

# net[0]访问第一层
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)

# 平方L2范数,即均方误差
loss = nn.MSELoss()

# 定义优化算法:小批量梯度随机下降
# lr 为学习率
trainer = torch.optim.SGD(net.parameters(), lr=0.03)

# 训练
num_epochs = 3 # 迭代周期个数
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X) ,y)
trainer.zero_grad()
l.backward()
trainer.step()
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')

w = net[0].weight.data
print('w的估计误差:', true_w - w.reshape(true_w.shape))
b = net[0].bias.data
print('b的估计误差:', true_b - b)

深度学习笔记
https://ignotusjee.github.io/2022/11/16/2022-11-16-深度学习笔记/
作者
柳苏明
发布于
2022年11月16日
许可协议