python - 如何根据pytorch中另一个张量的值将某个张量的值更改为零?
问题描述
我有两个张量:张量 a 和张量 b。如何根据张量 b 的值更改张量 a 的某些值?
我知道下面的代码是正确的,但是当张量很大时它运行得非常慢。还有其他方法吗?
import torch
a = torch.rand(10).cuda()
b = torch.rand(10).cuda()
a[b > 0.5] = 0.
解决方案
我想torch.where
我在 CPU 中测量的结果会更快。
import torch
a = torch.rand(3**10)
b = torch.rand(3**10)
%timeit a[b > 0.5] = 0.
852 µs ± 30.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit temp = torch.where(b > 0.5, torch.tensor(0.), a)
294 µs ± 4.51 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
推荐阅读
- video - 在整页js滚动上向前和向后播放视频
- node.js - GraphQL 关系
- java - 从终端 ClassNotFoundException 手动编译 Java
- pandas-groupby - 创建一个图表,按不同年龄显示平均医疗费用
- tsql - 使用 SET NOEXEC ON 时抑制数据库错误消息
- c++ - auto 和 __auto_type 之间有什么区别吗?
- android - 在 Android 库中隐藏未使用的公共方法
- r - 如何在 R 中重新分类数据集的值和聚合行?
- .htaccess - Htaccess 标头设置为 301 而不是 200
- r - 如何用泊松分布估计[和绘制]最大似然?