Skip to content

Commit 14bc2d5

Browse files
[Term Entry] PyTorch Tensor Operations: .log2()
1 parent 10578df commit 14bc2d5

File tree

1 file changed

+79
-0
lines changed
  • content/pytorch/concepts/tensor-operations/terms/log2

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
---
2+
Title: '.log2()'
3+
Description: 'Computes the base-2 logarithm of each element in the input tensor and returns a new tensor with the results.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
- 'Data Science'
8+
Tags:
9+
- 'Elements'
10+
- 'Methods'
11+
- 'PyTorch'
12+
- 'Tensors'
13+
CatalogContent:
14+
- 'learn-python-3'
15+
- 'paths/data-science'
16+
---
17+
18+
The **`.log2()`** method in PyTorch returns a new [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) 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).
19+
20+
## Syntax
21+
22+
```pseudo
23+
torch.log2(input, *, out=None) → Tensor
24+
```
25+
26+
**Parameters:**
27+
28+
- `input` (Tensor): The tensor whose elements are to be transformed by base-2 logarithm.
29+
- `out` (Tensor, optional): A tensor to store the output; must have the same shape as input if provided.
30+
31+
**Return value:**
32+
33+
Returns a new tensor of the same shape as `input` where each element is `log₂(input[i])`.
34+
35+
## Example 1: Basic Usage of `torch.log2()`
36+
37+
In this example, the base-2 logarithm is computed for a tensor of powers of two:
38+
39+
```py
40+
import torch
41+
42+
# Define a tensor
43+
input_tensor = torch.tensor([2.0, 4.0, 8.0, 16.0, 32.0])
44+
45+
# Compute base-2 logarithm
46+
output_tensor = torch.log2(input_tensor)
47+
48+
print(output_tensor)
49+
```
50+
51+
The output of this code is:
52+
53+
```shell
54+
tensor([1., 2., 3., 4., 5.])
55+
```
56+
57+
## Example 2: Applying `torch.log2()` on Random Values
58+
59+
In this example, a tensor with random positive values is transformed using base-2 logarithm to analyze data on a log scale:
60+
61+
```py
62+
import torch
63+
64+
# Generate a tensor of random positive values
65+
data = torch.rand(5) * 10 + 1
66+
67+
# Apply log2 transformation
68+
log_tensor = torch.log2(data)
69+
70+
print(data)
71+
print(log_tensor)
72+
```
73+
74+
The output of this code is:
75+
76+
```shell
77+
tensor([10.5500, 9.2777, 10.9371, 1.3551, 5.2609])
78+
tensor([3.3992, 3.2138, 3.4512, 0.4384, 2.3953])
79+
```

0 commit comments

Comments
 (0)