# Derivation of the Normal Equation for Linear Regression

Join the DZone community and get the full member experience.

Join For Free

i was going through the coursera "machine learning" course, and in the section on multivariate linear regression something caught my eye. andrew ng presented the normal equation as an analytical solution to the linear regression problem with a least-squares cost function. he mentioned that in some cases (such as for small feature sets) using it is more effective than applying gradient descent; unfortunately, he left its derivation out.

here i want to show how the normal equation is derived.

first, some terminology. the following symbols are compatible with the machine learning course, not with the exposition of the normal equation on wikipedia and other sites - semantically it's all the same, just the symbols are different.

given the hypothesis function:

we'd like to minimize the least-squares cost:

where is the i-th sample (from a set of m samples) and is the i-th expected result.

to proceed, we'll represent the problem in matrix notation; this is natural, since we essentially have a system of linear equations here. the regression coefficients we're looking for are the vector:

each of the m input samples is similarly a column vector with n+1 rows, being 1 for convenience. so we can now rewrite the hypothesis function as:

when this is summed over all samples, we can dip further into matrix notation. we'll define the "design matrix" x (uppercase x) as a matrix of m rows, in which each row is the i-th sample (the vector ). with this, we can rewrite the least-squares cost as following, replacing the explicit sum by matrix multiplication:

now, using some matrix transpose identities, we can simplify this a bit. i'll throw the part away since we're going to compare a derivative to zero anyway:

note that is a vector, and so is y. so when we multiply one by another, it doesn't matter what the order is (as long as the dimensions work out). so we can further simplify:

recall that here is our unknown. to find where the above function has a minimum, we will derive by and compare to 0. deriving by a vector may feel uncomfortable, but there's nothing to worry about. recall that here we only use matrix notation to conveniently represent a system of linear formulae. so we derive by each component of the vector, and then combine the resulting derivatives into a vector again. the result is:

or:

now, assuming that the matrix is invertible, we can multiply both sides by and get:

which is the normal equation.

Published at DZone with permission of Eli Bendersky. See the original article here.

Opinions expressed by DZone contributors are their own.

Comments