如何在 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]])
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP