# Introduction to Deep Learning with PyTorch

In this notebook, you'll get introduced to [PyTorch](http://pytorch.org/), a framework for building and training neural networks. PyTorch in a lot of ways behaves like the arrays you love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation!) and another module specifically for building neural networks. All together, PyTorch ends up being more coherent with Python and the Numpy/Scipy stack compared to TensorFlow and other frameworks.



## Neural Networks

Deep Learning is based on artificial neural networks which have been around in some form since the late 1950s. The networks are built from individual parts approximating neurons, typically called units or simply "neurons." Each unit has some number of weighted inputs. These weighted inputs are summed together (a linear combination) then passed through an activation function to get the unit's output.



Mathematically this looks like: 

$$
\begin{align}
y &= f(w_1 x_1 + w_2 x_2 + b) \\
y &= f\left(\sum_i w_i x_i \right)
\end{align}
$$

With vectors this is the dot/inner product of two vectors:

$$
h = \begin{bmatrix}
x_1 \, x_2 \cdots  x_n
\end{bmatrix}
\cdot 
\begin{bmatrix}
           w_1 \\
           w_2 \\
           \vdots \\
           w_n
\end{bmatrix}
$$

### Stack them up!

We can assemble these unit neurons into layers and stacks, into a network of neurons. The output of one layer of neurons becomes the input for the next layer. With multiple input units and output units, we now need to express the weights as a matrix.



We can express this mathematically with matrices again and use matrix multiplication to get linear combinations for each unit in one operation. For example, the hidden layer ($h_1$ and $h_2$ here) can be calculated 

$$
\vec{h} = [h_1 \, h_2] = 
\begin{bmatrix}
x_1 \, x_2 \cdots \, x_n
\end{bmatrix}
\cdot 
\begin{bmatrix}
           w_{11} & w_{12} \\
           w_{21} &w_{22} \\
           \vdots &\vdots \\
           w_{n1} &w_{n2}
\end{bmatrix}
$$

The output for this small network is found by treating the hidden layer as inputs for the output unit. The network output is expressed simply

$$
y =  f_2 \! \left(\, f_1 \! \left(\vec{x} \, \mathbf{W_1}\right) \mathbf{W_2} \right)
$$

## Tensors

It turns out neural network computations are just a bunch of linear algebra operations on *tensors*, a generalization of matrices. A vector is a 1-dimensional tensor, a matrix is a 2-dimensional tensor, an array with three indices is a 3-dimensional tensor (RGB color images for example). The fundamental data structure for neural networks are tensors and PyTorch (as well as pretty much every other deep learning framework) is built around tensors.



With the basics covered, it's time to explore how we can use PyTorch to build a simple neural network.


```python
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
```

    Python version
    3.6.5 | packaged by conda-forge | (default, Apr  6 2018, 13:44:09) 
    [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]
    Version info.
    sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)



```python
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import numpy as np
import torch

import helper
```

First, let's see how we work with PyTorch tensors. These are the fundamental data structures of neural networks and PyTorch, so it's imporatant to understand how these work.


```python
x = torch.rand(3, 2)
x
```




    tensor([[ 0.5249,  0.2378],
            [ 0.1303,  0.2541],
            [ 0.9113,  0.7750]])




```python
y = torch.ones(x.size())
y
```




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




```python
z = x + y
z
```




    tensor([[ 1.5249,  1.2378],
            [ 1.1303,  1.2541],
            [ 1.9113,  1.7750]])



In general PyTorch tensors behave similar to Numpy arrays. They are zero indexed and support slicing.


```python
z[0]
```




    tensor([ 1.5249,  1.2378])




```python
z[:, 1:]
```




    tensor([[ 1.2378],
            [ 1.2541],
            [ 1.7750]])



Tensors typically have two forms of methods, 
- one method that returns another tensor and 
- another method that performs the operation in place. That is, the values in memory for that tensor are changed without creating a new tensor. In-place functions are always followed by an underscore, for example `z.add()` and `z.add_()`.


