import random
import torch
import matplotlib.pyplot as plt
import numpy as np
def synthetic_data(w,b,num_examples):#@save
#有@save标记的函数是以后课程也需要的函数
#num_examples是需要生成的数据量
X=torch.normal(0,1,(num_examples,len(w)))#随机生成X值
y=torch.matmul(X,w)+b#点乘
y+=torch.normal(0,0.01,y.shape)#加入噪声
return X,y.reshape(-1,1)#y原本为1D向量,需要配合X转换为2D向量
true_w=torch.tensor([2,-3.4])
true_b=4.2
features,labels=synthetic_data(true_w,true_b,1000)
print('features:', features[0],'\nlabel:', labels[0])
features: tensor([-1.6631, 0.7055])
label: tensor([-1.5150])
for i in range(features.shape[1]):
plt.figure(figsize=(4, 6))
plt.scatter(features[:,i].detach().numpy(),labels.detach().numpy(),1)
plt.show()
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]#用yield返回生成器对象
#使用yield 语句,这个函数并不会一次性返回所有数据,而是每次迭代时返回一个批次,直到遍历完所有的数据。
batch_size = 10
for X, y in data_iter(batch_size, features, labels):
print(X, '\n', y)
break
tensor([[ 0.5498, -0.6602],
[ 1.3274, 1.1237],
[-0.8969, 1.4953],
[-0.8194, -1.4068],
[-1.8279, 0.2056],
[ 0.2234, 0.7288],
[ 0.2975, 1.2387],
[ 2.7754, -0.0386],
[-0.8039, 0.2879],
[-0.3941, -1.8162]])
tensor([[ 7.5530],
[ 3.0335],
[-2.6649],
[ 7.3398],
[-0.1459],
[ 2.1679],
[ 0.5731],
[ 9.8660],
[ 1.6141],
[ 9.5823]])
#随机选择
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)##requires_grad=True代表开启了对该张量的梯度计算
b = torch.zeros(1, requires_grad=True)
def linreg(X, w, b): #@save
"""线性回归模型"""
return torch.matmul(X, w) + b
def squared_loss(y_hat, y): #@save
"""均方损失"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
def sgd(params, lr, batch_size): #@save
"""小批量随机梯度下降"""
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形状是(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}')
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
epoch 1, loss 0.030949
epoch 2, loss 0.000105
epoch 3, loss 0.000050
w的估计误差: tensor([ 4.3511e-05, -7.3910e-05], grad_fn=)
b的估计误差: tensor([0.0004], grad_fn=)
-无事发生,算法仍然有效
-可能遇到的问题:
squared_loss
函数中需要使用reshape
函数?data_iter
函数的行为会有什么变化?如果有用求个star说是:myluster的github笔记