|
| 1 | +--- |
| 2 | +Title: '.lerp()' |
| 3 | +Description: 'Returns a tensor containing the linear interpolation of two tensors, controlled by a scalar or tensor weight.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Machine Learning' |
| 7 | +Tags: |
| 8 | + - 'Functions' |
| 9 | + - 'Machine Learning' |
| 10 | + - 'Python' |
| 11 | + - 'Tensor' |
| 12 | +CatalogContent: |
| 13 | + - 'intro-to-py-torch-and-neural-networks' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +In PyTorch, the **`.lerp()`** function computes the linear interpolation between an input [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) (`input`) and an end tensor (`end`), using a scalar or tensor `weight`. This is mathematically equivalent to applying the function $out_i = start_i + weight_i * (end_i - start_i)$. |
| 18 | + |
| 19 | +The shapes of `input`, `end`, and `weight` must be [broadcastable](https://www.codecademy.com/resources/docs/numpy/array-broadcasting). |
| 20 | + |
| 21 | +## Syntax |
| 22 | + |
| 23 | +```pseudo |
| 24 | +torch.lerp(input, end, weight, *, out=None) |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `input`: The input tensor containing the initial points. |
| 30 | +- `end`: The ending tensor containing the finishing points. |
| 31 | +- `weight`: The shapes of input, end, and weight must be [broadcastable](https://www.codecademy.com/resources/docs/numpy/array-broadcasting). |
| 32 | +- `out` (optional): A tensor to store the output. If provided, the result is written to this tensor. |
| 33 | + |
| 34 | +**Return value:** |
| 35 | + |
| 36 | +Returns a new tensor containing the result given by the interpolation formula. |
| 37 | + |
| 38 | +## Example |
| 39 | + |
| 40 | +The following example shows how to compute the interpolation between two tensors using `torch.lerp()` with a float scalar weight: |
| 41 | + |
| 42 | +```py |
| 43 | +import torch |
| 44 | +import math |
| 45 | + |
| 46 | +# Define two tensors |
| 47 | +start = torch.tensor([12.0 , 14.0 , 16.0 , math.log(2.)]) |
| 48 | +end = torch.tensor([11.0 , 13.0 , 15.0 , math.log(2.)]) |
| 49 | + |
| 50 | +# Compute the interpolation with a float weight |
| 51 | +out = torch.lerp(start, end, 0.8) |
| 52 | + |
| 53 | +print(out) |
| 54 | +``` |
| 55 | + |
| 56 | +Here is the output: |
| 57 | + |
| 58 | +```shell |
| 59 | +tensor([11.2000, 13.2000, 15.2000, 0.6931]) |
| 60 | +``` |
0 commit comments