pytorch中的前项计算和反向传播
前项计算1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import torch # (3*(x+2)^2)/4 #grad_fn 保留计算的过程 x = torch.ones([ 2 , 2 ],requires_grad = True ) print (x) y = x + 2 print (y) z = 3 * y. pow ( 2 ) print (z) out = z.mean() print (out) #带有反向传播属性的tensor不能直接转化为numpy格式,需要先进性detach操作 print (x.detach().numpy()) print (x.numpy())<br><br> |
Traceback (most recent call last):
File "C:/Users/liuxinyu/Desktop/pytorch_test/day2/前向计算.py", line 17, in <module>
print(x.numpy())
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
tensor([[1., 1.],
[1., 1.]], requires_grad=True)
tensor([[3., 3.],
[3., 3.]], grad_fn=<AddBackward0>)
tensor([[27., 27.],
[27., 27.]], grad_fn=<MulBackward0>)
tensor(27., grad_fn=<MeanBackward0>)
[[1. 1.]
[1. 1.]]
前向计算2
1 2 3 4 5 6 7 8 9 10 11 12 13 | import torch a = torch.randn( 2 , 2 ) a = ((a * 3 ) / (a - 1 )) print (a.requires_grad) a.requires_grad_( True ) #就地修改 print (a.requires_grad) b = (a * a). sum () print (b.grad_fn) with torch.no_grad(): c = (a * a). sum () print (c.requires_grad)<br><br> |
False
True
<SumBackward0 object at 0x000000000249D550>
False
反向传播
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 | import torch # (3*(x+2)^2)/4 #grad_fn 保留计算的过程 x = torch.ones([ 2 , 2 ],requires_grad = True ) print (x) y = x + 2 print (y) z = 3 * y. pow ( 2 ) print (z) out = z.mean() print (out) out.backward() print (x.grad) tensor([[ 1. , 1. ], [ 1. , 1. ]], requires_grad = True ) tensor([[ 3. , 3. ], [ 3. , 3. ]], grad_fn = <AddBackward0>) tensor([[ 27. , 27. ], [ 27. , 27. ]], grad_fn = <MulBackward0>) tensor( 27. , grad_fn = <MeanBackward0>) tensor([[ 4.5000 , 4.5000 ], [ 4.5000 , 4.5000 ]]) |
多思考也是一种努力,做出正确的分析和选择,因为我们的时间和精力都有限,所以把时间花在更有价值的地方。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 用 C# 插值字符串处理器写一个 sscanf
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!