1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| #更新 w=w-$w
import torch import numpy as np from matplotlib import pyplot as plt x=torch.ones(2,2,requires_grad=True) #不设置x的值,默认为None print(x) y=x+2 print(y) z=y*y*3 print(z) out=z.mean() #均值 print(out) #综上,若x的属性requires_grad=True,每次计算都修改grad_fn属性,用来记录做过的操作 a=torch.randn(2,2) a.requires_grad_(True) #实现就地修改
with torch.no_grad(): c=(a*a).sum() #此时在打印发现c没有gard_fn
out.backward() #计算梯度 print(x.grad) #获取x的梯度 print(x.data) #仅仅获取数据 x.detach().numpy() #如果requires_grad=True是不能转换的,要用该方法脱离
########################################################################################################## #手动实现线性回归 假设模型是y=wx+b 使用y=3x+0.8 x1=torch.rand([500,1]) y_true=3*x1+0.8 learning_rate=0.01 w=torch.rand([1,1],requires_grad=True) b=torch.rand(1,requires_grad=True,dtype=torch.float32)
for i in range(200000000): #循环,反向传播更新参数 y_predict = torch.matmul(x1, w) + b loss=(y_predict-y_true).pow(2).mean() #反向传播前把梯度质为0 if w.grad is not None: w.grad.data.zero_() if b.grad is not None: b.grad.data.zero_() loss.backward() w.data = w.data - learning_rate*w.grad b.data = w.data - learning_rate*b.grad print("w,b,loss",w.item(),b.item(),loss.item())
plt.figure(figsize=(20,8))#华图演练 plt.scatter(x1.numpy().reshape(-1),y_true.numpy().reshape(-1)) y_predict=torch.matmul(x1,w)+b plt.plot(x1.numpy().reshape(-1),y_predict.detach().numpy().reshape(-1)) #plt.show() #更快实现nn.model方法 from torch import nn class Lr(nn.Module): def __init__(self): super(Lr,self).__init__()#继承父类init参数 self.linear=nn.Linear(1,1)#nn.Linear是torch预定好的线性模型
def forward(self,x): out1=self.linear(x) return out
#优化器(optimizer) optimizer=optim.SGD(model.parameters(D))
|
评论区
欢迎你留下宝贵的意见,昵称输入QQ号会显示QQ头像哦~