英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论