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.

Syntax

torch.log(input, *, out=None) ? Tensor

Parameters

  • input − The input tensor containing positive values
  • out (optional) − The output tensor to store the result

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: Computing Logarithm of 1D Tensor

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

import torch

# Create a tensor
t = torch.tensor([2.3, 3.0, 2.3, 4.0, 3.4])

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

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

# print the computed logarithm of elements
print("Logarithm of Elements:")
print(log)
Original tensor:
tensor([2.3000, 3.0000, 2.3000, 4.0000, 3.4000])
Logarithm of Elements:
tensor([0.8329, 1.0986, 0.8329, 1.3863, 1.2238])

Example 2: Computing Logarithm of 2D Tensor

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

import torch

# Create a tensor of random numbers of size 3x4
torch.manual_seed(42)  # For reproducible results
t = torch.rand(3, 4)

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

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

# print the computed logarithm of elements
print("Logarithm of Elements:")
print(log)
Original tensor:
tensor([[0.8823, 0.9150, 0.3829, 0.9593],
        [0.3904, 0.6009, 0.2566, 0.7936],
        [0.9408, 0.1332, 0.9346, 0.5936]])
Logarithm of Elements:
tensor([[-0.1252, -0.0887, -0.9597, -0.0418],
        [-0.9400, -0.5098, -1.3594, -0.2317],
        [-0.0611, -2.0149, -0.0676, -0.5220]])

Key Points

  • The torch.log() function computes the natural logarithm (base e) of each element
  • Input tensor elements must be positive, as logarithm is undefined for zero and negative values
  • The function returns a new tensor with the same shape as the input
  • For other logarithm bases, use torch.log2() or torch.log10()

Conclusion

Use torch.log() to compute natural logarithms of tensor elements in PyTorch. Ensure input values are positive to avoid mathematical errors, and consider using torch.log2() or torch.log10() for different logarithm bases.

Updated on: 2026-03-26T18:45:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements