# PyTorch – How to get the exponents of tensor elements?

PyTorchServer Side ProgrammingProgramming

To find the exponential of the elements of an input tensor, we can apply Tensor.exp() or torch.exp(input). Here, input is the input tensor for which the exponentials are computed. Both the methods return a new tensor with the exponential values of the elements of the input tensor.

## Syntax

Tensor.exp()

or

torch.exp(input)


## Steps

We could use the following steps to compute the exponentials of the elements of an input tensor −

• Import the torch library. Make sure you have it already installed.
import torch
• Create a tensor and print it.
t1 = torch.rand(4,3)
print("Tensor:", t1)
• Compute the exponential of the elements of the tensor. For this, use torch.exp(input) and optionally assign this value to a new variable.
exp_t1 = torch.exp(t1)

• Print the resultant tensor.
print("Exponentials of elements:\n", exp_t1)

## Example 1

The following Python program shows how to compute the exponentials of the elements of an input tensor.

# 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)

## Output

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]])

## Example 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)

## Output

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]])