不适用任何深度学习框架,从零开始实现
构造人造数据集,知道真是的w和b
Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.22.0 -- An enhanced Interactive Python. Type '?' for help.
PyDev console: using IPython 7.22.0
Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] on win32
import random
import torch
from d2l import torch as d2l
Backend Qt5Agg is interactive backend. Turning interactive mode on.
import matplotlib.pyplot as plt
def synthetic_data(w, b, num_examples): #@save
"""均值为0,方差为1的随机数,大小是有num_examples多个样本,列数就是w的长度,也就是2"""
X = torch.normal(0, 1, (num_examples, len(w)))
"""生成 y = Xw + b + 噪声。"""
y = torch.matmul(X, w) + b
"""噪声"""
y += torch.normal(0, 0.01, y.shape)
"""把X和y做成列向量返回"""
return X, y.reshape((-1, 1))
"""赋值""
true_w = torch.tensor([2, -3.4])
true_w
Out[6]: tensor([ 2.0000, -3.4000])
true_b = 4.2
"""通过synthetic_data函数生成特征和标注"""
features, labels = synthetic_data(true_w, true_b, 1000)
"""打印一下第0个样本"""
print('features:', features[0],'\nlabel:', labels[0])
features: tensor([-0.4704, -2.3883])
label: tensor([11.3724])
"""画一下"""
d2l.set_figsize()
"""第一列和标签"""
d2l.plt.scatter(features[:, (1)].detach().numpy(), labels.detach().numpy(), 1);
通过生成第二个特征features[:, 1]
和labels
的散点图,可以直观地观察到两者之间的线性关系。
通过生成第一个特征features[:, 0]
和labels
的散点图,可以直观地观察到两者之间的线性关系。
2.读取数据集
在下面的代码中,我们定义一个data_iter
函数, 该函数接收批量大小、特征矩阵和标签向量作为输入,生成大小为batch_size
的小批量。每个小批量包含一组特征和标签。
def data_iter(batch_size, features, labels):
num_examples = len(features)
"""range表示从0提取到n-1,转成一个python的list"""
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 = 10
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
break
tensor([[-2.0444, 1.6804],
[-0.4173, 0.8380],
[ 1.4527, 0.5612],
[-1.1547, -1.1436],
[ 0.8584, 0.8789],
[ 0.4900, -1.1409],
[-0.9469, 0.7039],
[ 0.2019, 1.6009],
[-2.0083, 0.2322],
[ 0.6607, 0.6002]])
tensor([[-5.6159],
[ 0.5026],
[ 5.1867],
[ 5.7713],
[ 2.9272],
[ 9.0665],
[-0.0978],
[-0.8188],
[-0.6000],
[ 3.4800]])
3.初始化模型参数
"""随机正态分布,返回一个梯度"""
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
4.定义模型
def linreg(X, w, b): #@save
"""线性回归模型。"""
return torch.matmul(X, w) + b
5.定义损失函数
def squared_loss(y_hat, y): #@save
"""均方损失。y_hat为预测值,y为真实值,二者个数应该是一样的,但是吧y改成y_hat的样子,没有做均值。直接加起来了,求和部分在主函数里"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
6.定义优化算法
def sgd(params, lr, batch_size): #@save
"""params给定的list,小批量随机梯度下降。"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size#上面没有求均值,在这里求均值
param.grad.zero_()#梯度设为0,与上次无关
7.训练
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) # 使用参数的梯度更新参sgd数
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
w的估计误差: tensor([ 0.0006, -0.0010], grad_fn=<SubBackward0>)
b的估计误差: tensor([0.0006], grad_fn=<RsubBackward1>)