PyTorch – 如何获得张量元素的指数?

要找到输入张量元素的指数,我们可以应用或。这里,输入是计算指数的输入张量。这两种方法都返回一个新的张量,其中包含输入张量元素的指数值。Tensor.exp()torch.exp(input)

语法

Tensor.exp()

或者

torch.exp(input)

步骤

我们可以使用以下步骤来计算输入张量元素的指数 -

  • 导入火炬库。确保您已经安装了它。

import torch

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

t1 = torch.rand(4,3)
print("Tensor:", t1)

  • 计算张量元素的指数。为此,请使用并可选地将此值分配给新变量。torch.exp(input)

exp_t1 = torch.exp(t1)

  • 打印结果张量。

print("Exponentials of elements:\n", exp_t1)

示例 1

以下 Python 程序展示了如何计算输入张量元素的指数。

# import torch library
import torch

# create a tensor
t1 = torch.tensor([1,2,3,4,5])

# display the tensor
print("Tensor t1:\n", t1)

# Compute the exponential of the elements of the tensor
exp_t1 = t1.exp()
print("Exponential of t1:\n",exp_t1)

# create another tensor
t2 = torch.randn(2,3)
print("Tensor t2:\n", t2)

# Compute the exponential of the elements of the above tensor
exp_t2 = t2.exp()
print("Exponential of t2:\n",exp_t2)
输出结果
Tensor t1:
 tensor([1, 2, 3, 4, 5])
Exponential of t1:
 tensor([ 2.7183, 7.3891, 20.0855, 54.5981, 148.4132])
Tensor t2:
 tensor([[ 0.2986, 0.0348, 2.1201],
   [-0.4488, -0.2205, 0.5417]])
Exponential of t2:
 tensor([[1.3480, 1.0354, 8.3319],
   [0.6384, 0.8021, 1.7189]])

示例 2

# import torch library
import torch

# create a tensor
t1 = torch.tensor([[1,2,3],[4,5,6]])

# display the tensor
print("Tensor t1:\n", t1)

# Other way to compute the exponential of the elements
exp_t1 = torch.exp(t1)
print("Exponential of t1:\n",exp_t1)

# create another tensor
t2 = torch.randn(4,3)
print("Tensor t2:\n", t2)

# compute the exponential of the elements of the tensor
exp_t2 = torch.exp(t2)
print("Exponential of t2:\n",exp_t2)
输出结果
Tensor t1:
 tensor([[1, 2, 3],
   [4, 5, 6]])
Exponential of t1:
 tensor([[ 2.7183, 7.3891, 20.0855],
   [ 54.5981, 148.4132, 403.4288]])
Tensor t2:
 tensor([[ 1.3574, -0.3132, 0.9117],
   [-0.4421, 1.4100, -0.9875],
   [ 0.1515, 0.1374, -0.6713],
   [ 1.1636, -0.1663, -1.1224]])
Exponential of t2:
 tensor([[3.8862, 0.7311, 2.4884],
   [0.6427, 4.0959, 0.3725],
   [1.1636, 1.1473, 0.5110],
   [3.2014, 0.8468, 0.3255]])