Search code examples
torch

Torch tensor cannot deepcopy using an index array


I'm trying to deepcopy specific slices of a tensor. Suppose a=torch.Tensor([1,2,3,4,5,6]), b=a[2:4], c=a[[2,3]] Seems like b has a deepcopy while c is a shallow copy. But I need to use an index array like [2,3] to get some deepcopy slices. Are there any turnarounds for this? I tried .reshape, .view, .contiguous(), but no luck. Thank you.


Solution

  • Seems like view() works! I use .view() and select the consecutive rows using simple index([:,2:4,:]) instead of advanced index([:,[2,3],:]). One thing I noticed was that after using .view() and selecting wanted rows, it seems like the tensor storage will change and the result after .view() cannot apply another .view() again to change the shape to another.