Stochastic Gradient Descent: Theory and Implementation in C++

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 C++.

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:

C++
#include <vector>
#include <random>

// Linear regression problem
std::vector<double> X = {0, 1, 2, 3, 4, 5};
std::vector<double> Y = {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 in Stochastic Gradient Descent. Here, the term ((mxi+b)−yi)((mx_i + b) - y_i) is the difference between the model's prediction and the actual value for a single data point. For the slope mm, this difference is multiplied by the feature xix_i of the selected sample. For the intercept bb, the difference is used directly. In SGD, these updates are performed using only one randomly chosen data point at each iteration, making the process faster but noisier compared to Batch Gradient Descent, which averages the gradients over all samples.

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