平方根的负数 pytorch

huangapple go评论72阅读模式
英文:

Square root of a negative number pytorch

问题

我有一个张量(在cuda设备上),其中填充了负数和正数,我想计算这个张量的平方根。我希望输出是一个ComplexFloatTensor(因为sqrt(-1)=i)。请问我如何在PyTorch中实现这个目标?

我找到了一个解决方案,可以通过执行np.emath.sqrt(x.cpu().numpy())来实现,但我正在寻找一个不使用CPU,仅使用GPU的解决方案。

英文:

I have a tensor (on cuda device) filled with negative and positive numbers and i want to compute the square root of this tensor. I would like the output to be a ComplexFloatTensor (since sqrt(-1)=i). How can i do that in pytorch please ?

I found a solution by doing np.emath.sqrt(x.cpu().numpy()) but i am looking for a solution which doesn't use the cpu, only the gpu.

答案1

得分: 1

只需在调用 sqrt 之前将其转换为复数。

In [26]: t = torch.tensor([1,2,3,-1,-2,-3], dtype=torch.float)

In [27]: torch.sqrt(t)
Out[27]: tensor([1.0000, 1.4142, 1.7321,    nan,    nan,    nan])

In [28]: torch.sqrt(t.to(torch.complex64))
Out[28]:
tensor([1.0000+0.0000j, 1.4142+0.0000j, 1.7321+0.0000j, 0.0000+1.0000j,
        0.0000+1.4142j, 0.0000+1.7321j])
英文:

just convert to complex before calling sqrt

In [26]: t = torch.tensor([1,2,3,-1,-2,-3], dtype=torch.float)

In [27]: torch.sqrt(t)
Out[27]: tensor([1.0000, 1.4142, 1.7321,    nan,    nan,    nan])

In [28]: torch.sqrt(t.to(torch.complex64))
Out[28]:
tensor([1.0000+0.0000j, 1.4142+0.0000j, 1.7321+0.0000j, 0.0000+1.0000j,
        0.0000+1.4142j, 0.0000+1.7321j])

huangapple
  • 本文由 发表于 2023年7月14日 05:01:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定