如何在PyTorch中计算张量元素的正弦值?

如何在PyTorch中计算张量元素的正弦值?

要计算张量元素的正弦值,我们使用 torch.sin() 方法。它返回原始输入张量元素的正弦值的新张量。它以张量作为输入参数并输出一个张量。

步骤

  • 导入必需的库。在以下所有Python示例中,所需的Python库是 torch 。确保已经 安装了它。

  • 创建一个张量并打印它。

  • 计算 torch.sin(input) 。它以 输入 ,一个张量作为输入参数,并返回一个新张量,其中包含输入元素的正弦值。

  • 打印具有原始输入张量元素的正弦值的张量。

示例1

# Python program to compute sine of the elements of a tensor
# import necessary library
import torch

# create a tensor 张量
T = torch.Tensor([1.3,4.32,4.4,5.3,4.5])
print("Original Tensor T:\n", T)

# Compute the sine of above tensor 计算上面张量的正弦值
sine_T = torch.sin(T)
print("Sine value of elements of tensor T:\n", sine_T)

输出

Original Tensor T:
   tensor([1.3000, 4.3200, 4.4000, 5.3000, 4.5000])
Sine value of elements of tensor T:
   tensor([ 0.9636, -0.9240, -0.9516, -0.8323, -0.9775])

示例2

# Python program to compute sine of the elements of a tensor
# import necessary library
import torch

# Create a 2D tensor of size 3x5 创建3x5的二维张量
T = torch.Tensor([[1.3,4.32,4.4,5.3,4.5],
                  [0.2,0.3,0.5,0.7,0.9],
                  [1.1,1.2,2.3,3.1,4.9]])
print("Original Tensor T:\n", T)

# Compute the sine of above tensor 计算上面张量的正弦值
sine_T = torch.sin(T)
print("Sine value of elements of tensor T:\n", sine_T)

输出

Original Tensor T:
tensor([[1.3000, 4.3200, 4.4000, 5.3000, 4.5000],
         [0.2000, 0.3000, 0.5000, 0.7000, 0.9000],
         [1.1000, 1.2000, 2.3000, 3.1000, 4.9000]])
Sine value of elements of tensor T:
tensor([[ 0.9636, -0.9240, -0.9516, -0.8323, -0.9775],
         [ 0.1987, 0.2955, 0.4794, 0.6442, 0.7833],
         [ 0.8912, 0.9320, 0.7457, 0.0416, -0.9825]])

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程