Working through linear regression from two angles: the iterative updates of gradient descent and the normal equation for ordinary least squares, with derivations and notes on when to use each.
Ying Yao 3 min read
Introduction
Gradient descent is a popular method applied almost everywhere in machine learning. But back to the period
that traditional mathematics rules the world, ordinary least square is the fundamental of
solving linear problem. Therefore, my motivation of writing this blog is to figure out the
similarity and difference of these two methods.
Hopefully after this, we will have better understanding on the aspect of both theory and experiments.
Theory
While I was reviewing Machine Learning by Andrew Ng,
the course skipped the proof part of OLS, by default thinking that we have sufficient matrix knowledge (do we? lol).
So, I'd like to include the proof here.
First, let's introduce some terminologies and notations. Consider a multiple linear regression:
where
θ=θ0θ1⋮θn,
x(i)=1x1(i)x2(i)⋮xn(i),
y=y1y2⋮ym
y is the target, hθ(x(i)) is the hypothesis function,
m is number of training samples / observations, n is number of features, e.g. x(i) is the ith training sample,
xj(i) is the jth feature value of ith training sample.
Given the cost function:
J(θ)=2m1i=1∑m(hθ(x(i))−yi)2
The objective is to estimate parameters θ, so that hypothesis function can have the minimum cost.
Gradient Descent
Since the cost function is a convex bowl-shaped graph, let's use a 2-dimension projection between J and θi
to explain how the algorithm works.
In order to get the minimum point, the algorithm will start from a higher point θi, using learning rate and derivatives / slope
through many iterations until it gets there. Both derivaties ∂θ∂J and learning rate α
will impact on how fast the algorithm goes until it reaches the bottom. If α is too large, it can bring in divergent problem too.
Because of this, normalization and wisely choose α within the model becomes important.
Under most situation, you can choose to use either ordinary least square or gradient descent. With small dataset
or relatively small number of features (~<104), OLS is preferred. However, if features # is too large,
should consider using gradient descent as it would compute faster.
GD requires to choose α and do iteration, but OLS doesn't
OLS requires to compute (XTX)−1, which have rare cases that matrix is non-invertible,
so you may have to reduce dimensions or avoid multicollinearity