首先构造一个人造数据集 我们知道真实的w和b 例如w = 【2,-3.4】,b=4.2
y = Xw + b +e
def synthetic_data(w, b, num_examples): #@save """生成y=Xw+b+噪声""" 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))
torch.normal函数(均值,方差,(样本大小,列数)【shape】)
torch.matmul即两个张量的矩阵乘积
最后加入噪音
X,y都做成列向量返回
然后定义真实w 和b
传入上述函数 来生成feature 和label
true_w = torch.tensor([2, -3.4]) true_b = 4.2 features, labels = synthetic_data(true_w, true_b, 1000)
然后我们可以画图来观察一下这个数据 这里用到
plt.scatter(x, y, s, c, marker, cmap, norm, alpha, linewidths, edgecolorsl) 函数
- x: x轴数据
- y: y轴数据
- s: 散点大小
- c: 散点颜色
- marker: 散点形状
- cmap: 指定特定颜色图,该参数一般不用,有默认值
- alpha: 散点的透明度
- linewidths: 散点边框的宽度
- edgecolors: 设置散点边框的颜色
下面我们需要实现一个函数来每次读取一个小批量
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 批量大小 所有的feature label
生成样本数量
生成样本index
打乱下标
从0-num 每次跳batchsize大小
每次取batchsieze大小样本 如果越界 那么取边界
yield是返回 这些数据
初始化w,b
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
建立模型
matumul函数 矩阵乘法
def linreg(X, w, b): #@save
"""线性回归模型"""
return torch.matmul(X, w) + b
loss function
def squared_loss(y_hat, y): #@save
"""均方损失"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
sgd
def sgd(params, lr, batch_size): #@save
"""小批量随机梯度下降"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
主函数
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}')
epoch 扫数据的次数
每次拿出一个批量大小的x,y
然后对loss 求和算梯度 再用sgd更新梯度
简洁实现
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))
nn中的linear层 (shape) Sequnential 相当于一个存放层的list
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
0访问层 weitht (w) normal 使用正太分布替换data
bias 偏差
手动实现w和b
loss = nn.MSELoss()
方差
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
sgd (参数(w,b),学习率)
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}')
注意清零梯度 在调用step来进行模型更新