Data Manipulation

To start, we import torch. Note that though it's called PyTorch, we should import torch instead of pytorch

In [1]:
import torch

A tensor represents a (possibly multi-dimensional) array of numerical values

In [2]:
x = torch.arange(12)
x
Out[2]:
tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

We can access a tensor's shape and the total number of elements

In [3]:
x.shape
Out[3]:
torch.Size([12])
In [4]:
x.numel()
Out[4]:
12

Change the shape of a tensor without altering either the number of elements or their values

In [5]:
X = x.reshape(3, 4)
X
Out[5]:
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])

We can create a tensor representing a tensor with all elements set to 0 or 1

In [6]:
torch.zeros((2, 3, 4))
Out[6]:
tensor([[[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]],

        [[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]])
In [7]:
torch.ones((2, 3, 4))
Out[7]:
tensor([[[1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [1., 1., 1., 1.]],

        [[1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [1., 1., 1., 1.]]])

Randomly sample the values for each element in a tensor

In [8]:
torch.randn(3, 4)
Out[8]:
tensor([[ 0.0246, -1.2424, -1.2365, -0.6865],
        [ 0.4471,  0.6969, -0.2290,  0.3570],
        [-0.2619, -0.2451, -1.2113, -0.0141]])

Specify the exact values for each element

In [9]:
torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
Out[9]:
tensor([[2, 1, 4, 3],
        [1, 2, 3, 4],
        [4, 3, 2, 1]])

The common standard arithmetic operators (+, -, *, /, and **) have all been lifted to elementwise operations

In [10]:
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x**y
Out[10]:
(tensor([ 3.,  4.,  6., 10.]),
 tensor([-1.,  0.,  2.,  6.]),
 tensor([ 2.,  4.,  8., 16.]),
 tensor([0.5000, 1.0000, 2.0000, 4.0000]),
 tensor([ 1.,  4., 16., 64.]))

More operations can be applied elementwise

In [11]:
torch.exp(x)
Out[11]:
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])

concatenate multiple tensors together

In [12]:
X = torch.arange(12, dtype=torch.float32).reshape((3, 4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
Out[12]:
(tensor([[ 0.,  1.,  2.,  3.],
         [ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.],
         [ 2.,  1.,  4.,  3.],
         [ 1.,  2.,  3.,  4.],
         [ 4.,  3.,  2.,  1.]]),
 tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
         [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
         [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))

Construct a binary tensor via logical statements

In [13]:
X == Y
Out[13]:
tensor([[False,  True, False,  True],
        [False, False, False, False],
        [False, False, False, False]])

Summing all the elements in the tensor

In [14]:
X.sum()
Out[14]:
tensor(66.)

Perform elementwise operations by invoking the broadcasting mechanism

In [15]:
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
a, b
Out[15]:
(tensor([[0],
         [1],
         [2]]),
 tensor([[0, 1]]))
In [16]:
a + b
Out[16]:
tensor([[0, 1],
        [1, 2],
        [2, 3]])

[-1] selects the last element and [1:3] selects the second and the third elements

In [17]:
X[-1], X[1:3]
Out[17]:
(tensor([ 8.,  9., 10., 11.]),
 tensor([[ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.]]))

We can also write elements of a matrix by specifying indices

In [18]:
X[1, 2] = 9
X
Out[18]:
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  9.,  7.],
        [ 8.,  9., 10., 11.]])

To assign multiple elements the same value, we simply index all of them and then assign them the value

In [19]:
X[0:2, :] = 12
X
Out[19]:
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])

Running operations can cause new memory to be allocated to host results

In [20]:
before = id(Y)
Y = Y + X
id(Y) == before
Out[20]:
False

Performing in-place operations

In [21]:
Z = torch.zeros_like(Y)
print('id(Z):', id(Z))
Z[:] = X + Y
print('id(Z):', id(Z))
id(Z): 140163931996672
id(Z): 140163931996672

If the value of X is not reused in subsequent computations, we can also use X[:] = X + Y or X += Y to reduce the memory overhead of the operation

In [22]:
before = id(X)
X += Y
id(X) == before
Out[22]:
True

Converting to a NumPy tensor

In [23]:
A = X.numpy()
B = torch.tensor(A)
type(A), type(B)
Out[23]:
(numpy.ndarray, torch.Tensor)

Convert a size-1 tensor to a Python scalar

In [24]:
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
Out[24]:
(tensor([3.5000]), 3.5, 3.5, 3)