PyTorch torch.narrow_copy Function
PyTorch torch Reference Manual
torch.narrow_copyIt is a function in PyTorch used to return a copy of a tensor slice. It returns a copy of the slice from the starting position to the specified length on the specified dimension.
This function istorch.narrowfunctionally similar to, buttorch.narrowreturns a view, whiletorch.narrow_copyreturns a copy.
Function Definition
torch.narrow_copy(input, dim, start, length)
Parameters:
input(Tensor): Input tensor.dim(int): The dimension to be sliced.start(int): Starting index.length(int): The length of the slice.
Return Value:
torch.Tensor: Returns the tensor copy after the specified slicing.
Usage Example
Example
import torch
# Create a tensor
x = torch.tensor([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# In 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 does not affect the original tensor
y[0, 0] = 100
print("nAfter modifying the copy, original tensor:", x[0, 0])
print("After modifying the copy, sliced copy:", y[0, 0])
# Create a tensor
x = torch.tensor([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# In 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 does not affect the original tensor
y[0, 0] = 100
print("nAfter modifying the copy, original tensor:", x[0, 0])
print("After modifying the copy, sliced copy:", y[0, 0])
The output result is:
原始张量:
tensor([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
切片副本:
tensor([[1, 2, 3, 4],
[5, 6, 7, 8]])
修改副本后,原始张量: tensor(1)
修改副本后,切片副本: 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("Sliced copy shape:", y.shape)
# 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("Sliced copy shape:", y.shape)
The output result is:
原始形状: torch.Size([5, 6, 7]) 切片副本形状: torch.Size([5, 4, 7])
Note:torch.narrow_copyIt returns a copy, not a view. This means modifying the returned tensor does not affect the original tensor, but it consumes extra memory. If an independent copy is not needed, you can usetorch.narrowto save memory.
Other Extensions