Data Manipulation¶

To start, we import the PyTorch library. Note that the package name is torch

In [1]:
import torch


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

In [2]:
x = torch.arange(12, dtype=torch.float32)
x

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

Out[3]:
12

We can access a tensor's shape

In [4]:
x.shape

Out[4]:
torch.Size([12])

Change the shape of a tensor without altering its size or 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 construct a tensor with all elements set to zero or one

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.]]])

Sample each element randomly (and independently)

In [8]:
torch.randn(3, 4)

Out[8]:
tensor([[-0.4466, -1.9101, -0.3280,  1.6345],
[ 0.4009,  1.6138,  0.7530, -0.2274],
[-0.1332,  0.2832,  0.8813, -1.8539]])

Supplying 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]])

[-1] selects the last row and [1:3] selects the second and third rows

In [10]:
X[-1], X[1:3]

Out[10]:
(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 [11]:
X[1, 2] = 17
X

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

To assign multiple elements the same value, we apply the indexing on the left-hand side of the assignment operation

In [12]:
X[0:2, :] = 12
X

Out[12]:
tensor([[12., 12., 12., 12.],
[12., 12., 12., 12.],
[ 8.,  9., 10., 11.]])
In [13]:
torch.exp(x)

Out[13]:
tensor([162754.7969, 162754.7969, 162754.7969, 162754.7969, 162754.7969,
162754.7969, 162754.7969, 162754.7969,   2980.9580,   8103.0840,
22026.4648,  59874.1406])
In [14]:
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[14]:
(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.]))

concatenate multiple tensors together

In [15]:
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[15]:
(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 [16]:
X == Y

Out[16]:
tensor([[False,  True, False,  True],
[False, False, False, False],
[False, False, False, False]])

Summing all the elements in the tensor

In [17]:
X.sum()

Out[17]:
tensor(66.)

Perform elementwise binary operations by invoking the broadcasting mechanism

In [18]:
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
a, b

Out[18]:
(tensor([[0],
[1],
[2]]),
tensor([[0, 1]]))
In [19]:
a + b

Out[19]:
tensor([[0, 1],
[1, 2],
[2, 3]])

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): 140149213601664
id(Z): 140149213601664


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 (ndarray)

In [23]:
A = X.numpy()
B = torch.from_numpy(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)