#线性回归
import matplotlib.pyplot as plt
import random
import torch
from d2l import torch as d2l
#根据带有噪声的线性模型构造一个人造数据集
#线性模型参数w=[2,-3.4]T b=4.2和噪声项空生成数据集及其标签
def synthetic_data(w,b,num_examples):
#生成 y=xw+b+噪声
#torch.normal(means,std,out=None)
# 均值为0 方差为1的随机数 有num_examples个样本 列数是w的长度
x = torch.normal(0,1,(num_examples,len(w)))
#y = x*w + b(偏差)
y = torch.matmul(x,w) + b
#加上一个均值为0 方差为0.01的随机噪音,形状就是y的形状
y += torch.normal(0,0.01,y.shape)
#reshape中-1表示自动计算 1表示固定 即列向量为1
return x,y.reshape((-1,1))#将x和y做成列向量返回
true_w = torch.tensor([2,-3.4])
true_b = 4.2
features,labels = synthetic_data(true_w,true_b,1000)
#label是真实数据,features是预测的因子
#print('features:',features[0],'\nlabel:',labels[0])
#d2l.set_figsize()
#detach()分离出数值,不再有梯度
#d2l.plt.scatter(features[:,1].detach().numpy(),labels.numpy(),1)
#plt.show()
#定义data_iter函数 该函数接收批量大小,特征矩阵和标签向量作为输入,
# 生成大小为batch_size的小批量
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就是返回一个值 并记住这个返回的位置 下次迭代从这个位置后开始
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
w = torch.normal(0,0.01,size=(2,1),requires_grad=True)
b = torch.zeros(1,requires_grad=True)
def linreg(x,w,b):
#线性回归模型
return torch.matmul(x,w)+b
def squared_loss(y_hat,y):#y_hat是预测值 y是真实值
#均方损失
return (y_hat-y.reshape(y_hat.shape))**2 / 2
#定义优化算法
def sgd(params,lr,batch_size):
#小批量随机梯度下降
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
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.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}')