Skip to content

Commit eb07030

Browse files
authored
Update narrow-copy.md
1 parent edb7846 commit eb07030

File tree

1 file changed

+61
-0
lines changed
  • content/pytorch/concepts/tensor-operations/terms/narrow-copy

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
Title: '.narrow_copy()'
3+
Description: 'Creates a new tensor with a narrowed subsection of data from an input tensor.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Machine Learning'
7+
Tags:
8+
- 'Python'
9+
- 'Machine Learning'
10+
- 'Methods'
11+
- 'Functions'
12+
CatalogContent:
13+
- 'intro-to-py-torch-and-neural-networks'
14+
- 'paths/computer-science'
15+
---
16+
17+
In Pytorch, **`.narrow_copy()`** is a function that creates a new tensor with the same data as the input tensor but with a narrowed dimension. The function is similar to the **`.narrow()`** function, but it returns a new tensor instead of a view of the original tensor.
18+
19+
## Syntax
20+
21+
```pseudo
22+
torch.narrow_copy(input, dim, start, length)
23+
```
24+
25+
- `input`: The input tensor to be narrowed.
26+
- `dim`: The dimension along which the input tensor is to be narrowed.
27+
- `start`: The index where the narrowing begins. This can be a positive integer, a negative integer (to index from the end of `dim`), or a 0-dimensional integer tensor.
28+
- `length`: The number of elements to include from the starting position.
29+
30+
## Example
31+
32+
The following example demonstrates the usage of the **`.narrow_copy()`** function:
33+
34+
```py
35+
import torch
36+
37+
# Create a 2D tensor
38+
tensor_2d = torch.arange(1, 13).reshape(3, 4)
39+
print(f"Original 2D Tensor:\n{tensor_2d}")
40+
41+
# Narrow the tensor along rows and create a new tensor
42+
narrowed_tensor = torch.narrow_copy(tensor_2d, 0, 1, 2)
43+
print(f"Narrowed 2D Tensor:\n{narrowed_tensor}")
44+
```
45+
46+
The above code produces the following output:
47+
48+
```shell
49+
Original 2D Tensor:
50+
tensor([[ 1, 2, 3, 4],
51+
[ 5, 6, 7, 8],
52+
[ 9, 10, 11, 12]])
53+
54+
Narrowed 2D Tensor:
55+
tensor([[ 5, 6, 7, 8],
56+
[ 9, 10, 11, 12]])
57+
```
58+
59+
In this example, the **`.narrow_copy()`** function is used to narrow the input tensor along the rows (dimension 0) starting from index 1 and including 2 rows. The resulting tensor is a new tensor with the narrowed data.
60+
61+
The **`.narrow_copy()`** function is useful when you need to create a new tensor with a subset of data from an existing tensor without modifying the original tensor.

0 commit comments

Comments
 (0)