# PyTorch – torch.log2() Method

PyTorchServer Side ProgrammingProgramming

We use the torch.log2() method to compute logarithm to the base 2 of the elements of a tensor. It returns a new tensor with the logarithm values of the elements of the original input tensor. It takes a tensor as the input parameter and outputs a tensor.

### Syntax

torch.log2(input)

where input is a PyTorch tensor.

It returns a new tensor with logarithm base 2 values.

## Steps

• Import the torch library. Make sure you have it already installed.

import torch

• Create a tensor and print it.

tensor1 = torch.rand(5,3)
print("Tensor:", tensor1)
• Compute torch.log2(input) and optionally assign this value to a new variable. Here, input is the created tensor.

logb2 = torch.log2(tensor1)

• Print the resultant tensor.

print("logarithm base 2 of elements:\n",logb2)

## Example 1

The following Python program shows how to compute the logarithm to the base 2 of the elements of the input tensor in PyTorch.

# import torch library
import torch

# create a 2D tensor
tensor1 = torch.rand(5,3)
print("Tensor:", tensor1)

# compute logarithm base 2 of the elements of above tensor
logb2 = torch.log2(tensor1)

print("logarithm base 2 of elements:\n",logb2)

## Output

Tensor: tensor([[0.5755, 0.3263, 0.3598],
[0.0498, 0.0915, 0.0119],
[0.6760, 0.6329, 0.7446],
[0.5575, 0.6406, 0.2418],
[0.4944, 0.7194, 0.9808]])
logarithm base 2 of elements:
tensor([[-0.7970, -1.6158, -1.4749],
[-4.3272, -3.4495, -6.3959],
[-0.5650, -0.6599, -0.4255],
[-0.8430, -0.6426, -2.0480],
[-1.0162, -0.4751, -0.0279]])

## Example 2

# import required library
import torch

# create a 1D tensor
t = torch.tensor([1,2,3,4,5])
print("Tensor:", tensor1)

# compute logarithm base 2 of the elements of above tensor
logb2 = torch.log2(t)

print("logarithm base 2:\n",logb2)

## Output

Tensor: tensor([1, 2, 3, 3, 4, 5])
logarithm base 2:
tensor([0.0000, 1.0000, 1.5850, 2.0000, 2.3219])