PyTorch .log2()
Published Dec 16, 2025
Contribute to Docs
The .log2() method in PyTorch returns a new tensor by computing the logarithm base 2 of each element in the input tensor. This operation is useful in numerous data-science and machine-learning workflows where values are interpreted on a log scale (e.g., information theory, binary magnitude comparisons).
Syntax
torch.log2(input, *, out=None) → Tensor
Parameters:
input(Tensor): The tensor whose elements are to be transformed by base-2 logarithm.out(Tensor, optional): A tensor to store the output; must have the same shape as input if provided.
Return value:
Returns a new tensor of the same shape as input where each element is log₂(input[i]).
Example 1: Basic Usage of .log2()
In this example, the base-2 logarithm is computed for a tensor containing powers of 2:
import torch# Define a tensorinput_tensor = torch.tensor([2.0, 4.0, 8.0, 16.0, 32.0])# Compute base-2 logarithmoutput_tensor = torch.log2(input_tensor)print(output_tensor)
The output of this code is:
tensor([1., 2., 3., 4., 5.])
Example 2: Applying .log2() on Random Values
In this example, a tensor with random positive values is transformed using base-2 logarithm to analyze data on a log scale:
import torch# Generate a tensor of random positive valuesdata = torch.rand(5) * 10 + 1# Apply log2 transformationlog_tensor = torch.log2(data)print(data)print(log_tensor)
The output of this code is:
tensor([10.5500, 9.2777, 10.9371, 1.3551, 5.2609])tensor([3.3992, 3.2138, 3.4512, 0.4384, 2.3953])
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours