Pytorch 使用tensor特定条件判断索引
作者:judgechen1997 时间:2023-01-18 16:30:23
torch.where() 用于将两个broadcastable的tensor组合成新的tensor,类似于c++中的三元操作符“?:”
区别于python numpy中的where()直接可以找到特定条件元素的index
想要实现numpy中where()的功能,可以借助nonzero()
对应numpy中的where()操作效果:
补充:Pytorch torch.Tensor.detach()方法的用法及修改指定模块权重的方法
detach
detach的中文意思是分离,官方解释是返回一个新的Tensor,从当前的计算图中分离出来
需要注意的是,返回的Tensor和原Tensor共享相同的存储空间,但是返回的 Tensor 永远不会需要梯度
import torch as t
a = t.ones(10,)
b = a.detach()
print(b)
tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
那么这个函数有什么作用?
–假如A网络输出了一个Tensor类型的变量a, a要作为输入传入到B网络中,如果我想通过损失函数反向传播修改B网络的参数,但是不想修改A网络的参数,这个时候就可以使用detcah()方法
a = A(input)
a = detach()
b = B(a)
loss = criterion(b, target)
loss.backward()
来看一个实际的例子:
import torch as t
x = t.ones(1, requires_grad=True)
x.requires_grad #True
y = t.ones(1, requires_grad=True)
y.requires_grad #True
x = x.detach() #分离之后
x.requires_grad #False
y = x+y #tensor([2.])
y.requires_grad #我还是True
y.retain_grad() #y不是叶子张量,要加上这一行
z = t.pow(y, 2)
z.backward() #反向传播
y.grad #tensor([4.])
x.grad #None
以上代码就说明了反向传播到y就结束了,没有到达x,所以x的grad属性为None
既然谈到了修改模型的权重问题,那么还有一种情况是:
–假如A网络输出了一个Tensor类型的变量a, a要作为输入传入到B网络中,如果我想通过损失函数反向传播修改A网络的参数,但是不想修改B网络的参数,这个时候又应该怎么办了?
这时可以使用Tensor.requires_grad属性,只需要将requires_grad修改为False即可.
for param in B.parameters():
param.requires_grad = False
a = A(input)
b = B(a)
loss = criterion(b, target)
loss.backward()
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/judgechen1997/article/details/105820709
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL数据库卸载的完整步骤
![](https://img.aspxhome.com/file/2023/0/76370_0s.jpg)
Python爬虫HTPP请求方法有哪些
MySQL字段类型详解
自动更新程序的设计框架
![](https://img.aspxhome.com/file/UploadPic/20098/12/1124390-80s.jpg)
Python入门教程(四十一)Python的NumPy数组索引
![](https://img.aspxhome.com/file/2023/5/135265_0s.png)
Python必备基础之闭包和装饰器知识总结
Python实战之疫苗研发情况可视化
![](https://img.aspxhome.com/file/2023/4/102924_0s.png)
SQL附加数据库失败问题的解决方法
![](https://img.aspxhome.com/file/2023/1/108491_0s.jpg)
MySQL大量脏数据如何只保留最新的一条(最新推荐)
![](https://img.aspxhome.com/file/2023/8/88498_0s.jpg)
Python 'takes exactly 1 argument (2 given)' Python error
Scrapy爬虫实例讲解_校花网
Go语言切片前或中间插入项与内置copy()函数详解
![](https://img.aspxhome.com/file/2023/6/123906_0s.png)
python随机模块random的22种函数(小结)
![](https://img.aspxhome.com/file/2023/5/76715_0s.png)
Django Form设置文本框为readonly操作
python 协程中的迭代器,生成器原理及应用实例详解
![](https://img.aspxhome.com/file/2023/2/77032_0s.png)
Python模拟登录和登录跳转的参考示例
Sql Server 2005 默认端口修改方法
网页设计三剑客
python 星号(*)的多种用途
python 给图像添加透明度(alpha通道)
![](https://img.aspxhome.com/file/2023/3/98983_0s.jpg)