本质就是三步:处理数据,构建模型,训练参数
import torch
import matplotlib.pyplot as plt #画图
import random
def create_data(w,b,data_num): #生成数据
x=torch.normal(0,1,(data_num,len(w))) #(data_num, len(w)) 是生成张量的形状,其中 data_num是数据点的数量,len(w)是每个数据点的特征数量。
y=torch.matmul(x,w)+b #matmul表示矩阵相乘
noise=torch.normal(0,0.01,y.shape) #噪声加到y上
y+=noise
return x,y
num=500 #数据数量
true_w=torch.tensor([8.1,2,2,4]) #权重
true_b=torch.tensor(1.1) #偏置
X,Y=create_data(true_w,true_b,num) #生成数据
# plt.scatter(X[:,0],Y,1)
# plt.show()
def data_provider(data,label,batchsize): #每次访问这个函数,就能提供一堆数据
length=len(label)
indices=list(range(length)) #数据下标
random.shuffle(indices) #我不能按顺序取数据 要把数据打乱
for each in range(0,length,batchsize):#data:数据集,通常是一个列表或数组.label:对应的标签,通常也是一个列表或数组.batch_size:每个批次的数据量
get_indices=indices[each:each+batchsize] #按批次获取数据
get_data=data[get_indices]
get_label=label[get_indices]
yield get_data,get_label #存档点的return
batchsize = 16 #每批数据处理的数量
# for batch_x,batch_y in data_probider(X,Y,batchsize):
# print(batch_x,batch_y)
# break
def fun(x,w,b): #定义一个模型
pred_y=torch.matmul(x,w)+b
return pred_y
def maeloss(pre_y,y): #损失函数
return torch.sum(abs(pre_y-y))
def sgd(paras,lr): #梯度下降,paras模型参数的列表
with torch.no_grad(): #属于这句代码的部分,不计算.梯度上下文管理器来禁用梯度计算。这是因为参数更新不需要梯度计算,这样做可以提高效率并避免不必要的计算。
for para in paras:
para -= para.grad*lr #更新参数
para.grad.zero_() #使用过的梯度,归0.以便在下一次前向传播和反向传播时重新计算梯度。
lr=0.03 #学习率,控制参数更新的步长
w_0=torch.normal(0,0.01,true_w.shape,requires_grad=True) #requires_grad=True 是一个非常重要的属性,因为它告诉 PyTorch 这个张量是一个可训练的参数。
# 当你在模型中使用这个张量时,PyTorch 会自动计算其梯度,并在优化过程中更新其值
b_0=torch.tensor(0.01,requires_grad=True)
print(w_0,b_0)
epochs=100 #训练的轮数
for epoch in range(epochs): #训练参数
data_loss=0 #数据损失
for batch_x,batch_y in data_provider(X,Y,batchsize):
pred_y=fun(batch_x,w_0,b_0) #算出来的y
loss=maeloss(pred_y,batch_y) #损失
loss.backward() #用于执行反向传播算法
sgd([w_0, b_0], lr)
data_loss += loss #损失累计
print("epoch %03d: loss: %.6f"%(epoch,data_loss)) #输出每轮损失
print("真实的函数值是",true_w,true_b)
print("训练得到的参数值是",w_0,b_0)
idx = 0 #代表第一列
plt.plot(X[:, idx].detach().numpy(), X[:, idx].detach().numpy()*w_0[idx].detach().numpy()+b_0.detach().numpy()) # 要保证维度相同
plt.scatter(X[:, idx], Y, 1)
plt.show()