Note

Click here to download the full example code

# What is PyTorch?¶

It’s a Python-based scientific computing package targeted at two sets of audiences:

- A replacement for NumPy to use the power of GPUs
- a deep learning research platform that provides maximum flexibility and speed

## Getting Started¶

### Tensors¶

Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.

```
from __future__ import print_function
import torch
```

Note

An uninitialized matrix is declared, but does not contain definite known values before it is used. When an uninitialized matrix is created, whatever values were in the allocated memory at the time will appear as the initial values.

Construct a 5x3 matrix, uninitialized:

```
x = torch.empty(5, 3)
print(x)
```

Out:

```
tensor([[ 2.4803e+10, 4.5682e-41, -5.2702e-22],
[ 3.0956e-41, 5.1725e+10, 7.0413e+15],
[-6.2637e-10, 1.4842e+22, 9.2030e+14],
[ 7.3787e-19, 3.1588e-29, 1.6175e-38],
[ 4.5981e+34, nan, 1.0947e-22]])
```

Construct a randomly initialized matrix:

```
x = torch.rand(5, 3)
print(x)
```

Out:

```
tensor([[0.7799, 0.1989, 0.5753],
[0.4624, 0.5366, 0.7436],
[0.8719, 0.9631, 0.3204],
[0.8461, 0.0422, 0.3457],
[0.9910, 0.8967, 0.5962]])
```

Construct a matrix filled zeros and of dtype long:

```
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
```

Out:

```
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
```

Construct a tensor directly from data:

```
x = torch.tensor([5.5, 3])
print(x)
```

Out:

```
tensor([5.5000, 3.0000])
```

or create a tensor based on an existing tensor. These methods will reuse properties of the input tensor, e.g. dtype, unless new values are provided by user

```
x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes
print(x)
x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x) # result has the same size
```

Out:

```
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[-0.0216, -1.6584, 0.6530],
[-1.1740, -1.7741, 0.4818],
[ 1.1351, -0.6516, -0.7546],
[-0.1730, 1.7497, 0.1124],
[-0.6869, -1.2869, 1.7685]])
```

Get its size:

```
print(x.size())
```

Out:

```
torch.Size([5, 3])
```

Note

`torch.Size`

is in fact a tuple, so it supports all tuple operations.

### Operations¶

There are multiple syntaxes for operations. In the following example, we will take a look at the addition operation.

Addition: syntax 1

```
y = torch.rand(5, 3)
print(x + y)
```

Out:

```
tensor([[ 0.6630, -0.9238, 0.7862],
[-0.6723, -0.8995, 0.5601],
[ 1.2930, -0.6163, 0.0968],
[ 0.6110, 2.0112, 0.4511],
[-0.6683, -0.9723, 2.4026]])
```

Addition: syntax 2

```
print(torch.add(x, y))
```

Out:

```
tensor([[ 0.6630, -0.9238, 0.7862],
[-0.6723, -0.8995, 0.5601],
[ 1.2930, -0.6163, 0.0968],
[ 0.6110, 2.0112, 0.4511],
[-0.6683, -0.9723, 2.4026]])
```

Addition: providing an output tensor as argument

```
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
```

Out:

```
tensor([[ 0.6630, -0.9238, 0.7862],
[-0.6723, -0.8995, 0.5601],
[ 1.2930, -0.6163, 0.0968],
[ 0.6110, 2.0112, 0.4511],
[-0.6683, -0.9723, 2.4026]])
```

Addition: in-place

```
# adds x to y
y.add_(x)
print(y)
```

Out:

```
tensor([[ 0.6630, -0.9238, 0.7862],
[-0.6723, -0.8995, 0.5601],
[ 1.2930, -0.6163, 0.0968],
[ 0.6110, 2.0112, 0.4511],
[-0.6683, -0.9723, 2.4026]])
```

Note

Any operation that mutates a tensor in-place is post-fixed with an `_`

.
For example: `x.copy_(y)`

, `x.t_()`

, will change `x`

.

You can use standard NumPy-like indexing with all bells and whistles!

```
print(x[:, 1])
```

Out:

```
tensor([-1.6584, -1.7741, -0.6516, 1.7497, -1.2869])
```

Resizing: If you want to resize/reshape tensor, you can use `torch.view`

:

```
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
```

Out:

```
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
```

If you have a one element tensor, use `.item()`

to get the value as a
Python number

```
x = torch.randn(1)
print(x)
print(x.item())
```

Out:

```
tensor([-1.1961])
-1.1961029767990112
```

**Read later:**

100+ Tensor operations, including transposing, indexing, slicing, mathematical operations, linear algebra, random numbers, etc., are described here.

## NumPy Bridge¶

Converting a Torch Tensor to a NumPy array and vice versa is a breeze.

The Torch Tensor and NumPy array will share their underlying memory locations (if the Torch Tensor is on CPU), and changing one will change the other.

### Converting a Torch Tensor to a NumPy Array¶

```
a = torch.ones(5)
print(a)
```

Out:

```
tensor([1., 1., 1., 1., 1.])
```

```
b = a.numpy()
print(b)
```

Out:

```
[1. 1. 1. 1. 1.]
```

See how the numpy array changed in value.

```
a.add_(1)
print(a)
print(b)
```

Out:

```
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
```

### Converting NumPy Array to Torch Tensor¶

See how changing the np array changed the Torch Tensor automatically

```
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
```

Out:

```
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
```

All the Tensors on the CPU except a CharTensor support converting to NumPy and back.

## CUDA Tensors¶

Tensors can be moved onto any device using the `.to`

method.

```
# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
```

Out:

```
tensor([-0.1961], device='cuda:0')
tensor([-0.1961], dtype=torch.float64)
```

**Total running time of the script:** ( 0 minutes 6.797 seconds)