点此进入CSDN

点此添加QQ好友 加载失败时会显示




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]])

 

  

 

posted @   高颜值的殺生丸  阅读(517)  评论(0编辑  收藏  举报
编辑推荐:
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 用 C# 插值字符串处理器写一个 sscanf
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!

作者信息

昵称:

刘新宇

园龄:4年6个月


粉丝:1209


QQ:522414928

点击右上角即可分享
微信分享提示