How to compute the Logarithm of elements of a tensor in PyTorch?


To compute the logarithm of elements of a tensor in PyTorch, we use the torch.log() method. It returns a new tensor with the natural logarithm values of the elements of the original input tensor. It takes a tensor as the input parameter and outputs a tensor.

Steps

  • Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already installed it.

  • Create a tensor and print it.

  • Compute torch.log(input). It takes input, a tensor, as the input parameter and returns a new tensor with the natural logarithm values of elements of the input.

  • Print the tensor with the natural logarithm values of elements of the original input tensor.

Example 1

The following Python program shows how to compute the natural logarithm of a PyTorch tensor.

# import necessary library
import torch

# Create a tensor
t = torch.Tensor([2.3,3,2.3,4,3.4])

# print the above created tensor
print("Original tensor:\n", t)

# compute the logarithm of elements of the above tensor
log = torch.log(t)

# print the computed logarithm of elements
print("Logarithm of Elements:\n", log)

Output

Original tensor:
   tensor([2.3000, 3.0000, 2.3000, 4.0000, 3.4000])
Logrithm of Elements:
   tensor([0.8329, 1.0986, 0.8329, 1.3863, 1.2238])

Example 2

The following Python program shows how to compute the natural logarithm of a 2D tensor.

# import necessary libraries
import torch

# Create a tensor of random numbers of size 3x4
t = torch.rand(3,4)

# print the above created tensor
print("Original tensor:\n", t)

# compute the logarithm of elements of the above tensor
log = torch.log(t)

# print the computed logarithm of elements
print("Logarithm of Elements:\n", log)

Output

Original tensor:
tensor([[0.1245, 0.0448, 0.1176, 0.7607],
         [0.7415, 0.7738, 0.0694, 0.6983],
         [0.8371, 0.6169, 0.3858, 0.8027]])
Logarithm of Elements:
tensor([[-2.0837, -3.1048, -2.1405, -0.2735],
         [-0.2990, -0.2565, -2.6676, -0.3591],
         [-0.1778, -0.4830, -0.9524, -0.2198]])

Updated on: 06-Nov-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements