In [1]:
%matplotlib inline
from fastai import *


In this part of the lecture we explain Stochastic Gradient Descent (SGD) which is an optimization method commonly used in neural networks. We will illustrate the concepts with concrete examples.

# Linear Regression problem¶

The goal of linear regression is to fit a line to a set of points.

In [2]:
n = 100

In [5]:
x = torch.ones(n, 2)
x[:, 0].uniform_(-1., 1)
x[:5]

Out[5]:
tensor([[-0.6881,  1.0000],
[ 0.5168,  1.0000],
[-0.6775,  1.0000],
[-0.8571,  1.0000],
[ 0.2521,  1.0000]])
In [4]:
a = tensor(3.,2); a

Out[4]:
tensor([3., 2.])
In [47]:
a = tensor(3., 2)
a

Out[47]:
tensor([3., 2.])
In [56]:
y = x@a + torch.rand(n)

In [61]:
plt.scatter(x[:,0], y);


You want to find parameters (weights) a such that you minimize the error between the points and the line x@a. Note that here a is unknown. For a regression problem the most common error function or loss function is the mean squared error.

In [62]:
def mse(y_hat, y): return ((y_hat-y)**2).mean()


Suppose we believe a = (-1.0,1.0) then we can compute y_hat which is our prediction and then compute our error.

In [63]:
a = tensor(-1.,1)

In [64]:
y_hat = x@a
mse(y_hat, y)

Out[64]:
tensor(7.6210)
In [65]:
plt.scatter(x[:,0],y)
plt.scatter(x[:,0],y_hat);


So far we have specified the model (linear regression) and the evaluation criteria (or loss function). Now we need to handle optimization; that is, how do we find the best values for a? How do we find the best fitting linear regression.

We would like to find the values of a that minimize mse_loss.

Gradient descent is an algorithm that minimizes functions. Given a function defined by a set of parameters, gradient descent starts with an initial set of parameter values and iteratively moves toward a set of parameter values that minimize the function. This iterative minimization is achieved by taking steps in the negative direction of the function gradient.

Here is gradient descent implemented in PyTorch.

In [67]:
a = nn.Parameter(a); a

Out[67]:
Parameter containing:
tensor([-1.,  1.], requires_grad=True)
In [68]:
def update():
y_hat = x@a
loss = mse(y, y_hat)
if t % 10 == 0: print(loss)
loss.backward()

In [69]:
lr = 1e-1
for t in range(100): update()

tensor(7.6210, grad_fn=<MeanBackward1>)

In [70]:
plt.scatter(x[:,0],y)
plt.scatter(x[:,0],x@a);


## Animate it!¶

In [71]:
from matplotlib import animation, rc
rc('animation', html='jshtml')

In [74]:
a = nn.Parameter(tensor(-1.,1))

fig = plt.figure()
plt.scatter(x[:,0], y, c='orange')
line, = plt.plot(x[:,0], x@a)
plt.close()

def animate(i):
update()
line.set_ydata(x@a)
return line,

animation.FuncAnimation(fig, animate, np.arange(0, 100), interval=20)

Out[74]:

Once Loop Reflect