Python 如何根据另一个张量',将一个张量的某个值变为零;pytorch的价值是多少?

Python 如何根据另一个张量',将一个张量的某个值变为零;pytorch的价值是多少?,python,pytorch,Python,Pytorch,我有两个张量:张量a和张量b。如何根据张量b的值来改变张量a的值 我知道下面的代码是对的,但当张量很大时,它运行得相当慢。还有其他方法吗 import torch a = torch.rand(10).cuda() b = torch.rand(10).cuda() a[b > 0.5] = 0. 我想,火炬。在哪里,会更快,我在CPU中进行了测量,这里是结果 import torch a = torch.rand(3**10) b = torch.rand(3**10) 对于这个确切

我有两个张量:张量a和张量b。如何根据张量b的值来改变张量a的值

我知道下面的代码是对的,但当张量很大时,它运行得相当慢。还有其他方法吗

import torch
a = torch.rand(10).cuda()
b = torch.rand(10).cuda()
a[b > 0.5] = 0.

我想,
火炬。在哪里,
会更快,我在CPU中进行了测量,这里是结果

import torch
a = torch.rand(3**10)
b = torch.rand(3**10)

对于这个确切的用例,还需要考虑

a * (b <= 0.5)
a*(b0.5]=0。
每个回路553µs±17.2µs(7次运行的平均±标准偏差,每个1000个回路)
In[3]:a=火炬.rand(3**10)
在[4]中:%时间温度=火炬,其中(b>0.5,火炬张量(0.),a)
...:
每个回路49µs±391 ns(7次运行的平均值±标准偏差,每个10000个回路)
In[5]:a=火炬.rand(3**10)
在[6]中:%时间温度=(a*(b 0.5,0.)
每个回路244µs±3.48µs(7次运行的平均值±标准偏差,每个1000个回路)

我认为没有比这更有效的方法了。我认为产生巨大影响的方法更不可能。那很好。谢谢。
%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)
a * (b <= 0.5)
In [1]: import torch
   ...: a = torch.rand(3**10)
   ...: b = torch.rand(3**10)

In [2]: %timeit a[b > 0.5] = 0.
553 µs ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [3]: a = torch.rand(3**10)

In [4]: %timeit temp = torch.where(b > 0.5, torch.tensor(0.), a)
   ...:
49 µs ± 391 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [5]: a = torch.rand(3**10)

In [6]: %timeit temp = (a * (b <= 0.5))
44 µs ± 381 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [7]: %timeit a.masked_fill_(b > 0.5, 0.)
244 µs ± 3.48 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)