如何在 PyTorch 中計算給定輸入張量的逐元素角度?


要計算給定輸入張量的逐元素角度,我們應用 **torch.angle()**。它接收一個輸入張量,並返回一個張量,其中包含逐元素計算的弧度角。要將角度轉換為度數,我們將弧度角乘以 **180/np.pi**。它支援實數和複數張量。

語法

torch.angle(input)

步驟

要計算逐元素角度,您可以按照以下步驟操作:

  • 匯入所需的庫。在以下所有示例中,所需的 Python 庫是 **torch**。請確保您已安裝它。

import torch
  • 定義 torch 張量並列印它們。

input = torch.tensor([1 + 1j, -1 -4j, 3-2j])
  • 計算 **torch.angle(input)**。它是一個張量,包含針對輸入逐元素計算的弧度角。

angle = torch.angle(input)
  • 列印上面計算的包含弧度角的張量。

print("Angles in Radian:
", angle)

讓我們通過幾個示例來演示如何計算弧度和度數的逐元素角度。

示例 1

在下面的 Python3 程式中,我們計算給定輸入張量的弧度和度數的逐元素角度。

# Python 3 program to compute the element-wise
# angle (in radians and degree) of the given input tensor
# Import the required libraries
import torch
from numpy import pi

# define a complex input tensor
input = torch.tensor([1 + 1j, -1 -4j, 3-2j])

# print the input tensor
print("Input Tensor:
", input) # compute the angle in radians angle = torch.angle(input) # print the computed tensor of angles print("Angles in Radian:
", angle) # convert the angle s in degree degree = angle*180/pi # print the computed tensor of degree print("Angles in Degree:
", degree)

輸出

Input Tensor:
   tensor([ 1.+1.j, -1.-4.j, 3.-2.j])
Angles in Radian:
   tensor([ 0.7854, -1.8158, -0.5880])
Angles in Degree:
   tensor([ 45.0000, -104.0362, -33.6901])

示例 2

在這個程式中,我們計算給定輸入張量的弧度和度數的逐元素角度。

# Python 3 program to to compute the element-wise
# angle (in radians and degrees) of the given input tensor
# Import the required libraries
import torch
from numpy import pi

# define a complex input tensor
real = torch.randn(3,4)
imag = torch.randn(3,4)
input = torch.complex(real, imag)

# print the input tensor
print("Input Tensor:
", input) # compute the angle in radians angle = torch.angle(input) # print the computed tensor of angles print("Angles in Radian:
", angle) # convert the angle s in degree degree = angle*180/pi # print the computed tensor of degree print("Angles in Degree:
", degree)

輸出

Input Tensor:
   tensor([[ 0.1967-0.0188j, -0.5311-1.2427j, 0.9937+0.0051j, - 1.8304-0.1321j],
      [-0.1787+1.7834j, 0.9925+0.2452j, -0.8813-0.0207j, - 0.4967+0.9938j],
      [-0.9051-0.1204j, 1.0013+0.3430j, 0.6131-0.0317j, - 0.3861+0.6365j]])
Angles in Radian:
   tensor([[-0.0955, -1.9747, 0.0052, -3.0695],
      [ 1.6707, 0.2422, -3.1181, 2.0343],
      [-3.0093, 0.3300, -0.0517, 2.1161]])
Angles in Degree:
   tensor([[ -5.4711, -113.1396, 0.2962, -175.8722],
      [ 95.7231, 13.8750, -178.6560, 116.5553],
      [-172.4209, 18.9103, -2.9624, 121.2437]])

更新於: 2022年1月27日

458 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.