Lecture 3: Locally Weighted Regression and Logistic Regression
Stanford CS229 lecture 3 notes: Locally Weighted Regression and Logistic Regression.
- cs229
- machine-learning
- course-notes
On this page
Why least squares? The probabilistic view#
Why should we use the squared error? Why not absolute error or something else? Here's a justification.
Assume the target is the linear prediction plus some noise:
That means . Now write the likelihood of the data and take the log:
Maximizing this is the exact same as minimizing the sum of squared errors. So least squares is maximum likelihood under Gaussian noise. Nice.
Parametric vs Non-parametric#
- Parametric: fixed number of parameters, and once trained, you can throw away the training data (linear regression).
- Non-parametric: the number of parameters grows with the training set size, so you need to keep the data around.
Locally Weighted Regression (LWR)#
Problem: if the data isn't linear, a straight line fits badly, and you'd have to pick features by hand.
The idea: to make a prediction at a point , only look at the training examples near , and fit a line just to those.
For each query point , fit to minimize:
where the weights are:
- If is close to , the weight is about 1.
- If it's far, the weight is about 0.
is the bandwidth. Small means only very close points matter (wiggly fit, risk of overfitting). Big means more points matter (smoother, closer to plain linear regression).
The downside is that you have to refit for every prediction, and you keep the whole training set. It's great for small, low dimensional datasets.
Classification and Logistic Regression#
Now . Using linear regression for this is a bad idea (one far away outlier can drag the line and mess up the threshold). Plus would output values way above 1 or below 0.
So we choose:
where is the sigmoid (logistic) function. It squashes everything into .
1 | ______
| /
.5 | /
| /
0 |_____/
+---------------- zWe interpret the output as a probability:
Combined: .
Fitting it#
Maximize the log likelihood:
Gradient ascent (since we're maximizing):
Wait, that looks identical to the linear regression update! It is, in form. The only difference is that is now the sigmoid. This isn't a coincidence, and we'll see why in the lecture on GLMs.
Newton's Method#
A faster way to maximize . To find where , Newton's method repeatedly approximates the function with a tangent line and jumps to where that line hits zero:
For a vector of parameters:
where is the Hessian (matrix of second derivatives).
- Converges in very few iterations (quadratic convergence, the number of correct digits roughly doubles each step).
- Each iteration is expensive, because you need to compute and invert an matrix.
So Newton's method is great when is small (say, up to a few thousand), and a pain when it's huge.