```python
# Return a new tensor z + 1
z.add(1)
```




    tensor([[ 2.5249,  2.2378],
            [ 2.1303,  2.2541],
            [ 2.9113,  2.7750]])




```python
# z tensor is unchanged
z
```




    tensor([[ 1.5249,  1.2378],
            [ 1.1303,  1.2541],
            [ 1.9113,  1.7750]])




```python
# Add 1 and update z tensor in-place
z.add_(1)
```




    tensor([[ 2.5249,  2.2378],
            [ 2.1303,  2.2541],
            [ 2.9113,  2.7750]])




```python
# z has been updated
z
```




    tensor([[ 2.5249,  2.2378],
            [ 2.1303,  2.2541],
            [ 2.9113,  2.7750]])



### Reshaping

Reshaping tensors is a really common operation. First to get the size and shape of a tensor use `.size()`. Then, to reshape a tensor, use `.resize_()`. Notice the underscore, reshaping is an in-place operation.


```python
z.size()
```




    torch.Size([3, 2])




```python
z.resize_(2, 3)
```




    tensor([[ 2.5249,  2.2378,  2.1303],
            [ 2.2541,  2.9113,  2.7750]])




```python
z
```




    tensor([[ 2.5249,  2.2378,  2.1303],
            [ 2.2541,  2.9113,  2.7750]])



## Numpy to Torch and back

Converting between Numpy arrays and Torch tensors is super simple and useful. To create a tensor from a Numpy array, use `torch.from_numpy()`. To convert a tensor to a Numpy array, use the `.numpy()` method.


```python
a = np.random.rand(4,3)
a
```




    array([[0.31670837, 0.82964753, 0.57837596],
           [0.28175374, 0.62455649, 0.73768427],
           [0.04358543, 0.92271407, 0.81054312],
           [0.30038343, 0.42245814, 0.2019588 ]])




```python
b = torch.from_numpy(a)
b
```




    tensor([[ 0.3167,  0.8296,  0.5784],
            [ 0.2818,  0.6246,  0.7377],
            [ 0.0436,  0.9227,  0.8105],
            [ 0.3004,  0.4225,  0.2020]], dtype=torch.float64)




```python
b.numpy()
```




    array([[0.31670837, 0.82964753, 0.57837596],
           [0.28175374, 0.62455649, 0.73768427],
           [0.04358543, 0.92271407, 0.81054312],
           [0.30038343, 0.42245814, 0.2019588 ]])



The memory is shared between the Numpy array and Torch tensor, so if you change the values in-place of one object, the other will change as well.


```python
# Multiply PyTorch Tensor by 2, in place
b.mul_(2)
```




    tensor([[ 0.6334,  1.6593,  1.1568],
            [ 0.5635,  1.2491,  1.4754],
            [ 0.0872,  1.8454,  1.6211],
            [ 0.6008,  0.8449,  0.4039]], dtype=torch.float64)




```python
# Numpy array matches new values from Tensor
a
```




    array([[0.63341675, 1.65929505, 1.15675192],
           [0.56350749, 1.24911298, 1.47536853],
           [0.08717086, 1.84542815, 1.62108625],
           [0.60076685, 0.84491629, 0.40391761]])




```python

```

24dd361ba01a7e8a9ab4c8a897de365c66ec5e23
ipynb
Jupyter Notebook
Part 01 - Tensors in PyTorch.ipynb
yankang18/pytorch_deep_learning
88e5f17c3b89a4987fd1aae520cf33fc78eec61f
MIT
2020-05-21T16:18:38.000Z
2020-06-05T01:30:08.000Z
Part 01 - Tensors in PyTorch.ipynb
yankang18/pytorch_deep_learning
88e5f17c3b89a4987fd1aae520cf33fc78eec61f
MIT
Part 01 - Tensors in PyTorch.ipynb
yankang18/pytorch_deep_learning
88e5f17c3b89a4987fd1aae520cf33fc78eec61f
MIT
Qwen/Qwen-72B
1. YES
2. YES