SoFunction
Updated on 2024-11-10

pytorch Methods for reordering data in a dimension

In pytorch, the Tensor exists as a reference, so it is not possible to exchange data directly as in python.

a = (3,4)
a[0],a[1] = a[1],a[0]

# This will result in a=(a[1],a[1],a[2])
# Instead of expected (a[1],a[0],a[2])

This is due to reference assignment, in the exchange process, as shown below, when the value of b is assigned with a, because the tmp pointer is a different name of the same variable as a, so the content of tmp will also change to b.

# Swap a,b
a,b = b,a
# Equivalent to
tmp = a
a = b # At this point, tmp = a= b
b = tmp

So in the other way we exchange them, by indexing the subscripts of the

a = (3,4)
index = [1,0,2]
a = a[index]

This pytorch above method of adjusting the order of data in a certain dimension is all that I have shared with you, and I hope it will give you a reference, and I hope you will support me more.