添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
另类的甜瓜  ·  塔罗牌圣杯四 (4 of ...·  1 月前    · 
骑白马的紫菜汤  ·  Python Asyncio ...·  2 月前    · 
爱热闹的打火机  ·  Permision problem pip·  6 月前    · 
开朗的针织衫  ·  道枝駿佑 ...·  6 月前    · 

Is there a way to vectorize this code in pytorch?

def myfunc(a, b):
    "Return a-b if a>b, otherwise return a+b"
    if a > b:
        return a - b
    else:
        return a + b

With numpy I can simply do

@np.vectorize
def myfunc(a, b):
    "Return a-b if a>b, otherwise return a+b"
    if a > b:
        return a - b
    else:
        return a + b

such that myfunc(a=[1, 2, 3, 4], b=2) returns array([3, 4, 1, 2]).

Is there a way to do the same in pytorch?

It seems torch.where() is the way to go:

a = torch.tensor([1, 2, 3, 4])
b = torch.tensor(2)
torch.where(a>b, a-b, a+b)

the code above returns tensor([3, 4, 1, 2]).