|
| 1 | +--- |
| 2 | +Title: '.as_strided()' |
| 3 | +Description: 'Creates a view of a tensor with a specified shape and strides.' |
| 4 | +Subjects: |
| 5 | + - 'AI' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'AI' |
| 9 | + - 'Data Types' |
| 10 | + - 'Deep Learning' |
| 11 | + - 'Functions' |
| 12 | +CatalogContent: |
| 13 | + - 'intro-to-py-torch-and-neural-networks' |
| 14 | + - 'paths/data-science' |
| 15 | +--- |
| 16 | + |
| 17 | +In PyTorch, the **`.as_strided()`** function creates a view of a tensor with a specified shape and strides. Unlike operations that copy data, `.as_strided()` allows modifying how the tensor accesses memory, which enables efficient slicing, reshaping, and advanced indexing without additional memory allocation. |
| 18 | + |
| 19 | +> **Note:** Since `.as_strided()` manipulates tensor memory layout directly, incorrect stride values can lead to unexpected behavior or memory overlap. |
| 20 | +
|
| 21 | +## Syntax |
| 22 | + |
| 23 | +```pseudo |
| 24 | +torch.as_strided(input, size, stride, storage_offset=None) |
| 25 | +``` |
| 26 | + |
| 27 | +- `input`: The input tensor. |
| 28 | +- `size`: The desired shape of the output tensor. |
| 29 | +- `stride`: A tuple specifying the step size to move across dimensions. |
| 30 | +- `storage_offset` (Optional): Defines the starting point in the underlying storage for the output tensor. If set to `None`, the output tensor retains the same `storage_offset` as the input tensor. |
| 31 | + |
| 32 | +## Example |
| 33 | + |
| 34 | +The following example demonstrates how `.as_strided()` can be used to create a sliding window view of a tensor: |
| 35 | + |
| 36 | +```py |
| 37 | +import torch |
| 38 | + |
| 39 | +# Create a 1D tensor |
| 40 | +tensor = torch.arange(10) |
| 41 | + |
| 42 | +# Create a 2x3 strided view (overlapping windows) |
| 43 | +windowed_tensor = tensor.as_strided((2, 3), (2, 1)) |
| 44 | + |
| 45 | +# Print the resultant tensor |
| 46 | +print(windowed_tensor) |
| 47 | +``` |
| 48 | + |
| 49 | +This code generates the output as: |
| 50 | + |
| 51 | +```shell |
| 52 | +tensor([[0, 1, 2], |
| 53 | + [2, 3, 4]]) |
| 54 | +``` |
| 55 | + |
| 56 | +- The original tensor `tensor` contains values `[0, 1, 2, ..., 9]`. |
| 57 | +- The `.as_strided()` function generates a view where: |
| 58 | + - The new shape is `(2, 3)`, meaning two rows and three columns. |
| 59 | + - The first stride is `2`, meaning each row starts 2 elements ahead in the original tensor. |
| 60 | + - The second stride is `1`, meaning elements within each row are consecutive. |
0 commit comments