#定义测试数据
x = torch.randn((1000,1))*100
y = x*50+1230
y_ = y + torch.normal(10000,3000,size= (1000,1)) #加入噪音
#定义损失函数:
def MSE_loss(y_,y):
MSE = torch.sum(torch.square(y-y_))/y.size()[0]
loss = MSE
return loss
#定义网络及迭代方式
def Linear_Net(x,y,lr,epochs):
#导入必备库:
import torch
import torch.nn as nn
#提取size:
input_size = x.size()[0]
input_features = x.size()[1]
#初始化参数:
w = torch.rand((input_features,1),requires_grad=True)
b = torch.rand((1,1),requires_grad=True)
loss_ = []
#计算及迭代:
for i in range(epochs):
y_ = torch.mm(x,w)+b
loss = MSE_loss(y_,y)
loss.backward()
for param in [w,b]:
param.data -= -lr* param.grad
#梯度清零,否则梯度累加
w.grad.data.zero_()
b.grad.data.zero_()
loss_.append(loss.item())
#查看每次w,b运行情况
print(w)
print(b)
#导出结果:
print("w============>>>>>>",w)
print("b============>>>>>>",b)
结果不知道为什么,好差,不收敛: