|
| 1 | +--- |
| 2 | +Title: '.logaddexp()' |
| 3 | +Description: 'Computes the element-wise logarithm of the sum of exponentials of two input tensors.' |
| 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 **`.logaddexp()`** function in PyTorch computes the element-wise logarithm of the sum of exponentials of two input [tensors](https://www.codecademy.com/resources/docs/pytorch/tensors). If the tensors are `x` and `y`, the mathematical formula will be: |
| 18 | + |
| 19 | +$$\log(\exp(x) + \exp(y))$$ |
| 20 | + |
| 21 | +This operation is particularly useful for combining log-space values (such as log-probabilities) in a numerically stable way. |
| 22 | + |
| 23 | +## Syntax |
| 24 | + |
| 25 | +```pseudo |
| 26 | +torch.logaddexp(input, other, *, out=None) → Tensor |
| 27 | +``` |
| 28 | + |
| 29 | +**Parameters:** |
| 30 | + |
| 31 | +- `input` (Tensor): The first input tensor. |
| 32 | +- `other` (Tensor): The second input tensor, broadcastable to the shape of `input`. |
| 33 | +- `out` (Tensor, optional): A tensor to store the output; must have the same shape as the broadcasted result if provided. |
| 34 | + |
| 35 | +**Return value:** |
| 36 | + |
| 37 | +Returns a new tensor of the same shape as the broadcasted `input` and `other`, where each element is: |
| 38 | + |
| 39 | +$$\log\left(\exp(\text{input}[i]) + \exp(\text{other}[i])\right)$$ |
| 40 | + |
| 41 | +## Example 1: Combining Log-Probabilities |
| 42 | + |
| 43 | +In this example, two tensors representing log-probabilities are combined using `.logaddexp()`: |
| 44 | + |
| 45 | +```py |
| 46 | +import torch |
| 47 | + |
| 48 | +x = torch.tensor([ -0.5, -1.2, -3.0 ]) |
| 49 | +y = torch.tensor([ -0.2, -0.8, -4.5 ]) |
| 50 | + |
| 51 | +result = torch.logaddexp(x, y) |
| 52 | +print(result) |
| 53 | +``` |
| 54 | + |
| 55 | +The output of this code is: |
| 56 | + |
| 57 | +```shell |
| 58 | +tensor([ 0.3544, -0.2870, -2.7986]) |
| 59 | +``` |
| 60 | + |
| 61 | +## Example 2: Broadcasting Two Tensors of Different Shapes |
| 62 | + |
| 63 | +In this example, a tensor and a scalar are combined with broadcasting using `.logaddexp()`: |
| 64 | + |
| 65 | +```py |
| 66 | +import torch |
| 67 | + |
| 68 | +x = torch.tensor([[ 1.0, 2.0 ,3.0], |
| 69 | + [ 4.0, 5.0 ,6.0]]) |
| 70 | +y = torch.tensor( 2.0 ) |
| 71 | + |
| 72 | +result = torch.logaddexp(x, y) |
| 73 | +print(result) |
| 74 | +``` |
| 75 | + |
| 76 | +The output of this code is: |
| 77 | + |
| 78 | +```shell |
| 79 | +tensor([[2.3133, 2.6931, 3.3133], |
| 80 | + [4.1269, 5.0486, 6.0181]]) |
| 81 | +``` |
0 commit comments