如何在 PyTorch 中使用给定的实部和虚部构建一个复数张量?
使用给定的实部和虚部,我们可以使用 **torch.complex()** 方法在 PyTorch 中构建一个复数。实部和虚部必须是 **float** 或 **double** 类型。实部和虚部都必须是相同的类型。如果实部是 **float**,则虚部也必须是 **float**。
如果输入是 **torch.float32**,则构建的复数张量必须是 **torch.complex64**。
如果输入是 **torch.float64**,则复数张量必须是 **torch.complex128**。
语法
torch.complex(real, imag)
参数
**real** 和 **imag** - 复数张量的实部和虚部。两者必须具有相同的 dtype,只能是 **float** 或 **double**。
步骤
我们可以使用以下步骤构建一个具有给定 **real** 和 **imag** 的复数张量:
导入所需的库。在以下所有示例中,所需的 Python 库是 torch。确保您已安装它。
import torch
定义两个 torch 张量 - **real** 和 **imag**。两个张量中的元素数量必须相同。
real = torch.randn(2,3, dtype = torch.double) imag = torch.randn(2,3, dtype= torch.double)
使用给定的 **real** 和 **imag** 构建一个复数张量。
z = torch.complex(real, imag)
打印上面计算出的复数张量。
print("Complex Number:
", z)打印复数张量的 dtype。
print("dtype of Complex number:",z.dtype)示例 1
import torch
real = torch.tensor([1, 2], dtype = torch.float32)
imag = torch.tensor([3, 4], dtype= torch.float32)
print("Real Part:
", real)
print("Imaginary Part:
", imag)
z = torch.complex(real, imag)
'''
Both real and imaginary parts should be of same data types;
it supports float and double
'''
print("Complex Number:
", z)
print("dtype of Complex number:",z.dtype)输出
Real Part: tensor([1., 2.]) Imaginary Part: tensor([3., 4.]) Complex Number: tensor([1.+3.j, 2.+4.j]) dtype of Complex number: torch.complex64
在上面的示例中,我们构建了一个 **dtype=torch.complx64** 的复数张量。实部和虚部张量的 **dtype=torch.float32**。
示例 2
# Import the required library
import torch
# define real and imag parts as double
real = torch.randn(2,3, dtype = torch.double)
imag = torch.randn(2,3, dtype= torch.double)
print("Real Part:
", real)
print("Imaginary Part:
", imag)
# create complex number using the above
z = torch.complex(real, imag)
'''
Both real and imaginary parts should be of same data types;
it supports float and double
'''
print("Complex number:
",z)
print("dtype of complex number:
", z.dtype)输出
Real Part: tensor([[-0.6168, -0.8757, 1.5826], [-0.7090, 1.4633, -0.6376]], dtype=torch.float64) Imaginary Part: tensor([[-0.1338, -0.1485, -0.1314], [ 1.8149, -0.1233, -0.0694]], dtype=torch.float64) Complex number: tensor([[-0.6168-0.1338j, -0.8757-0.1485j, 1.5826-0.1314j], [-0.7090+1.8149j, 1.4633-0.1233j, -0.6376-0.0694j]], dtype=torch.complex128) dtype of complex number: torch.complex128
在上面的示例中,我们构建了一个 **dtype=torch.complex128** 的复数张量。实部和虚部张量的 **dtype=torch.double**。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP