Pytorch Torch Narrow_Copy
# PyTorch torch.narrow_copy Function
* * PyTorch torch Reference](#)
`torch.narrow_copy` is a PyTorch function that returns a copy of a tensor slice. It creates a copy of the slice starting at a specified position along a given dimension with a specified length.
This function works similarly to `torch.narrow`, but `torch.narrow` returns a view while `torch.narrow_copy` returns a copy.
### Function Definition
torch.narrow_copy(input, dim, start, length)
**Parameters**:
* `input` (Tensor): Input tensor.
* `dim` (int): Dimension to slice.
* `start` (int): Starting index.
* `length` (int): Length of the slice.
**Returns**:
* `torch.Tensor`: Returns a tensor copy of the specified slice.
* * *
## Usage Examples
## Example
import torch
# Create a tensor
x = torch.tensor([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
# On the first dimension (rows), take 2 rows starting from index 0
y = torch.narrow_copy(x, dim=0, start=0, length=2)
print("Original tensor:")
print(x)
print("nSliced copy:")
print(y)
# Modifying the copy will not affect the Original tensor
y[0,0]=100
print("nAfter modifying the copy, the Original tensor:", x[0,0])
print("Sliced copy after modifying the copy:", y[0,0])
Output result:
Original tensor: tensor([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]])Sliced copy: tensor([[1, 2, 3, 4], [5, 6, 7, 8]])After modifying the copy, the Original tensor: tensor(1)Sliced copy after modifying the copy: tensor(100)
## Example
import torch
# Create a 3D tensor
x = torch.randn(5,6,7)
# On the second dimension, take 4 elements starting from index 2
y = torch.narrow_copy(x, dim=1, start=2, length=4)
print("Original shape:", x.shape)
print("Shape of the sliced copy:", y.shape)
Output result:
Original shape: torch.Size([5, 6, 7])Shape of the sliced copy: torch.Size([5, 4, 7])
* * *
Note: `torch.narrow_copy` returns a copy rather than a view. This means modifying the returned tensor will not affect the original tensor, but it will consume additional memory. Use `torch.narrow` if you don't need an independent copy to save memory.
* * PyTorch torch Reference](#)
YouTip