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