当前位置:网站首页>【简易笔记】PyTorch官方教程简易笔记 EP3
【简易笔记】PyTorch官方教程简易笔记 EP3
2022-08-10 05:34:00 【Mioulo】
已完结…
记录PyTorch 官方入门教程中的大部分代码和对代码的解释注释
暂时内容包括:自动求梯度工具
参考网站:https://pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html
自动梯度工具
import torch
x = torch.ones(5) # input tensor
y = torch.zeros(3) # expected output
w = torch.randn(5, 3, requires_grad=True)
b = torch.randn(3, requires_grad=True)
z = torch.matmul(x, w)+b
loss = torch.nn.functional.binary_cross_entropy_with_logits(z, y)
print(f"Gradient function for z = {
z.grad_fn}")
print(f"Gradient function for loss = {
loss.grad_fn}")
这一段是手打的线性分类器
比较重要的是 torch.nn.functional.binary_cross_entropy_with_logits这个函数
cross-entropy意为交叉熵,通过这个函数实现对交叉熵的快速计算
下面链接有这个函数参数的介绍
函数参考:torch.nn.functional.binary_cross_entropy_with_logits
交叉熵
loss.backward()
print(w.grad)
print(b.grad)
这个tensor.backward即为反向传递,在设置传递requires_grad=true后,所有的梯度会进行自动计算然后存在.grad属性中
函数参考:tensor.backward
z = torch.matmul(x, w)+b
print(z.requires_grad)
with torch.no_grad():
z = torch.matmul(x, w)+b
print(z.requires_grad)
#或者可以这样
#z = torch.matmul(x, w)+b
#z_det = z.detach()
#print(z_det.requires_grad)
默认时是可以反向传递求出梯度的,但是可以用下面的方法设置不让其反向传递,此时无法用.grad求出梯度
边栏推荐
猜你喜欢
随机推荐
先人一步,不再错过,链读APP即将上线!
Four characteristics of ACID
Day1 微信小程序-小程序代码的构成
Operation table Function usage
21天挑战杯MySQL——Day06
[List Exercise] Traverse the collection and sort by price from low to high,
力扣——情侣牵手
Set Sources Resources and other folders in the IDEA project
LeetCode 1894.找到需要补充粉笔的学生编号
Exploratory Data Analysis EDA
常用类 BigDecimal
Copy large files with crontab
Decentralized and p2p networks and traditional communications with centralization at the core
MySql constraints
微信小程序-小程序的宿主环境
ORACLE system table space SYSTEM is full and cannot expand table space problem solving process
优先队列
Pytorch配置与实战--Tips
测一测异性的你长什么样?
Notes 1