Stochastic Gradient Descent: Theory and Implementation in Python

Introduction

Welcome! We're about to explore Stochastic Gradient Descent (SGD), a pivotal optimization algorithm. SGD, a variant of Gradient Descent, is renowned for its efficiency with large datasets due to its unique stochastic nature. Stochastic means “random” and is the opposite of deterministic.  A deterministic algorithm runs the same every time, but a stochastic one introduces a randomness. Our journey includes understanding SGD, its theoretical concepts, and implementing it in Python.

Understanding Stochastic Gradient Descent

SGD starts by understanding its structure. Unlike Gradient Descent, SGD calculates an estimate of the gradient using a randomly selected single data point, not the entire dataset. Consequently, SGD is highly efficient for large datasets.

While the efficient handling of large datasets by SGD is a blessing, its stochasticity can often lead to a slightly noisier process for convergence, resulting in the model not settling at an absolute minimum.

Defining Data

We are going to use this simple example of data:

Python
# Importing Necessary Library
import numpy as np

# Linear regression problem
X = np.array([0, 1, 2, 3, 4, 5]) 
Y = np.array([0, 1.1, 1.9, 3, 4.2, 5.2])  

Math Behind

In terms of math, SGD can be formulated as follows. Imagine we are looking for a best-fit line, setting the parameters of the familiar y=mx+by = mx + b equation. Remember, mm is the slope and bb is the y-intercept. Then:

m′=m−2α⋅((mxi+b)−yi)⋅xim' = m - 2\alpha \cdot ((mx_i + b) - y_i) \cdot x_i

b′=b−2α⋅((mxi+b)−yi)b' = b - 2\alpha \cdot ((mx_i + b) - y_i)

where:

  • mm and bb are the initial values of your parameters
  • m′m' and b′b' are the updated parameters
  • xix_i is a particular feature of your training set
  • yiy_i is the actual output for the given feature xix_i
  • α\alpha is the learning rate

These formulas represent the update rules for parameters mm and bb. Here, the term (mxi+b)−yi(mx_i+ b) - y_i presents the difference between the actual data point and the initial model mxi+bmx_i + b prediction. Multiplying it with a specific feature xix_i and averaging over all samples provide the gradient for parameter mm. The same principle applies to parameter bb, but without multiplication by xix_i, as bb is the bias term.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal