如何在 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**。

更新於: 2022年1月25日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.