Inverting an array with pytorch

I’ve been working with pytorch more and more lately for NLP, and I’d like to write down some things I want to keep in mind.

github

  • The file in jupyter notebook format is here

google colaboratory

  • To run it in google colaboratory here

Author’s environment

The author’s OS is macOS, and the options are different from Linux and Unix commands.

! sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G103
Python -V
Python 3.8.5

Import the basic libraries and check their versions.

%matplotlib inline
%config InlineBackend.figure_format = 'svg'

import matplotlib
import matplotlib.pyplot as plt
import scipy
import numpy as np
import torch

print('matplotlib version :', matplotlib.__version__)
print('scipy version :', scipy.__version__)
print('numpy version :', np.__version__)
print('torch version :', torch.__version__)
matplotlib version : 3.3.2
scipy version : 1.3.1
numpy version : 1.19.2
torch version : 1.10.0

Invert with numpy

a = np.array([i for i in range(10)])
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[::-1]]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
a = np.array([[i * j for i in range(10)] for j in range(10)])
a
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
       [ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27],
       [ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36],
       [ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45],
       [ 0, 6, 12, 18, 24, 30, 36, 42, 48, 54],
       [ 0, 7, 14, 21, 28, 35, 42, 49, 56, 63],
       [ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72],
       [ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81]])
a[:,::-1]]
array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
       [18, 16, 14, 12, 10, 8, 6, 4, 2, 0],
       [27, 24, 21, 18, 15, 12, 9, 6, 3, 0],
       [36, 32, 28, 24, 20, 16, 12, 8, 4, 0],
       [45, 40, 35, 30, 25, 20, 15, 10, 5, 0],
       [54, 48, 42, 36, 30, 24, 18, 12, 6, 0],
       [63, 56, 49, 42, 35, 28, 21, 14, 7, 0],
       [72, 64, 56, 48, 40, 32, 24, 16, 8, 0],
       [81, 72, 63, 54, 45, 36, 27, 18, 9, 0]])

Inversion by pytroch

Since pytorch can’t do inversion like a[::-1], we need to invert it in another way.

Inverting a 1D tensor.

a = torch.tensor(range(12))
a
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
torch.flip(a, dims=[0])
tensor([11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

Invert 2D tensor.

a = a.reshape(3,4)
a
tensor([ 0, 1, 2, 3],
        [ 4, 5, 6, 7],
        [ 8, 9, 10, 11]])

Invert on the x-axis.

torch.flip(a, dims=[0])
tensor([[ 8, 9, 10, 11]],
        [ 4, 5, 6, 7],
        [ 0, 1, 2, 3]])

Invert on the y-axis.

torch.flip(a, dims=[1])
tensor([ 3, 2, 1, 0],
        [ 7, 6, 5, 4],
        [11, 10, 9, 8]])

Flip the image left and right.

torch.fliplr(a)
tensor([[ 3, 2, 1, 0]],
        [ 7, 6, 5, 4],
        [11, 10, 9, 8]])

I’ll remember this because sometimes I forget and have to look it up every time.