0% found this document useful (0 votes)
9 views69 pages

CS229

The document discusses supervised learning, particularly focusing on linear regression using housing price data as an example. It explains the concepts of input features, target variables, training sets, and the learning algorithm, including methods like batch and stochastic gradient descent for minimizing the cost function. Additionally, it introduces matrix derivatives and the normal equations as alternative approaches to minimize the cost function without iterative algorithms.

Uploaded by

simthandesoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views69 pages

CS229

The document discusses supervised learning, particularly focusing on linear regression using housing price data as an example. It explains the concepts of input features, target variables, training sets, and the learning algorithm, including methods like batch and stochastic gradient descent for minimizing the cost function. Additionally, it introduces matrix derivatives and the normal equations as alternative approaches to minimize the cost function without iterative algorithms.

Uploaded by

simthandesoke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

CS229 Lecture notes

Andrew Ng

Supervised learning
Lets start by talking about a few examples of supervised learning problems.
Suppose we have a dataset giving the living areas and prices of 47 houses
from Portland, Oregon:
Living area (feet2 ) Price (1000$s)
2104 400
1600 330
2400 369
1416 232
3000 540
.. ..
. .
We can plot this data:
housing prices

1000

900

800

700

600
price (in $1000)

500

400

300

200

100

500 1000 1500 2000 2500 3000 3500 4000 4500 5000
square feet

Given data like this, how can we learn to predict the prices of other houses
in Portland, as a function of the size of their living areas?

1
CS229 Winter 2003 2

To establish notation for future use, we’ll use x(i) to denote the “input”
variables (living area in this example), also called input features, and y (i)
to denote the “output” or target variable that we are trying to predict
(price). A pair (x(i) , y (i) ) is called a training example, and the dataset
that we’ll be using to learn—a list of m training examples {(x(i) , y (i) ); i =
1, . . . , m}—is called a training set. Note that the superscript “(i)” in the
notation is simply an index into the training set, and has nothing to do with
exponentiation. We will also use X denote the space of input values, and Y
the space of output values. In this example, X = Y = R.
To describe the supervised learning problem slightly more formally, our
goal is, given a training set, to learn a function h : X 7→ Y so that h(x) is a
“good” predictor for the corresponding value of y. For historical reasons, this
function h is called a hypothesis. Seen pictorially, the process is therefore
like this:

Training
set

Learning
algorithm

x h predicted y
(living area of (predicted price)
house.) of house)

When the target variable that we’re trying to predict is continuous, such
as in our housing example, we call the learning problem a regression prob-
lem. When y can take on only a small number of discrete values (such as
if, given the living area, we wanted to predict if a dwelling is a house or an
apartment, say), we call it a classification problem.
3

Part I
Linear Regression
To make our housing example more interesting, lets consider a slightly richer
dataset in which we also know the number of bedrooms in each house:
Living area (feet2 ) #bedrooms Price (1000$s)
2104 3 400
1600 3 330
2400 3 369
1416 2 232
3000 4 540
.. .. ..
. . .
(i)
Here, the x’s are two-dimensional vectors in R2 . For instance, x1 is the
(i)
living area of the i-th house in the training set, and x2 is its number of
bedrooms. (In general, when designing a learning problem, it will be up to
you to decide what features to choose, so if you are out in Portland gathering
housing data, you might also decide to include other features such as whether
each house has a fireplace, the number of bathrooms, and so on. We’ll say
more about feature selection later, but for now lets take the features as given.)
To perform supervised learning, we must decide how we’re going to rep-
resent functions/hypotheses h in a computer. As an initial choice, lets say
we decide to approximate y as a linear function of x:

hθ (x) = θ0 + θ1 x1 + θ2 x2

Here, the θi ’s are the parameters (also called weights) parameterizing the
space of linear functions mapping from X to Y. When there is no risk of
confusion, we will drop the θ subscript in hθ (x), and write it more simply as
h(x). To simplify our notation, we also introduce the convention of letting
x0 = 1 (this is the intercept term), so that
n
X
h(x) = θi xi = θT x,
i=0

where on the right-hand side above we are viewing θ and x both as vectors,
and here n is the number of input variables (not counting x0 ).
Now, given a training set, how do we pick, or learn, the parameters θ?
One reasonable method seems to be to make h(x) close to y, at least for
4

the training examples we have. To formalize this, we will define a function


that measures, for each value of the θ’s, how close the h(x(i) )’s are to the
corresponding y (i) ’s. We define the cost function:
m
1X
J(θ) = (hθ (x(i) ) − y (i) )2 .
2 i=1

If you’ve seen linear regression before, you may recognize this as the familiar
least-squares cost function that gives rise to the ordinary least squares
regression model. Whether or not you have seen it previously, lets keep
going, and we’ll eventually show this to be a special case of a much broader
family of algorithms.

1 LMS algorithm
We want to choose θ so as to minimize J(θ). To do so, lets use a search
algorithm that starts with some “initial guess” for θ, and that repeatedly
changes θ to make J(θ) smaller, until hopefully we converge to a value of
θ that minimizes J(θ). Specifically, lets consider the gradient descent
algorithm, which starts with some initial θ, and repeatedly performs the
update:

θj := θj − α J(θ).
∂θj
(This update is simultaneously performed for all values of j = 0, . . . , n.)
Here, α is called the learning rate. This is a very natural algorithm that
repeatedly takes a step in the direction of steepest decrease of J.
In order to implement this algorithm, we have to work out what is the
partial derivative term on the right hand side. Lets first work it out for the
case of if we have only one training example (x, y), so that we can neglect
the sum in the definition of J. We have:
∂ ∂ 1
J(θ) = (hθ (x) − y)2
∂θj ∂θj 2
1 ∂
= 2 · (hθ (x) − y) · (hθ (x) − y)
2 ∂θj
n
!
∂ X
= (hθ (x) − y) · θi x i − y
∂θj i=0
= (hθ (x) − y) xj
5

For a single training example, this gives the update rule:1


 (i)
θj := θj + α y (i) − hθ (x(i) ) xj .

The rule is called the LMS update rule (LMS stands for “least mean squares”),
and is also known as the Widrow-Hoff learning rule. This rule has several
properties that seem natural and intuitive. For instance, the magnitude of
the update is proportional to the error term (y (i) − hθ (x(i) )); thus, for in-
stance, if we are encountering a training example on which our prediction
nearly matches the actual value of y (i) , then we find that there is little need
to change the parameters; in contrast, a larger change to the parameters will
be made if our prediction hθ (x(i) ) has a large error (i.e., if it is very far from
y (i) ).
We’d derived the LMS rule for when there was only a single training
example. There are two ways to modify this method for a training set of
more than one example. The first is replace it with the following algorithm:

Repeat until convergence {


 (i)
θj := θj + α m (i)
− hθ (x(i) ) xj
P
i=1 y (for every j).

The reader can easily verify that the quantity in the summation in the update
rule above is just ∂J(θ)/∂θj (for the original definition of J). So, this is
simply gradient descent on the original cost function J. This method looks
at every example in the entire training set on every step, and is called batch
gradient descent. Note that, while gradient descent can be susceptible
to local minima in general, the optimization problem we have posed here
for linear regression has only one global, and no other local, optima; thus
gradient descent always converges (assuming the learning rate α is not too
large) to the global minimum. Indeed, J is a convex quadratic function.
Here is an example of gradient descent as it is run to minimize a quadratic
function.
1
We use the notation “a := b” to denote an operation (in a computer program) in
which we set the value of a variable a to be equal to the value of b. In other words, this
operation overwrites a with the value of b. In contrast, we will write “a = b” when we are
asserting a statement of fact, that the value of a is equal to the value of b.
6

50

45

40

35

30

25

20

15

10

5 10 15 20 25 30 35 40 45 50

The ellipses shown above are the contours of a quadratic function. Also
shown is the trajectory taken by gradient descent, with was initialized at
(48,30). The x’s in the figure (joined by straight lines) mark the successive
values of θ that gradient descent went through.
When we run batch gradient descent to fit θ on our previous dataset,
to learn to predict housing price as a function of living area, we obtain
θ0 = 71.27, θ1 = 0.1345. If we plot hθ (x) as a function of x (area), along
with the training data, we obtain the following figure:
housing prices

1000

900

800

700

600
price (in $1000)

500

400

300

200

100

500 1000 1500 2000 2500 3000 3500 4000 4500 5000
square feet

If the number of bedrooms were included as one of the input features as well,
we get θ0 = 89.60, θ1 = 0.1392, θ2 = −8.738.
The above results were obtained with batch gradient descent. There is
an alternative to batch gradient descent that also works very well. Consider
the following algorithm:
7

Loop {

for i=1 to m, {
 (i)
θj := θj + α y (i) − hθ (x(i) ) xj (for every j).
}

In this algorithm, we repeatedly run through the training set, and each time
we encounter a training example, we update the parameters according to
the gradient of the error with respect to that single training example only.
This algorithm is called stochastic gradient descent (also incremental
gradient descent). Whereas batch gradient descent has to scan through
the entire training set before taking a single step—a costly operation if m is
large—stochastic gradient descent can start making progress right away, and
continues to make progress with each example it looks at. Often, stochastic
gradient descent gets θ “close” to the minimum much faster than batch gra-
dient descent. (Note however that it may never “converge” to the minimum,
and the parameters θ will keep oscillating around the minimum of J(θ); but
in practice most of the values near the minimum will be reasonably good
approximations to the true minimum.2 ) For these reasons, particularly when
the training set is large, stochastic gradient descent is often preferred over
batch gradient descent.

2 The normal equations


Gradient descent gives one way of minimizing J. Lets discuss a second way
of doing so, this time performing the minimization explicitly and without
resorting to an iterative algorithm. In this method, we will minimize J by
explicitly taking its derivatives with respect to the θj ’s, and setting them to
zero. To enable us to do this without having to write reams of algebra and
pages full of matrices of derivatives, lets introduce some notation for doing
calculus with matrices.
2
While it is more common to run stochastic gradient descent as we have described it
and with a fixed learning rate α, by slowly letting the learning rate α decrease to zero as
the algorithm runs, it is also possible to ensure that the parameters will converge to the
global minimum rather then merely oscillate around the minimum.
8

2.1 Matrix derivatives


For a function f : Rm×n 7→ R mapping from m-by-n matrices to the real
numbers, we define the derivative of f with respect to A to be:
 ∂f ∂f

∂A11
· · · ∂A 1n

∇A f (A) =  ... ... .. 



. 
∂f ∂f
∂Am1
··· ∂Amn

Thus, the gradient ∇A f (A) is itself an m-by-n matrix,


 whose (i, j)-element
A11 A12
is ∂f /∂Aij . For example, suppose A = is a 2-by-2 matrix, and
A21 A22
2×2
the function f : R 7→ R is given by
3
f (A) = A11 + 5A212 + A21 A22 .
2
Here, Aij denotes the (i, j) entry of the matrix A. We then have
 3 
10A12
∇A f (A) = 2 .
A22 A21
We also introduce the trace operator, written “tr.” For an n-by-n
(square) matrix A, the trace of A is defined to be the sum of its diagonal
entries: n
X
trA = Aii
i=1
If a is a real number (i.e., a 1-by-1 matrix), then tr a = a. (If you haven’t
seen this “operator notation” before, you should think of the trace of A as
tr(A), or as application of the “trace” function to the matrix A. It’s more
commonly written without the parentheses, however.)
The trace operator has the property that for two matrices A and B such
that AB is square, we have that trAB = trBA. (Check this yourself!) As
corollaries of this, we also have, e.g.,
trABC = trCAB = trBCA,
trABCD = trDABC = trCDAB = trBCDA.
The following properties of the trace operator are also easily verified. Here,
A and B are square matrices, and a is a real number:
trA = trAT
tr(A + B) = trA + trB
tr aA = atrA
9

We now state without proof some facts of matrix derivatives (we won’t
need some of these until later this quarter). Equation (4) applies only to
non-singular square matrices A, where |A| denotes the determinant of A. We
have:

∇A trAB = BT (1)
∇AT f (A) = (∇A f (A))T (2)
∇A trABAT C = CAB + C T AB T (3)
∇A |A| = |A|(A−1 )T . (4)

To make our matrix notation more concrete, let us now explain in detail the
meaning of the first of these equations. Suppose we have some fixed matrix
B ∈ Rn×m . We can then define a function f : Rm×n 7→ R according to
f (A) = trAB. Note that this definition makes sense, because if A ∈ Rm×n ,
then AB is a square matrix, and we can apply the trace operator to it; thus,
f does indeed map from Rm×n to R. We can then apply our definition of
matrix derivatives to find ∇A f (A), which will itself by an m-by-n matrix.
Equation (1) above states that the (i, j) entry of this matrix will be given by
the (i, j)-entry of B T , or equivalently, by Bji .
The proofs of Equations (1-3) are reasonably simple, and are left as an
exercise to the reader. Equations (4) can be derived using the adjoint repre-
sentation of the inverse of a matrix.3

2.2 Least squares revisited


Armed with the tools of matrix derivatives, let us now proceed to find in
closed-form the value of θ that minimizes J(θ). We begin by re-writing J in
matrix-vectorial notation.
Giving a training set, define the design matrix X to be the m-by-n
matrix (actually m-by-n + 1, if we include the intercept term) that contains
3
If we define A′ to be the matrix whose (i, j) element is (−1)i+j times the determinant
of the square matrix resulting from deleting row i and column j from A, then it can be
proved that A−1 = (A′ )T /|A|. (You can check that this is consistent with the standard
way of finding A−1 when A is a 2-by-2 matrix. If you want to see a proof of this more
general result, see an intermediate or advanced linear algebra text, such as Charles Curtis,
1991, Linear Algebra, Springer.) This
P shows that A′ = |A|(A−1 )T . Also, the determinant
of a matrix can be written |A| = j Aij Aij . Since (A′ )ij does not depend on Aij (as can

be seen from its definition), this implies that (∂/∂Aij )|A| = A′ij . Putting all this together
shows the result.
10

the training examples’ input values in its rows:


 
— (x(1) )T —
 — (x(2) )T — 
X= .. .
 
 . 
(m) T
— (x ) —

Also, let ~y be the m-dimensional vector containing all the target values from
the training set:  
y (1)
 y (2) 
~y =  ..  .
 
 . 
y (m)
Now, since hθ (x(i) ) = (x(i) )T θ, we can easily verify that
   
(x(1) )T θ y (1)
Xθ − ~y =  .. .. 
−
  
. . 
(x(m) )T θ y (m)
 
hθ (x(1) ) − y (1)
=  ..
.
 
.
(m) (m)
hθ (x ) − y
2
Thus, using the fact that for a vector z, we have that z T z =
P
i zi :

m
1 1X
(Xθ − ~y )T (Xθ − ~y ) = (hθ (x(i) ) − y (i) )2
2 2 i=1
= J(θ)

Finally, to minimize J, lets find its derivatives with respect to θ. Combining


Equations (2) and (3), we find that

∇AT trABAT C = B T AT C T + BAT C (5)


11

Hence,
1
∇θ J(θ) = ∇θ (Xθ − ~y )T (Xθ − ~y )
2
1
∇θ θT X T Xθ − θT X T ~y − ~y T Xθ + ~y T ~y

=
2
1
∇θ tr θT X T Xθ − θT X T ~y − ~y T Xθ + ~y T ~y

=
2
1
∇θ tr θT X T Xθ − 2tr ~y T Xθ

=
2
1
X T Xθ + X T Xθ − 2X T ~y

=
2
= X T Xθ − X T ~y

In the third step, we used the fact that the trace of a real number is just the
real number; the fourth step used the fact that trA = trAT , and the fifth
step used Equation (5) with AT = θ, B = B T = X T X, and C = I, and
Equation (1). To minimize J, we set its derivatives to zero, and obtain the
normal equations:
X T Xθ = X T ~y
Thus, the value of θ that minimizes J(θ) is given in closed form by the
equation
θ = (X T X)−1 X T ~y .

3 Probabilistic interpretation
When faced with a regression problem, why might linear regression, and
specifically why might the least-squares cost function J, be a reasonable
choice? In this section, we will give a set of probabilistic assumptions, under
which least-squares regression is derived as a very natural algorithm.
Let us assume that the target variables and the inputs are related via the
equation
y (i) = θT x(i) + ǫ(i) ,
where ǫ(i) is an error term that captures either unmodeled effects (such as
if there are some features very pertinent to predicting housing price, but
that we’d left out of the regression), or random noise. Let us further assume
that the ǫ(i) are distributed IID (independently and identically distributed)
according to a Gaussian distribution (also called a Normal distribution) with
12

mean zero and some variance σ 2 . We can write this assumption as “ǫ(i) ∼
N (0, σ 2 ).” I.e., the density of ǫ(i) is given by

(ǫ(i) )2
 
(i) 1
p(ǫ ) = √ exp − .
2πσ 2σ 2

This implies that

(y (i) − θT x(i) )2
 
(i) (i) 1
p(y |x ; θ) = √ exp − .
2πσ 2σ 2

The notation “p(y (i) |x(i) ; θ)” indicates that this is the distribution of y (i)
given x(i) and parameterized by θ. Note that we should not condition on θ
(“p(y (i) |x(i) , θ)”), since θ is not a random variable. We can also write the
distribution of y (i) as as y (i) | x(i) ; θ ∼ N (θT x(i) , σ 2 ).
Given X (the design matrix, which contains all the x(i) ’s) and θ, what
is the distribution of the y (i) ’s? The probability of the data is given by
p(~y |X; θ). This quantity is typically viewed a function of ~y (and perhaps X),
for a fixed value of θ. When we wish to explicitly view this as a function of
θ, we will instead call it the likelihood function:

L(θ) = L(θ; X, ~y ) = p(~y |X; θ).

Note that by the independence assumption on the ǫ(i) ’s (and hence also the
y (i) ’s given the x(i) ’s), this can also be written
m
Y
L(θ) = p(y (i) | x(i) ; θ)
i=1
m
(y (i) − θT x(i) )2
 
Y 1
= √ exp − .
i=1
2πσ 2σ 2

Now, given this probabilistic model relating the y (i) ’s and the x(i) ’s, what
is a reasonable way of choosing our best guess of the parameters θ? The
principal of maximum likelihood says that we should should choose θ so
as to make the data as high probability as possible. I.e., we should choose θ
to maximize L(θ).
Instead of maximizing L(θ), we can also maximize any strictly increasing
function of L(θ). In particular, the derivations will be a bit simpler if we
13

instead maximize the log likelihood ℓ(θ):

ℓ(θ) = log L(θ)


m
(y (i) − θT x(i) )2
 
Y 1
= log √ exp −
i=1
2πσ 2σ 2
m
(y (i) − θT x(i) )2
 
X 1
= log √ exp −
i=1
2πσ 2σ 2
m
1 1 1 X (i)
= m log √ − 2· (y − θT x(i) )2 .
2πσ σ 2 i=1

Hence, maximizing ℓ(θ) gives the same answer as minimizing


m
1 X (i)
(y − θT x(i) )2 ,
2 i=1

which we recognize to be J(θ), our original least-squares cost function.


To summarize: Under the previous probabilistic assumptions on the data,
least-squares regression corresponds to finding the maximum likelihood esti-
mate of θ. This is thus one set of assumptions under which least-squares re-
gression can be justified as a very natural method that’s just doing maximum
likelihood estimation. (Note however that the probabilistic assumptions are
by no means necessary for least-squares to be a perfectly good and rational
procedure, and there may—and indeed there are—other natural assumptions
that can also be used to justify it.)
Note also that, in our previous discussion, our final choice of θ did not
depend on what was σ 2 , and indeed we’d have arrived at the same result
even if σ 2 were unknown. We will use this fact again later, when we talk
about the exponential family and generalized linear models.

4 Locally weighted linear regression


Consider the problem of predicting y from x ∈ R. The leftmost figure below
shows the result of fitting a y = θ0 + θ1 x to a dataset. We see that the data
doesn’t really lie on straight line, and so the fit is not very good.
14

4.5 4.5 4.5

4 4 4

3.5 3.5 3.5

3 3 3

2.5 2.5 2.5


y

y
2 2 2

1.5 1.5 1.5

1 1 1

0.5 0.5 0.5

0 0 0
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
x x x

Instead, if we had added an extra feature x2 , and fit y = θ0 + θ1 x + θ2 x2 ,


then we obtain a slightly better fit to the data. (See middle figure) Naively, it
might seem that the more features we add, the better. However, there is also
a danger in adding too many features: P The rightmost figure is the result of
fitting a 5-th order polynomial y = 5j=0 θj xj . We see that even though the
fitted curve passes through the data perfectly, we would not expect this to
be a very good predictor of, say, housing prices (y) for different living areas
(x). Without formally defining what these terms mean, we’ll say the figure
on the left shows an instance of underfitting—in which the data clearly
shows structure not captured by the model—and the figure on the right is
an example of overfitting. (Later in this class, when we talk about learning
theory we’ll formalize some of these notions, and also define more carefully
just what it means for a hypothesis to be good or bad.)
As discussed previously, and as shown in the example above, the choice of
features is important to ensuring good performance of a learning algorithm.
(When we talk about model selection, we’ll also see algorithms for automat-
ically choosing a good set of features.) In this section, let us talk briefly talk
about the locally weighted linear regression (LWR) algorithm which, assum-
ing there is sufficient training data, makes the choice of features less critical.
This treatment will be brief, since you’ll get a chance to explore some of the
properties of the LWR algorithm yourself in the homework.
In the original linear regression algorithm, to make a prediction at a query
point x (i.e., to evaluate h(x)), we would:
1. Fit θ to minimize i (y (i) − θT x(i) )2 .
P

2. Output θT x.
In contrast, the locally weighted linear regression algorithm does the fol-
lowing:
1. Fit θ to minimize i w(i) (y (i) − θT x(i) )2 .
P

2. Output θT x.
15

Here, the w(i) ’s are non-negative valued weights. Intuitively, if w(i) is large
for a particular value of i, then in picking θ, we’ll try hard to make (y (i) −
θT x(i) )2 small. If w(i) is small, then the (y (i) − θT x(i) )2 error term will be
pretty much ignored in the fit.
A fairly standard choice for the weights is4

(x(i) − x)2
 
(i)
w = exp −
2τ 2

Note that the weights depend on the particular point x at which we’re trying
to evaluate x. Moreover, if |x(i) − x| is small, then w(i) is close to 1; and
if |x(i) − x| is large, then w(i) is small. Hence, θ is chosen giving a much
higher “weight” to the (errors on) training examples close to the query point
x. (Note also that while the formula for the weights takes a form that is
cosmetically similar to the density of a Gaussian distribution, the w(i) ’s do
not directly have anything to do with Gaussians, and in particular the w(i)
are not random variables, normally distributed or otherwise.) The parameter
τ controls how quickly the weight of a training example falls off with distance
of its x(i) from the query point x; τ is called the bandwidth parameter, and
is also something that you’ll get to experiment with in your homework.
Locally weighted linear regression is the first example we’re seeing of a
non-parametric algorithm. The (unweighted) linear regression algorithm
that we saw earlier is known as a parametric learning algorithm, because
it has a fixed, finite number of parameters (the θi ’s), which are fit to the
data. Once we’ve fit the θi ’s and stored them away, we no longer need to
keep the training data around to make future predictions. In contrast, to
make predictions using locally weighted linear regression, we need to keep
the entire training set around. The term “non-parametric” (roughly) refers
to the fact that the amount of stuff we need to keep in order to represent the
hypothesis h grows linearly with the size of the training set.

4
If x is vector-valued, this is generalized to be w(i) = exp(−(x(i) − x)T (x(i) − x)/(2τ 2 )),
or w(i) = exp(−(x(i) − x)T Σ−1 (x(i) − x)/2), for an appropriate choice of τ or Σ.
16

Part II
Classification and logistic
regression
Lets now talk about the classification problem. This is just like the regression
problem, except that the values y we now want to predict take on only
a small number of discrete values. For now, we will focus on the binary
classification problem in which y can take on only two values, 0 and 1.
(Most of what we say here will also generalize to the multiple-class case.)
For instance, if we are trying to build a spam classifier for email, then x(i)
may be some features of a piece of email, and y may be 1 if it is a piece
of spam mail, and 0 otherwise. 0 is also called the negative class, and 1
the positive class, and they are sometimes also denoted by the symbols “-”
and “+.” Given x(i) , the corresponding y (i) is also called the label for the
training example.

5 Logistic regression
We could approach the classification problem ignoring the fact that y is
discrete-valued, and use our old linear regression algorithm to try to predict
y given x. However, it is easy to construct examples where this method
performs very poorly. Intuitively, it also doesn’t make sense for hθ (x) to take
values larger than 1 or smaller than 0 when we know that y ∈ {0, 1}.
To fix this, lets change the form for our hypotheses hθ (x). We will choose
1
hθ (x) = g(θT x) = ,
1 + e−θT x
where
1
g(z) =
1 + e−z
is called the logistic function or the sigmoid function. Here is a plot
showing g(z):
17

0.9

0.8

0.7

0.6
g(z)
0.5

0.4

0.3

0.2

0.1

0
−5 −4 −3 −2 −1 0 1 2 3 4 5
z

Notice that g(z) tends towards 1 as z → ∞, and g(z) tends towards 0 as


z → −∞. Moreover, g(z), and hence also h(x), is always bounded between
0 and 1. AsP before, we are keeping the convention of letting x0 = 1, so that
θT x = θ0 + nj=1 θj xj .
For now, lets take the choice of g as given. Other functions that smoothly
increase from 0 to 1 can also be used, but for a couple of reasons that we’ll see
later (when we talk about GLMs, and when we talk about generative learning
algorithms), the choice of the logistic function is a fairly natural one. Before
moving on, here’s a useful property of the derivative of the sigmoid function,
which we write a g ′ :
d 1
g ′ (z) =
dz 1 + e−z
1
e−z

= −z 2
(1 + e )
 
1 1
= · 1−
(1 + e−z ) (1 + e−z )
= g(z)(1 − g(z)).

So, given the logistic regression model, how do we fit θ for it? Follow-
ing how we saw least squares regression could be derived as the maximum
likelihood estimator under a set of assumptions, lets endow our classification
model with a set of probabilistic assumptions, and then fit the parameters
via maximum likelihood.
18

Let us assume that

P (y = 1 | x; θ) = hθ (x)
P (y = 0 | x; θ) = 1 − hθ (x)

Note that this can be written more compactly as

p(y | x; θ) = (hθ (x))y (1 − hθ (x))1−y

Assuming that the m training examples were generated independently, we


can then write down the likelihood of the parameters as

L(θ) = p(~y | X; θ)
Ym
= p(y (i) | x(i) ; θ)
i=1
m
Y y(i) 1−y(i)
= hθ (x(i) ) 1 − hθ (x(i) )
i=1

As before, it will be easier to maximize the log likelihood:

ℓ(θ) = log L(θ)


Xm
= y (i) log h(x(i) ) + (1 − y (i) ) log(1 − h(x(i) ))
i=1

How do we maximize the likelihood? Similar to our derivation in the case


of linear regression, we can use gradient ascent. Written in vectorial notation,
our updates will therefore be given by θ := θ + α∇θ ℓ(θ). (Note the positive
rather than negative sign in the update formula, since we’re maximizing,
rather than minimizing, a function now.) Lets start by working with just
one training example (x, y), and take derivatives to derive the stochastic
gradient ascent rule:
 
∂ 1 1 ∂
ℓ(θ) = y − (1 − y) g(θT x)
∂θj T
g(θ x) 1 − g(θ x) ∂θj
T
 
1 1 ∂ T
= y − (1 − y) g(θT x)(1 − g(θT x) θ x
T
g(θ x) 1 − g(θ x)
T ∂θj
= y(1 − g(θT x)) − (1 − y)g(θT x) xj


= (y − hθ (x)) xj
19

Above, we used the fact that g ′ (z) = g(z)(1 − g(z)). This therefore gives us
the stochastic gradient ascent rule
 (i)
θj := θj + α y (i) − hθ (x(i) ) xj

If we compare this to the LMS update rule, we see that it looks identical; but
this is not the same algorithm, because hθ (x(i) ) is now defined as a non-linear
function of θT x(i) . Nonetheless, it’s a little surprising that we end up with
the same update rule for a rather different algorithm and learning problem.
Is this coincidence, or is there a deeper reason behind this? We’ll answer this
when get get to GLM models. (See also the extra credit problem on Q3 of
problem set 1.)

6 Digression: The perceptron learning algo-


rithm
We now digress to talk briefly about an algorithm that’s of some historical
interest, and that we will also return to later when we talk about learning
theory. Consider modifying the logistic regression method to “force” it to
output values that are either 0 or 1 or exactly. To do so, it seems natural to
change the definition of g to be the threshold function:

1 if z ≥ 0
g(z) =
0 if z < 0

If we then let hθ (x) = g(θT x) as before but using this modified definition of
g, and if we use the update rule
 (i)
θj := θj + α y (i) − hθ (x(i) ) xj .

then we have the perceptron learning algorithm.


In the 1960s, this “perceptron” was argued to be a rough model for how
individual neurons in the brain work. Given how simple the algorithm is, it
will also provide a starting point for our analysis when we talk about learning
theory later in this class. Note however that even though the perceptron may
be cosmetically similar to the other algorithms we talked about, it is actually
a very different type of algorithm than logistic regression and least squares
linear regression; in particular, it is difficult to endow the perceptron’s predic-
tions with meaningful probabilistic interpretations, or derive the perceptron
as a maximum likelihood estimation algorithm.
20

7 Another algorithm for maximizing ℓ(θ)


Returning to logistic regression with g(z) being the sigmoid function, lets
now talk about a different algorithm for minimizing ℓ(θ).
To get us started, lets consider Newton’s method for finding a zero of a
function. Specifically, suppose we have some function f : R 7→ R, and we
wish to find a value of θ so that f (θ) = 0. Here, θ ∈ R is a real number.
Newton’s method performs the following update:
f (θ)
θ := θ − ′ .
f (θ)
This method has a natural interpretation in which we can think of it as
approximating the function f via a linear function that is tangent to f at
the current guess θ, solving for where that linear function equals to zero, and
letting the next guess for θ be where that linear function is zero.
Here’s a picture of the Newton’s method in action:
60 60 60

50 50 50

40 40 40

30 30 30
f(x)

f(x)

f(x)

20 20 20

10 10 10

0 0 0

−10 −10 −10


1 1.5 2 2.5 3 3.5 4 4.5 5 1 1.5 2 2.5 3 3.5 4 4.5 5 1 1.5 2 2.5 3 3.5 4 4.5 5
x x x

In the leftmost figure, we see the function f plotted along with the line
y = 0. We’re trying to find θ so that f (θ) = 0; the value of θ that achieves this
is about 1.3. Suppose we initialized the algorithm with θ = 4.5. Newton’s
method then fits a straight line tangent to f at θ = 4.5, and solves for the
where that line evaluates to 0. (Middle figure.) This give us the next guess
for θ, which is about 2.8. The rightmost figure shows the result of running
one more iteration, which the updates θ to about 1.8. After a few more
iterations, we rapidly approach θ = 1.3.
Newton’s method gives a way of getting to f (θ) = 0. What if we want to
use it to maximize some function ℓ? The maxima of ℓ correspond to points
where its first derivative ℓ′ (θ) is zero. So, by letting f (θ) = ℓ′ (θ), we can use
the same algorithm to maximize ℓ, and we obtain update rule:
ℓ′ (θ)
θ := θ − ′′ .
ℓ (θ)
(Something to think about: How would this change if we wanted to use
Newton’s method to minimize rather than maximize a function?)
21

Lastly, in our logistic regression setting, θ is vector-valued, so we need to


generalize Newton’s method to this setting. The generalization of Newton’s
method to this multidimensional setting (also called the Newton-Raphson
method) is given by
θ := θ − H −1 ∇θ ℓ(θ).
Here, ∇θ ℓ(θ) is, as usual, the vector of partial derivatives of ℓ(θ) with respect
to the θi ’s; and H is an n-by-n matrix (actually, n + 1-by-n + 1, assuming
that we include the intercept term) called the Hessian, whose entries are
given by
∂ 2 ℓ(θ)
Hij = .
∂θi ∂θj
Newton’s method typically enjoys faster convergence than (batch) gra-
dient descent, and requires many fewer iterations to get very close to the
minimum. One iteration of Newton’s can, however, be more expensive than
one iteration of gradient descent, since it requires finding and inverting an
n-by-n Hessian; but so long as n is not too large, it is usually much faster
overall. When Newton’s method is applied to maximize the logistic regres-
sion log likelihood function ℓ(θ), the resulting method is also called Fisher
scoring.
22

Part III
Generalized Linear Models5
So far, we’ve seen a regression example, and a classification example. In the
regression example, we had y|x; θ ∼ N (µ, σ 2 ), and in the classification one,
y|x; θ ∼ Bernoulli(φ), where for some appropriate definitions of µ and φ as
functions of x and θ. In this section, we will show that both of these methods
are special cases of a broader family of models, called Generalized Linear
Models (GLMs). We will also show how other models in the GLM family
can be derived and applied to other classification and regression problems.

8 The exponential family


To work our way up to GLMs, we will begin by defining exponential family
distributions. We say that a class of distributions is in the exponential family
if it can be written in the form

p(y; η) = b(y) exp(η T T (y) − a(η)) (6)

Here, η is called the natural parameter (also called the canonical param-
eter) of the distribution; T (y) is the sufficient statistic (for the distribu-
tions we consider, it will often be the case that T (y) = y); and a(η) is the log
partition function. The quantity e−a(η) essentially plays the role of a nor-
malization constant, that makes sure the distribution p(y; η) sums/integrates
over y to 1.
A fixed choice of T , a and b defines a family (or set) of distributions that
is parameterized by η; as we vary η, we then get different distributions within
this family.
We now show that the Bernoulli and the Gaussian distributions are ex-
amples of exponential family distributions. The Bernoulli distribution with
mean φ, written Bernoulli(φ), specifies a distribution over y ∈ {0, 1}, so that
p(y = 1; φ) = φ; p(y = 0; φ) = 1 − φ. As we varying φ, we obtain Bernoulli
distributions with different means. We now show that this class of Bernoulli
distributions, ones obtained by varying φ, is in the exponential family; i.e.,
that there is a choice of T , a and b so that Equation (6) becomes exactly the
class of Bernoulli distributions.
5
The presentation of the material in this section takes inspiration from Michael I.
Jordan, Learning in graphical models (unpublished book draft), and also McCullagh and
Nelder, Generalized Linear Models (2nd ed.).
23

We write the Bernoulli distribution as:

p(y; φ) = φy (1 − φ)1−y
= exp(y log φ + (1 − y) log(1 − φ))
   
φ
= exp log y + log(1 − φ) .
1−φ

Thus, the natural parameter is given by η = log(φ/(1 − φ)). Interestingly, if


we invert this definition for η by solving for φ in terms of η, we obtain φ =
1/(1 + e−η ). This is the familiar sigmoid function! This will come up again
when we derive logistic regression as a GLM. To complete the formulation
of the Bernoulli distribution as an exponential family distribution, we also
have

T (y) = y
a(η) = − log(1 − φ)
= log(1 + eη )
b(y) = 1

This shows that the Bernoulli distribution can be written in the form of
Equation (6), using an appropriate choice of T , a and b.
Lets now move on to consider the Gaussian distribution. Recall that,
when deriving linear regression, the value of σ 2 had no effect on our final
choice of θ and hθ (x). Thus, we can choose an arbitrary value for σ 2 without
changing anything. To simplify the derivation below, lets set σ 2 = 1.6 We
then have:
 
1 1 2
p(y; µ) = √ exp − (y − µ)
2π 2
   
1 1 2 1 2
= √ exp − y · exp µy − µ
2π 2 2
6
If we leave σ 2 as a variable, the Gaussian distribution can also be shown to be in the
exponential family, where η ∈ R2 is now a 2-dimension vector that depends on both µ and
σ. For the purposes of GLMs, however, the σ 2 parameter can also be treated by considering
a more general definition of the exponential family: p(y; η, τ ) = b(a, τ ) exp((η T T (y) −
a(η))/c(τ )). Here, τ is called the dispersion parameter, and for the Gaussian, c(τ ) = σ 2 ;
but given our simplification above, we won’t need the more general definition for the
examples we will consider here.
24

Thus, we see that the Gaussian is in the exponential family, with

η = µ
T (y) = y
a(η) = µ2 /2
= η 2 /2

b(y) = (1/ 2π) exp(−y 2 /2).

There’re many other distributions that are members of the exponen-


tial family: The multinomial (which we’ll see later), the Poisson (for mod-
elling count-data; also see the problem set); the gamma and the exponen-
tial (for modelling continuous, non-negative random variables, such as time-
intervals); the beta and the Dirichlet (for distributions over probabilities);
and many more. In the next section, we will describe a general “recipe”
for constructing models in which y (given x and θ) comes from any of these
distributions.

9 Constructing GLMs
Suppose you would like to build a model to estimate the number y of cus-
tomers arriving in your store (or number of page-views on your website) in
any given hour, based on certain features x such as store promotions, recent
advertising, weather, day-of-week, etc. We know that the Poisson distribu-
tion usually gives a good model for numbers of visitors. Knowing this, how
can we come up with a model for our problem? Fortunately, the Poisson is an
exponential family distribution, so we can apply a Generalized Linear Model
(GLM). In this section, we will we will describe a method for constructing
GLM models for problems such as these.
More generally, consider a classification or regression problem where we
would like to predict the value of some random variable y as a function of
x. To derive a GLM for this problem, we will make the following three
assumptions about the conditional distribution of y given x and about our
model:
1. y | x; θ ∼ ExponentialFamily(η). I.e., given x and θ, the distribution of
y follows some exponential family distribution, with parameter η.
2. Given x, our goal is to predict the expected value of T (y) given x.
In most of our examples, we will have T (y) = y, so this means we
would like the prediction h(x) output by our learned hypothesis h to
25

satisfy h(x) = E[y|x]. (Note that this assumption is satisfied in the


choices for hθ (x) for both logistic regression and linear regression. For
instance, in logistic regression, we had hθ (x) = p(y = 1|x; θ) = 0 · p(y =
0|x; θ) + 1 · p(y = 1|x; θ) = E[y|x; θ].)

3. The natural parameter η and the inputs x are related linearly: η = θT x.


(Or, if η is vector-valued, then ηi = θiT x.)

The third of these assumptions might seem the least well justified of
the above, and it might be better thought of as a “design choice” in our
recipe for designing GLMs, rather than as an assumption per se. These
three assumptions/design choices will allow us to derive a very elegant class
of learning algorithms, namely GLMs, that have many desirable properties
such as ease of learning. Furthermore, the resulting models are often very
effective for modelling different types of distributions over y; for example, we
will shortly show that both logistic regression and ordinary least squares can
both be derived as GLMs.

9.1 Ordinary Least Squares


To show that ordinary least squares is a special case of the GLM family
of models, consider the setting where the target variable y (also called the
response variable in GLM terminology) is continuous, and we model the
conditional distribution of y given x as as a Gaussian N (µ, σ 2 ). (Here, µ
may depend x.) So, we let the ExponentialF amily(η) distribution above be
the Gaussian distribution. As we saw previously, in the formulation of the
Gaussian as an exponential family distribution, we had µ = η. So, we have

hθ (x) = E[y|x; θ]
= µ
= η
= θT x.

The first equality follows from Assumption 2, above; the second equality
follows from the fact that y|x; θ ∼ N (µ, σ 2 ), and so its expected value is given
by µ; the third equality follows from Assumption 1 (and our earlier derivation
showing that µ = η in the formulation of the Gaussian as an exponential
family distribution); and the last equality follows from Assumption 3.
26

9.2 Logistic Regression


We now consider logistic regression. Here we are interested in binary classifi-
cation, so y ∈ {0, 1}. Given that y is binary-valued, it therefore seems natural
to choose the Bernoulli family of distributions to model the conditional dis-
tribution of y given x. In our formulation of the Bernoulli distribution as
an exponential family distribution, we had φ = 1/(1 + e−η ). Furthermore,
note that if y|x; θ ∼ Bernoulli(φ), then E[y|x; θ] = φ. So, following a similar
derivation as the one for ordinary least squares, we get:

hθ (x) = E[y|x; θ]
= φ
= 1/(1 + e−η )
T
= 1/(1 + e−θ x )
T
So, this gives us hypothesis functions of the form hθ (x) = 1/(1 + e−θ x ). If
you are previously wondering how we came up with the form of the logistic
function 1/(1 + e−z ), this gives one answer: Once we assume that y condi-
tioned on x is Bernoulli, it arises as a consequence of the definition of GLMs
and exponential family distributions.
To introduce a little more terminology, the function g giving the distri-
bution’s mean as a function of the natural parameter (g(η) = E[T (y); η])
is called the canonical response function. Its inverse, g −1 , is called the
canonical link function. Thus, the canonical response function for the
Gaussian family is just the identify function; and the canonical response
function for the Bernoulli is the logistic function.7

9.3 Softmax Regression


Lets look at one more example of a GLM. Consider a classification problem
in which the response variable y can take on any one of k values, so y ∈
{1 2, . . . , k}. For example, rather than classifying email into the two classes
spam or not-spam—which would have been a binary classification problem—
we might want to classify it into three classes, such as spam, personal mail,
and work-related mail. The response variable is still discrete, but can now
take on more than two values. We will thus model it as distributed according
to a multinomial distribution.
7
Many texts use g to denote the link function, and g −1 to denote the response function;
but the notation we’re using here, inherited from the early machine learning literature,
will be more consistent with the notation used in the rest of the class.
27

Lets derive a GLM for modelling this type of multinomial data. To do


so, we will begin by expressing the multinomial as an exponential family
distribution.
To parameterize a multinomial over k possible outcomes, one could use
k parameters φ1 , . . . , φk specifying the probability of each of the outcomes.
However, these parameters would be redundant, or more formally, they would
not be independent (since knowing any Pk k − 1 of the φi ’s uniquely determines
the last one, as they must satisfy i=1 φi = 1). So, we will instead pa-
rameterize the multinomial with only kP − 1 parameters, φ1 , . . . , φk−1 , where
k−1
φi = p(y = i; φ), and p(y = k; φ) = 1 − i=1 φi . For notational convenience,
Pk−1
we will also let φk = 1 − i=1 φi , but we should keep in mind that this is
not a parameter, and that it is fully specified by φ1 , . . . , φk−1 .
To express the multinomial as an exponential family distribution, we will
define T (y) ∈ Rk−1 as follows:
         
1 0 0 0 0

 0 


 1 


 0 


 0 


 0 

T (1) = 
 0  , T (2) = 
  0  , T (3) = 
  1  , · · · , T (k−1) = 
  0  , T (k) = 
  0 ,

 ..   ..   ..   ..   .. 
 .   .   .   .   . 
0 0 0 1 0

Unlike our previous examples, here we do not have T (y) = y; also, T (y) is
now a k − 1 dimensional vector, rather than a real number. We will write
(T (y))i to denote the i-th element of the vector T (y).
We introduce one more very useful piece of notation. An indicator func-
tion 1{·} takes on a value of 1 if its argument is true, and 0 otherwise
(1{True} = 1, 1{False} = 0). For example, 1{2 = 3} = 0, and 1{3 =
5 − 2} = 1. So, we can also write the relationship between T (y) and y as
(T (y))i = 1{y = i}. (Before you continue reading, please make sure you un-
derstand why this is true!) Further, we have that E[(T (y))i ] = P (y = i) = φi .
We are now ready to show that the multinomial is a member of the
28

exponential family. We have:


1{y=1} 1{y=2} 1{y=k}
p(y; φ) = φ1 φ2 · · · φk
1− k−1
P
1{y=1} 1{y=2} 1{y=i}
= φ1 φ2 · · · φk i=1
1− k−1 (T (y))i
P
(T (y))1 (T (y))2
= φ1 φ2 · · · φk i=1
= exp((T (y))1 log(φ1 ) + (T (y))2 log(φ2 ) +
 Pk−1 
· · · + 1 − i=1 (T (y))i log(φk ))
= exp((T (y))1 log(φ1 /φk ) + (T (y))2 log(φ2 /φk ) +
· · · + (T (y))k−1 log(φk−1 /φk ) + log(φk ))
= b(y) exp(η T T (y) − a(η))
where
 
log(φ1 /φk )
 log(φ2 /φk ) 
η =  .. ,
 
 . 
log(φk−1 /φk )
a(η) = − log(φk )
b(y) = 1.
This completes our formulation of the multinomial as an exponential family
distribution.
The link function is given (for i = 1, . . . , k) by
φi
ηi = log .
φk
For convenience, we have also defined ηk = log(φk /φk ) = 0. To invert the
link function and derive the response function, we therefore have that
φi
eηi =
φk
φk eηi = φi (7)
k
X Xk
φk eηi = φi = 1
i=1 i=1
Pk
This implies that φk = 1/ i=1 eηi , which can be substituted back into Equa-
tion (7) to give the response function
eηi
φi = Pk
j=1 eηj
29

This function mapping from the η’s to the φ’s is called the softmax function.
To complete our model, we use Assumption 3, given earlier, that the ηi ’s
are linearly related to the x’s. So, have ηi = θiT x (for i = 1, . . . , k − 1),
where θ1 , . . . , θk−1 ∈ Rn+1 are the parameters of our model. For notational
convenience, we can also define θk = 0, so that ηk = θkT x = 0, as given
previously. Hence, our model assumes that the conditional distribution of y
given x is given by

p(y = i|x; θ) = φi
eηi
= Pk
j=1 eηj
T
eθi x
= Pk T (8)
j=1 eθj x

This model, which applies to classification problems where y ∈ {1, . . . , k}, is


called softmax regression. It is a generalization of logistic regression.
Our hypothesis will output

hθ (x) = E[T (y)|x; θ]


 
1{y = 1}
 1{y = 2} 
= E .. x; θ
 
 . 
1{y = k − 1}
 
φ1
 φ2 
=  .. 
 
 . 
φk−1
exp(θT x)
 
1
Pk
 j=1exp(θjT x) 
 exp(θ2T x) 
Pk T
j=1 exp(θj x)
 
= 
 ..
.

 . 
 T
exp(θk−1 x)

Pk T
j=1 exp(θj x)

In other words, our hypothesis will output the estimated probability that
p(y = i|x; θ), for every value of i = 1, . . . , k. (Even though hθ (x) as defined
above is only k − 1 dimensional, clearly p(y = k|x; θ) can be obtained as
Pk−1
1 − i=1 φi .)
30

Lastly, lets discuss parameter fitting. Similar to our original derivation of


ordinary least squares and logistic regression, if we have a training set of m
examples {(x(i) , y (i) ); i = 1, . . . , m} and would like to learn the parameters θi
of this model, we would begin by writing down the log-likelihood
m
X
ℓ(θ) = log p(y (i) |x(i) ; θ)
i=1
m k T x(i)
!1{y(i) =l}
X Y eθl
= log Pk T (i)
i=1 l=1 j=1 eθj x

To obtain the second line above, we used the definition for p(y|x; θ) given
in Equation (8). We can now obtain the maximum likelihood estimate of
the parameters by maximizing ℓ(θ) in terms of θ, using a method such as
gradient ascent or Newton’s method.
CS229 Lecture notes
Andrew Ng

Part IV
Generative Learning algorithms
So far, we’ve mainly been talking about learning algorithms that model
p(y|x; θ), the conditional distribution of y given x. For instance, logistic
regression modeled p(y|x; θ) as hθ (x) = g(θ T x) where g is the sigmoid func-
tion. In these notes, we’ll talk about a different type of learning algorithm.
Consider a classification problem in which we want to learn to distinguish
between elephants (y = 1) and dogs (y = 0), based on some features of
an animal. Given a training set, an algorithm like logistic regression or
the perceptron algorithm (basically) tries to find a straight line—that is, a
decision boundary—that separates the elephants and dogs. Then, to classify
a new animal as either an elephant or a dog, it checks on which side of the
decision boundary it falls, and makes its prediction accordingly.
Here’s a different approach. First, looking at elephants, we can build a
model of what elephants look like. Then, looking at dogs, we can build a
separate model of what dogs look like. Finally, to classify a new animal, we
can match the new animal against the elephant model, and match it against
the dog model, to see whether the new animal looks more like the elephants
or more like the dogs we had seen in the training set.
Algorithms that try to learn p(y|x) directly (such as logistic regression),
or algorithms that try to learn mappings directly from the space of inputs X
to the labels {0, 1}, (such as the perceptron algorithm) are called discrim-
inative learning algorithms. Here, we’ll talk about algorithms that instead
try to model p(x|y) (and p(y)). These algorithms are called generative
learning algorithms. For instance, if y indicates whether a example is a dog
(0) or an elephant (1), then p(x|y = 0) models the distribution of dogs’
features, and p(x|y = 1) models the distribution of elephants’ features.
After modeling p(y) (called the class priors) and p(x|y), our algorithm

1
2

can then use Bayes rule to derive the posterior distribution on y given x:
p(x|y)p(y)
p(y|x) = .
p(x)
Here, the denominator is given by p(x) = p(x|y = 1)p(y = 1) + p(x|y =
0)p(y = 0) (you should be able to verify that this is true from the standard
properties of probabilities), and thus can also be expressed in terms of the
quantities p(x|y) and p(y) that we’ve learned. Actually, if were calculating
p(y|x) in order to make a prediction, then we don’t actually need to calculate
the denominator, since
p(x|y)p(y)
arg max p(y|x) = arg max
y y p(x)
= arg max p(x|y)p(y).
y

1 Gaussian discriminant analysis


The first generative learning algorithm that we’ll look at is Gaussian discrim-
inant analysis (GDA). In this model, we’ll assume that p(x|y) is distributed
according to a multivariate normal distribution. Lets talk briefly about the
properties of multivariate normal distributions before moving on to the GDA
model itself.

1.1 The multivariate normal distribution


The multivariate normal distribution in n-dimensions, also called the multi-
variate Gaussian distribution, is parameterized by a mean vector µ ∈ Rn
and a covariance matrix Σ ∈ Rn×n , where Σ ≥ 0 is symmetric and positive
semi-definite. Also written “N (µ, Σ)”, its density is given by:
 
1 1 T −1
p(x; µ, Σ) = exp − (x − µ) Σ (x − µ) .
(2π)n/2 |Σ|1/2 2
In the equation above, “|Σ|” denotes the determinant of the matrix Σ.
For a random variable X distributed N (µ, Σ), the mean is (unsurpris-
ingly,) given by µ: Z
E[X] = x p(x; µ, Σ)dx = µ
x
The covariance of a vector-valued random variable Z is defined as Cov(Z) =
E[(Z − E[Z])(Z − E[Z])T ]. This generalizes the notion of the variance of a
3

real-valued random variable. The covariance can also be defined as Cov(Z) =


E[ZZ T ] − (E[Z])(E[Z])T . (You should be able to prove to yourself that these
two definitions are equivalent.) If X ∼ N (µ, Σ), then

Cov(X) = Σ.

Here’re some examples of what the density of a Gaussian distribution


look like:
0.25 0.25 0.25

0.2 0.2 0.2

0.15 0.15 0.15

0.1 0.1 0.1

0.05 0.05 0.05

3 3 3
2 2 2
3 3 3
1 2 1 2 1 2
0 1 0 1 0 1
−1 0 −1 0 −1 0
−1 −1 −1
−2 −2 −2
−2 −2 −2
−3 −3 −3 −3 −3 −3

The left-most figure shows a Gaussian with mean zero (that is, the 2x1
zero-vector) and covariance matrix Σ = I (the 2x2 identity matrix). A Gaus-
sian with zero mean and identity covariance is also called the standard nor-
mal distribution. The middle figure shows the density of a Gaussian with
zero mean and Σ = 0.6I; and in the rightmost figure shows one with , Σ = 2I.
We see that as Σ becomes larger, the Gaussian becomes more “spread-out,”
and as it becomes smaller, the distribution becomes more “compressed.”
Lets look at some more examples.
0.25 0.25 0.25

0.2 0.2 0.2

0.15 0.15 0.15

0.1 0.1 0.1

0.05 0.05 0.05

3 3 3

2 2 2

1 1 1

0 0 0
3 3 3
−1 2 −1 2 −1 2
1 1 1
−2 0 −2 0 −2 0
−1 −1 −1
−3 −2 −3 −2 −3 −2
−3 −3 −3

The figures above show Gaussians with mean 0, and with covariance
matrices respectively
     
1 0 1 0.5 1 0.8
Σ= ; Σ= ; .Σ = .
0 1 0.5 1 0.8 1

The leftmost figure shows the familiar standard normal distribution, and we
see that as we increase the off-diagonal entry in Σ, the density becomes more
“compressed” towards the 45◦ line (given by x1 = x2 ). We can see this more
clearly when we look at the contours of the same three densities:
4

3 3 3

2 2 2

1 1 1

0 0 0

−1 −1 −1

−2 −2 −2

−3 −3 −3
−3 −2 −1 0 1 2 3 −3 −2 −1 0 1 2 3 −3 −2 −1 0 1 2 3

Here’s one last set of examples generated by varying Σ:


3 3 3

2 2 2

1 1 1

0 0 0

−1 −1 −1

−2 −2 −2

−3 −3 −3
−3 −2 −1 0 1 2 3 −3 −2 −1 0 1 2 3 −3 −2 −1 0 1 2 3

The plots above used, respectively,


     
1 -0.5 1 -0.8 3 0.8
Σ= ; Σ= ; .Σ = .
-0.5 1 -0.8 1 0.8 1
From the leftmost and middle figures, we see that by decreasing the diagonal
elements of the covariance matrix, the density now becomes “compressed”
again, but in the opposite direction. Lastly, as we vary the parameters, more
generally the contours will form ellipses (the rightmost figure showing an
example).
As our last set of examples, fixing Σ = I, by varying µ, we can also move
the mean of the density around.

0.25 0.25 0.25

0.2 0.2 0.2

0.15 0.15 0.15

0.1 0.1 0.1

0.05 0.05 0.05

3 3 3
2 2 2
3 3 3
1 2 1 2 1 2
0 1 0 1 0 1
−1 0 −1 0 −1 0
−1 −1 −1
−2 −2 −2
−2 −2 −2
−3 −3 −3 −3 −3 −3

The figures above were generated using Σ = I, and respectively


     
1 -0.5 -1
µ= ; µ= ; µ= .
0 0 -1.5
5

1.2 The Gaussian Discriminant Analysis model


When we have a classification problem in which the input features x are
continuous-valued random variables, we can then use the Gaussian Discrim-
inant Analysis (GDA) model, which models p(x|y) using a multivariate nor-
mal distribution. The model is:

y ∼ Bernoulli(φ)
x|y = 0 ∼ N (µ0 , Σ)
x|y = 1 ∼ N (µ1 , Σ)

Writing out the distributions, this is:

p(y) = φy (1 − φ)1−y
 
1 1 T −1
p(x|y = 0) = exp − (x − µ0 ) Σ (x − µ0 )
(2π)n/2 |Σ|1/2 2
 
1 1 T −1
p(x|y = 1) = exp − (x − µ1 ) Σ (x − µ1 )
(2π)n/2 |Σ|1/2 2

Here, the parameters of our model are φ, Σ, µ0 and µ1 . (Note that while
there’re two different mean vectors µ0 and µ1 , this model is usually applied
using only one covariance matrix Σ.) The log-likelihood of the data is given
by
m
Y
`(φ, µ0 , µ1 , Σ) = log p(x(i) , y (i) ; φ, µ0 , µ1 , Σ)
i=1
Ym
= log p(x(i) |y (i) ; µ0 , µ1 , Σ)p(y (i) ; φ).
i=1
6

By maximizing ` with respect to the parameters, we find the maximum like-


lihood estimate of the parameters (see problem set 1) to be:
m
1 X
φ = 1{y (i) = 1}
m i=1
Pm (i)
i=1 1{y = 0}x(i)
µ0 = P m
1{y (i) = 0}
Pm i=1 (i)
i=1 1{y = 1}x(i)
µ1 = P m (i) = 1}
i=1 1{y
m
1 X (i)
Σ = (x − µy(i) )(x(i) − µy(i) )T .
m i=1
Pictorially, what the algorithm is doing can be seen in as follows:
1

−1

−2

−3

−4

−5

−6

−7
−2 −1 0 1 2 3 4 5 6 7

Shown in the figure are the training set, as well as the contours of the
two Gaussian distributions that have been fit to the data in each of the
two classes. Note that the two Gaussians have contours that are the same
shape and orientation, since they share a covariance matrix Σ, but they have
different means µ0 and µ1 . Also shown in the figure is the straight line
giving the decision boundary at which p(y = 1|x) = 0.5. On one side of
the boundary, we’ll predict y = 1 to be the most likely outcome, and on the
other side, we’ll predict y = 0.

1.3 Discussion: GDA and logistic regression


The GDA model has an interesting relationship to logistic regression. If we
view the quantity p(y = 1|x; φ, µ0 , µ1 , Σ) as a function of x, we’ll find that it
7

can be expressed in the form


1
p(y = 1|x; φ, Σ, µ0 , µ1 ) = ,
1 + exp(−θ T x)

where θ is some appropriate function of φ, Σ, µ0 , µ1 .1 This is exactly the form


that logistic regression—a discriminative algorithm—used to model p(y =
1|x).
When would we prefer one model over another? GDA and logistic regres-
sion will, in general, give different decision boundaries when trained on the
same dataset. Which is better?
We just argued that if p(x|y) is multivariate gaussian (with shared Σ),
then p(y|x) necessarily follows a logistic function. The converse, however,
is not true; i.e., p(y|x) being a logistic function does not imply p(x|y) is
multivariate gaussian. This shows that GDA makes stronger modeling as-
sumptions about the data than does logistic regression. It turns out that
when these modeling assumptions are correct, then GDA will find better fits
to the data, and is a better model. Specifically, when p(x|y) is indeed gaus-
sian (with shared Σ), then GDA is asymptotically efficient. Informally,
this means that in the limit of very large training sets (large m), there is no
algorithm that is strictly better than GDA (in terms of, say, how accurately
they estimate p(y|x)). In particular, it can be shown that in this setting,
GDA will be a better algorithm than logistic regression; and more generally,
even for small training set sizes, we would generally expect GDA to better.
In contrast, by making significantly weaker assumptions, logistic regres-
sion is also more robust and less sensitive to incorrect modeling assumptions.
There are many different sets of assumptions that would lead to p(y|x) taking
the form of a logistic function. For example, if x|y = 0 ∼ Poisson(λ0 ), and
x|y = 1 ∼ Poisson(λ1 ), then p(y|x) will be logistic. Logistic regression will
also work well on Poisson data like this. But if we were to use GDA on such
data—and fit Gaussian distributions to such non-Gaussian data—then the
results will be less predictable, and GDA may (or may not) do well.
To summarize: GDA makes stronger modeling assumptions, and is more
data efficient (i.e., requires less training data to learn “well”) when the mod-
eling assumptions are correct or at least approximately correct. Logistic
regression makes weaker assumptions, and is significantly more robust to
deviations from modeling assumptions. Specifically, when the data is in-
deed non-Gaussian, then in the limit of large datasets, logistic regression will
1
This uses the convention of redefining the x(i) ’s on the right-hand-side to be n + 1-
(i)
dimensional vectors by adding the extra coordinate x0 = 1; see problem set 1.
8

almost always do better than GDA. For this reason, in practice logistic re-
gression is used more often than GDA. (Some related considerations about
discriminative vs. generative models also apply for the Naive Bayes algo-
rithm that we discuss next, but the Naive Bayes algorithm is still considered
a very good, and is certainly also a very popular, classification algorithm.)

2 Naive Bayes
In GDA, the feature vectors x were continuous, real-valued vectors. Lets now
talk about a different learning algorithm in which the xi ’s are discrete-valued.
For our motivating example, consider building an email spam filter using
machine learning. Here, we wish to classify messages according to whether
they are unsolicited commercial (spam) email, or non-spam email. After
learning to do this, we can then have our mail reader automatically filter
out the spam messages and perhaps place them in a separate mail folder.
Classifying emails is one example of a broader set of problems called text
classification.
Lets say we have a training set (a set of emails labeled as spam or non-
spam). We’ll begin our construction of our spam filter by specifying the
features xi used to represent an email.
We will represent an email via a feature vector whose length is equal to
the number of words in the dictionary. Specifically, if an email contains the
i-th word of the dictionary, then we will set xi = 1; otherwise, we let xi = 0.
For instance, the vector

1 a
 
 0  aardvark
 
 0  aardwolf
 .  ..
 . 
x= .  .
 1  buy
 
 .  ..
 ..  .
0 zygmurgy

is used to represent an email that contains the words “a” and “buy,” but not
“aardvark,” “aardwolf” or “zygmurgy.”2 The set of words encoded into the
2
Actually, rather than looking through an english dictionary for the list of all english
words, in practice it is more common to look through our training set and encode in our
feature vector only the words that occur at least once there. Apart from reducing the
number of words modeled and hence reducing our computational and space requirements,
9

feature vector is called the vocabulary, so the dimension of x is equal to


the size of the vocabulary.
Having chosen our feature vector, we now want to build a discriminative
model. So, we have to model p(x|y). But if we have, say, a vocabulary of
50000 words, then x ∈ {0, 1}50000 (x is a 50000-dimensional vector of 0’s and
1’s), and if we were to model x explicitly with a multinomial distribution over
the 250000 possible outcomes, then we’d end up with a (250000 −1)-dimensional
parameter vector. This is clearly too many parameters.
To model p(x|y), we will therefore make a very strong assumption. We will
assume that the xi ’s are conditionally independent given y. This assumption
is called the Naive Bayes (NB) assumption, and the resulting algorithm is
called the Naive Bayes classifier. For instance, if y = 1 means spam email;
“buy” is word 2087 and “price” is word 39831; then we are assuming that if
I tell you y = 1 (that a particular piece of email is spam), then knowledge
of x2087 (knowledge of whether “buy” appears in the message) will have no
effect on your beliefs about the value of x39831 (whether “price” appears).
More formally, this can be written p(x2087 |y) = p(x2087 |y, x39831 ). (Note that
this is not the same as saying that x2087 and x39831 are independent, which
would have been written “p(x2087 ) = p(x2087 |x39831 )”; rather, we are only
assuming that x2087 and x39831 are conditionally independent given y.)
We now have:

p(x1 , . . . , x50000 |y)


= p(x1 |y)p(x2 |y, x1 )p(x3 |y, x1 , x2 ) · · · p(x50000 |y, x1 , . . . , x49999 )
= p(x1 |y)p(x2 |y)p(x3 |y) · · · p(x50000 |y)
Y n
= p(xi |y)
i=1

The first equality simply follows from the usual properties of probabilities,
and the second equality used the NB assumption. We note that even though
the Naive Bayes assumption is an extremely strong assumptions, the resulting
algorithm works well on many problems.
Our model is parameterized by φi|y=1 = p(xi = 1|y = 1), φi|y=0 = p(xi =
1|y = 0), and φy = p(y = 1). As usual, given a training set {(x(i) , y (i) ); i =
this also has the advantage of allowing us to model/include as a feature many words
that may appear in your email (such as “cs229”) but that you won’t find in a dictionary.
Sometimes (as in the homework), we also exclude the very high frequency words (which
will be words like “the,” “of,” “and,”; these high frequency, “content free” words are called
stop words) since they occur in so many documents and do little to indicate whether an
email is spam or non-spam.
10

1, . . . , m}, we can write down the joint likelihood of the data:


m
Y
L(φy , φi|y=0 , φi|y=1 ) = p(x(i) , y (i) ).
i=1

Maximizing this with respect to φy , φi|y=0 and φi|y=1 gives the maximum
likelihood estimates:
Pm (i) (i)
i=1 1{xj = 1 ∧ y = 1}
φj|y=1 = Pm (i)
i=1 1{y = 1}
Pm (i) (i)
i=1 1{xj = 1 ∧ y = 0}
φj|y=0 = Pm (i) = 0}
i=1 1{y
Pm (i)
i=1 1{y = 1}
φy =
m
In the equations above, the “∧” symbol means “and.” The parameters have
a very natural interpretation. For instance, φj|y=1 is just the fraction of the
spam (y = 1) emails in which word j does appear.
Having fit all these parameters, to make a prediction on a new example
with features x, we then simply calculate

p(x|y = 1)p(y = 1)
p(y = 1|x) =
p(x)
( ni=1 p(xi |y = 1)) p(y = 1)
Q
= Qn ,
( i=1 p(xi |y = 1)) p(y = 1) + ( ni=1 p(xi |y = 0)) p(y = 0)
Q

and pick whichever class has the higher posterior probability.


Lastly, we note that while we have developed the Naive Bayes algorithm
mainly for the case of problems where the features xi are binary-valued, the
generalization to where xi can take values in {1, 2, . . . , ki } is straightforward.
Here, we would simply model p(xi |y) as multinomial rather than as Bernoulli.
Indeed, even if some original input attribute (say, the living area of a house,
as in our earlier example) were continuous valued, it is quite common to
discretize it—that is, turn it into a small set of discrete values—and apply
Naive Bayes. For instance, if we use some feature xi to represent living area,
we might discretize the continuous values as follows:
Living area (sq. feet) < 400 400-800 800-1200 1200-1600 >1600
xi 1 2 3 4 5
Thus, for a house with living area 890 square feet, we would set the value
of the corresponding feature xi to 3. We can then apply the Naive Bayes
11

algorithm, and model p(xi |y) with a multinomial distribution, as described


previously. When the original, continuous-valued attributes are not well-
modeled by a multivariate normal distribution, discretizing the features and
using Naive Bayes (instead of GDA) will often result in a better classifier.

2.1 Laplace smoothing


The Naive Bayes algorithm as we have described it will work fairly well
for many problems, but there is a simple change that makes it work much
better, especially for text classification. Lets briefly discuss a problem with
the algorithm in its current form, and then talk about how we can fix it.
Consider spam/email classification, and lets suppose that, after complet-
ing CS229 and having done excellent work on the project, you decide around
June 2003 to submit the work you did to the NIPS conference for publication.
(NIPS is one of the top machine learning conferences, and the deadline for
submitting a paper is typically in late June or early July.) Because you end
up discussing the conference in your emails, you also start getting messages
with the word “nips” in it. But this is your first NIPS paper, and until this
time, you had not previously seen any emails containing the word “nips”;
in particular “nips” did not ever appear in your training set of spam/non-
spam emails. Assuming that “nips” was the 35000th word in the dictionary,
your Naive Bayes spam filter therefore had picked its maximum likelihood
estimates of the parameters φ35000|y to be
Pm (i) (i)
i=1 1{x 35000 = 1 ∧ y = 1}
φ35000|y=1 = P m (i)
=0
i=1 1{y = 1}
Pm (i) (i)
i=1 1{x 35000 = 1 ∧ y = 0}
φ35000|y=0 = P m (i)
=0
i=1 1{y = 0}
I.e., because it has never seen “nips” before in either spam or non-spam
training examples, it thinks the probability of seeing it in either type of email
is zero. Hence, when trying to decide if one of these messages containing
“nips” is spam, it calculates the class posterior probabilities, and obtains
Qn
i=1 p(xi |y = Q
1)p(y = 1)
p(y = 1|x) = Qn n
i=1 p(xi |y = 1)p(y = 1) + i=1 p(xi |y = 0)p(y = 0)
0
= .
0
This is because each of the terms “ ni=1 p(xi |y)” includes a term p(x35000 |y) =
Q
0 that is multiplied into it. Hence, our algorithm obtains 0/0, and doesn’t
know how to make a prediction.
12

Stating the problem more broadly, it is statistically a bad idea to estimate


the probability of some event to be zero just because you haven’t seen it be-
fore in your finite training set. Take the problem of estimating the mean of
a multinomial random variable z taking values in {1, . . . , k}. We can param-
eterize our multinomial with φi = p(z = i). Given a set of m independent
observations {z (1) , . . . , z (m) }, the maximum likelihood estimates are given by
Pm
1{z (i) = j}
φj = i=1 .
m
As we saw previously, if we were to use these maximum likelihood estimates,
then some of the φj ’s might end up as zero, which was a problem. To avoid
this, we can use Laplace smoothing, which replaces the above estimate
with Pm
1{z (i) = j} + 1
φj = i=1 .
m+k
Here, we’ve added 1 to the numerator, and k to the denominator. Note that
P k
j=1 φj = 1 still holds (check this yourself!), which is a desirable property
since the φj ’s are estimates for probabilities that we know must sum to 1.
Also, φj 6= 0 for all values of j, solving our problem of probabilities being
estimated as zero. Under certain (arguably quite strong) conditions, it can
be shown that the Laplace smoothing actually gives the optimal estimator
of the φj ’s.
Returning to our Naive Bayes classifier, with Laplace smoothing, we
therefore obtain the following estimates of the parameters:
Pm (i) (i)
i=1 1{xj = 1 ∧ y = 1} + 1
φj|y=1 = P m (i) = 1} + 2
i=1 1{y
Pm (i) (i)
i=1 1{xj = 1 ∧ y = 0} + 1
φj|y=0 = Pm (i) = 0} + 2
i=1 1{y

(In practice, it usually doesn’t matter much whether we apply Laplace smooth-
ing to φy or not, since we will typically have a fair fraction each of spam and
non-spam messages, so φy will be a reasonable estimate of p(y = 1) and will
be quite far from 0 anyway.)

2.2 Event models for text classification


To close off our discussion of generative learning algorithms, lets talk about
one more model that is specifically for text classification. While Naive Bayes
13

as we’ve presented it will work well for many classification problems, for text
classification, there is a related model that does even better.
In the specific context of text classification, Naive Bayes as presented uses
the what’s called the multi-variate Bernoulli event model. In this model,
we assumed that the way an email is generated is that first it is randomly
determined (according to the class priors p(y)) whether a spammer or non-
spammer will send you your next message. Then, the person sending the
email runs through the dictionary, deciding whether to include each word i
in that email independently and according to the probabilities Q p(xi = 1|y) =
φi|y . Thus, the probability of a message was given by p(y) ni=1 p(xi |y).
Here’s a different model, called the multinomial event model. To de-
scribe this model, we will use a different notation and set of features for
representing emails. We let xi denote the identity of the i-th word in the
email. Thus, xi is now an integer taking values in {1, . . . , |V |}, where |V |
is the size of our vocabulary (dictionary). An email of n words is now rep-
resented by a vector (x1 , x2 , . . . , xn ) of length n; note that n can vary for
different documents. For instance, if an email starts with “A NIPS . . . ,”
then x1 = 1 (“a” is the first word in the dictionary), and x2 = 35000 (if
“nips” is the 35000th word in the dictionary).
In the multinomial event model, we assume that the way an email is
generated is via a random process in which spam/non-spam is first deter-
mined (according to p(y)) as before. Then, the sender of the email writes the
email by first generating x1 from some multinomial distribution over words
(p(x1 |y)). Next, the second word x2 is chosen independently of x1 but from
the same multinomial distribution, and similarly for x3 , x4 , and so on, until
all n words of the email have Qnbeen generated. Thus, the overall probability of
a message is given by p(y) i=1 p(xi |y). Note that this formula looks like the
one we had earlier for the probability of a message under the multi-variate
Bernoulli event model, but that the terms in the formula now mean very dif-
ferent things. In particular xi |y is now a multinomial, rather than a Bernoulli
distribution.
The parameters for our new model are φy = p(y) as before, φi|y=1 =
p(xj = i|y = 1) (for any j) and φi|y=0 = p(xj = i|y = 0). Note that we have
assumed that p(xj |y) is the same for all values of j (i.e., that the distribution
according to which a word is generated does not depend on its position j
within the email).
If we are given a training set {(x(i) , y (i) ); i = 1, . . . , m} where x(i) =
(i) (i) (i)
(x1 , x2 , . . . , xni ) (here, ni is the number of words in the i-training example),
14

the likelihood of the data is given by


m
Y
L(φ, φi|y=0 , φi|y=1 ) = p(x(i) , y (i) )
i=1
m ni
!
(i)
Y Y
= p(xj |y; φi|y=0 , φi|y=1 ) p(y (i) ; φy ).
i=1 j=1

Maximizing this yields the maximum likelihood estimates of the parameters:


P m Pni (i) (i)
i=1 j=1 1{xj = k ∧ y = 1}
φk|y=1 = Pm (i) = 1}n
i=1 1{y i
P m Pni (i) (i)
i=1 j=1 1{xj = k ∧ y = 0}
φk|y=0 = Pm (i) = 0}n
i=1 1{y i
Pm (i)
i=1 1{y = 1}
φy = .
m
If we were to apply Laplace smoothing (which needed in practice for good
performance) when estimating φk|y=0 and φk|y=1 , we add 1 to the numerators
and |V | to the denominators, and obtain:
Pm Pni (i) (i)
i=1 j=1 1{xj = k ∧ y = 1} + 1
φk|y=1 = Pm (i) = 1}n + |V |
i=1 1{y i
Pm Pni (i) (i)
i=1 j=1 1{xj = k ∧ y = 0} + 1
φk|y=0 = Pm (i) = 0}n + |V |
.
i=1 1{y i

While not necessarily the very best classification algorithm, the Naive Bayes
classifier often works surprisingly well. It is often also a very good “first thing
to try,” given its simplicity and ease of implementation.
CS229 Lecture notes
Andrew Ng

Part V
Support Vector Machines
This set of notes presents the Support Vector Machine (SVM) learning al-
gorithm. SVMs are among the best (and many believe is indeed the best)
“off-the-shelf” supervised learning algorithm. To tell the SVM story, we’ll
need to first talk about margins and the idea of separating data with a large
“gap.” Next, we’ll talk about the optimal margin classifier, which will lead
us into a digression on Lagrange duality. We’ll also see kernels, which give
a way to apply SVMs efficiently in very high dimensional (such as infinite-
dimensional) feature spaces, and finally, we’ll close off the story with the
SMO algorithm, which gives an efficient implementation of SVMs.

1 Margins: Intuition
We’ll start our story on SVMs by talking about margins. This section will
give the intuitions about margins and about the “confidence” of our predic-
tions; these ideas will be made formal in Section 3.
Consider logistic regression, where the probability p(y = 1|x; θ) is mod-
eled by hθ (x) = g(θ T x). We would then predict “1” on an input x if and
only if hθ (x) ≥ 0.5, or equivalently, if and only if θ T x ≥ 0. Consider a
positive training example (y = 1). The larger θ T x is, the larger also is
hθ (x) = p(y = 1|x; w, b), and thus also the higher our degree of “confidence”
that the label is 1. Thus, informally we can think of our prediction as being
a very confident one that y = 1 if θ T x  0. Similarly, we think of logistic
regression as making a very confident prediction of y = 0, if θ T x  0. Given
a training set, again informally it seems that we’d have found a good fit to
the training data if we can find θ so that θ T x(i)  0 whenever y (i) = 1, and

1
2

θT x(i)  0 whenever y (i) = 0, since this would reflect a very confident (and
correct) set of classifications for all the training examples. This seems to be
a nice goal to aim for, and we’ll soon formalize this idea using the notion of
functional margins.
For a different type of intuition, consider the following figure, in which x’s
represent positive training examples, o’s denote negative training examples,
a decision boundary (this is the line given by the equation θ T x = 0, and
is also called the separating hyperplane) is also shown, and three points
have also been labeled A, B and C.

A


B


C


Notice that the point A is very far from the decision boundary. If we are
asked to make a prediction for the value of y at at A, it seems we should be
quite confident that y = 1 there. Conversely, the point C is very close to
the decision boundary, and while it’s on the side of the decision boundary
on which we would predict y = 1, it seems likely that just a small change to
the decision boundary could easily have caused out prediction to be y = 0.
Hence, we’re much more confident about our prediction at A than at C. The
point B lies in-between these two cases, and more broadly, we see that if
a point is far from the separating hyperplane, then we may be significantly
more confident in our predictions. Again, informally we think it’d be nice if,
given a training set, we manage to find a decision boundary that allows us
to make all correct and confident (meaning far from the decision boundary)
predictions on the training examples. We’ll formalize this later using the
notion of geometric margins.
3

2 Notation
To make our discussion of SVMs easier, we’ll first need to introduce a new
notation for talking about classification. We will be considering a linear
classifier for a binary classification problem with labels y and features x.
From now, we’ll use y ∈ {−1, 1} (instead of {0, 1}) to denote the class labels.
Also, rather than parameterizing our linear classifier with the vector θ, we
will use parameters w, b, and write our classifier as

hw,b (x) = g(w T x + b).

Here, g(z) = 1 if z ≥ 0, and g(z) = −1 otherwise. This “w, b” notation


allows us to explicitly treat the intercept term b separately from the other
parameters. (We also drop the convention we had previously of letting x0 = 1
be an extra coordinate in the input feature vector.) Thus, b takes the role of
what was previously θ0 , and w takes the role of [θ1 . . . θn ]T .
Note also that, from our definition of g above, our classifier will directly
predict either 1 or −1 (cf. the perceptron algorithm), without first going
through the intermediate step of estimating the probability of y being 1
(which was what logistic regression did).

3 Functional and geometric margins


Lets formalize the notions of the functional and geometric margins. Given a
training example (x(i) , y (i) ), we define the functional margin of (w, b) with
respect to the training example

γ̂ (i) = y (i) (wT x + b).

Note that if y (i) = 1, then for the functional margin to be large (i.e., for our
prediction to be confident and correct), then we need w T x + b to be a large
positive number. Conversely, if y (i) = −1, then for the functional margin to
be large, then we need w T x + b to be a large negative number. Moreover,
if y (i) (wT x + b) > 0, then our prediction on this example is correct. (Check
this yourself.) Hence, a large functional margin represents a confident and a
correct prediction.
For a linear classifier with the choice of g given above (taking values in
{−1, 1}), there’s one property of the functional margin that makes it not a
very good measure of confidence, however. Given our choice of g, we note that
if we replace w with 2w and b with 2b, then since g(w T x + b) = g(2w T x + 2b),
4

this would not change hw,b (x) at all. I.e., g, and hence also hw,b (x), depends
only on the sign, but not on the magnitude, of w T x + b. However, replacing
(w, b) with (2w, 2b) also results in multiplying our functional margin by a
factor of 2. Thus, it seems that by exploiting our freedom to scale w and b,
we can make the functional margin arbitrarily large without really changing
anything meaningful. Intuitively, it might therefore make sense to impose
some sort of normalization condition such as that ||w||2 = 1; i.e., we might
replace (w, b) with (w/||w||2 , b/||w||2 ), and instead consider the functional
margin of (w/||w||2 , b/||w||2 ). We’ll come back to this later.
Given a training set S = {(x(i) , y (i) ); i = 1, . . . , m}, we also define the
function margin of (w, b) with respect to S as the smallest of the functional
margins of the individual training examples. Denoted by γ̂, this can therefore
be written:
γ̂ = min γ̂ (i) .
i=1,...,m

Next, lets talk about geometric margins. Consider the picture below:

A w

γ (i)

The decision boundary corresponding to (w, b) is shown, along with the


vector w. Note that w is orthogonal (at 90◦ ) to the separating hyperplane.
(You should convince yourself that this must be the case.) Consider the
point at A, which represents the input x(i) of some training example with
label y (i) = 1. Its distance to the decision boundary, γ (i) , is given by the line
segment AB.
How can we find the value of γ (i) ? Well, w/||w|| is a unit-length vector
pointing in the same direction as w. Since A represents x(i) , we therefore
5

find that the point B is given by x(i) − γ (i) · w/||w||. But this point lies on
the decision boundary, and all points x on the decision boundary satisfy the
equation w T x + b = 0. Hence,
 
T (i) (i) w
w x −γ + b = 0.
||w||

Solving for γ (i) yields


T
wT x(i) + b

(i) w b
γ = = x(i) + .
||w|| ||w|| ||w||
This was worked out for the case of a positive training example at A in the
figure, where being on the “positive” side of the decision boundary is good.
More generally, we define the geometric margin of (w, b) with respect to a
training example (x(i) , y (i) ) to be
 T !
(i) (i) w (i) b
γ =y x + .
||w|| ||w||

Note that if ||w|| = 1, then the functional margin equals the geometric
margin—this thus gives us a way of relating these two different notions of
margin. Also, the geometric margin is invariant to rescaling of the parame-
ters; i.e., if we replace w with 2w and b with 2b, then the geometric margin
does not change. This will in fact come in handy later. Specifically, because
of this invariance to the scaling of the parameters, when trying to fit w and b
to training data, we can impose an arbitrary scaling constraint on w without
changing anything important; for instance, we can demand that ||w|| = 1, or
|w1 | = 5, or |w1 + b| + |w2 | = 2, and any of these can be satisfied simply by
rescaling w and b.
Finally, given a training set S = {(x(i) , y (i) ); i = 1, . . . , m}, we also define
the geometric margin of (w, b) with respect to S to be the smallest of the
geometric margins on the individual training examples:

γ = min γ (i) .
i=1,...,m

4 The optimal margin classifier


Given a training set, it seems from our previous discussion that a natural
desideratum is to try to find a decision boundary that maximizes the (ge-
ometric) margin, since this would reflect a very confident set of predictions
6

on the training set and a good “fit” to the training data. Specifically, this
will result in a classifier that separates the positive and the negative training
examples with a “gap” (geometric margin).
For now, we will assume that we are given a training set that is linearly
separable; i.e., that it is possible to separate the positive and negative ex-
amples using some separating hyperplane. How we we find the one that
achieves the maximum geometric margin? We can pose the following opti-
mization problem:

maxγ,w,b γ
s.t. y (i) (wT x(i) + b) ≥ γ, i = 1, . . . , m
||w|| = 1.

I.e., we want to maximize γ, subject to each training example having func-


tional margin at least γ. The ||w|| = 1 constraint moreover ensures that the
functional margin equals to the geometric margin, so we are also guaranteed
that all the geometric margins are at least γ. Thus, solving this problem will
result in (w, b) with the largest possible geometric margin with respect to the
training set.
If we could solve the optimization problem above, we’d be done. But the
“||w|| = 1” constraint is a nasty (non-convex) one, and this problem certainly
isn’t in any format that we can plug into standard optimization software to
solve. So, lets try transforming the problem into a nicer one. Consider:
γ̂
maxγ,w,b
||w||
s.t. y (i) (wT x(i) + b) ≥ γ̂, i = 1, . . . , m

Here, we’re going to maximize γ̂/||w||, subject to the functional margins all
being at least γ̂. Since the geometric and functional margins are related by
γ = γ̂/||w|, this will give us the answer we want. Moreover, we’ve gotten rid
of the constraint ||w|| = 1 that we didn’t like. The downside is that we now
γ̂
have a nasty (again, non-convex) objective ||w|| function; and, we still don’t
have any off-the-shelf software that can solve this form of an optimization
problem.
Lets keep going. Recall our earlier discussion that we can add an arbitrary
scaling constraint on w and b without changing anything. This is the key idea
we’ll use now. We will introduce the scaling constraint that the functional
margin of w, b with respect to the training set must be 1:

γ̂ = 1.
7

Since multiplying w and b by some constant results in the functional margin


being multiplied by that same constant, this is indeed a scaling constraint,
and can be satisfied by rescaling w, b. Plugging this into our problem above,
and noting that maximizing γ̂/||w|| = 1/||w|| is the same thing as minimizing
||w||2 , we now have the following optimization problem:
1
minγ,w,b ||w||2
2
s.t. y (i) (wT x(i) + b) ≥ 1, i = 1, . . . , m
We’ve now transformed the problem into a form that can be efficiently
solved. The above is an optimization problem with a convex quadratic ob-
jective and only linear constraints. Its solution gives us the optimal mar-
gin classifier. This optimization problem can be solved using commercial
quadratic programming (QP) code.1
While we could call the problem solved here, what we will instead do is
make a digression to talk about Lagrange duality. This will lead us to our
optimization problem’s dual form, which will play a key role in allowing us to
use kernels to get optimal margin classifiers to work efficiently in very high
dimensional spaces. The dual form will also allow us to derive an efficient
algorithm for solving the above optimization problem that will typically do
much better than generic QP software.

5 Lagrange duality
Lets temporarily put aside SVMs and maximum margin classifiers, and talk
about solving constrained optimization problems.
Consider a problem of the following form:
minw f (w)
s.t. hi (w) = 0, i = 1, . . . , l.
Some of you may recall how the method of Lagrange multipliers can be used
to solve it. (Don’t worry if you haven’t seen it before.) In this method, we
define the Lagrangian to be
l
X
L(w, β) = f (w) + βi hi (w)
i=1
1
You may be familiar with linear programming, which solves optimization problems
that have linear objectives and linear constraints. QP software is also widely available,
which allows convex quadratic objectives and linear constraints.
8

Here, the βi ’s are called the Lagrange multipliers. We would then find
and set L’s partial derivatives to zero:
∂L ∂L
= 0; = 0,
∂wi ∂βi
and solve for w and β.
In this section, we will generalize this to constrained optimization prob-
lems in which we may have inequality as well as equality constraints. Due to
time constraints, we won’t really be able to do the theory of Lagrange duality
justice in this class,2 but we will give the main ideas and results, which we
will then apply to our optimal margin classifier’s optimization problem.
Consider the following, which we’ll call the primal optimization problem:
minw f (w)
s.t. gi (w) ≤ 0, i = 1, . . . , k
hi (w) = 0, i = 1, . . . , l.
To solve it, we start by defining the generalized Lagrangian
k
X l
X
L(w, α, β) = f (w) + αi gi (w) + βi hi (w).
i=1 i=1

Here, the αi ’s and βi ’s are the Lagrange multipliers. Consider the quantity
θP (w) = max L(w, α, β).
α,β : αi ≥0

Here, the “P” subscript stands for “primal.” Let some w be given. If w
violates any of the primal constraints (i.e., if either gi (w) > 0 or hi (w) 6= 0
for some i), then you should be able to verify that
k
X l
X
θP (w) = max f (w) + αi gi (w) + βi hi (w) (1)
α,β : αi ≥0
i=1 i=1
= ∞. (2)
Conversely, if the constraints are indeed satisfied for a particular value of w,
then θP (w) = f (w). Hence,

f (w) if w satisfies primal constraints
θP (w) =
∞ otherwise.
2
Readers interested in learning more about this topic are encouraged to read, e.g., R.
T. Rockarfeller (1970), Convex Analysis, Princeton University Press.
9

Thus, θP takes the same value as the objective in our problem for all val-
ues of w that satisfies the primal constraints, and is positive infinity if the
constraints are violated. Hence, if we consider the minimization problem
min θP (w) = min max L(w, α, β),
w w α,β : αi ≥0

we see that it is the same problem (i.e., and has the same solutions as) our
original, primal problem. For later use, we also define the optimal value of
the objective to be p∗ = minw θP (w); we call this the value of the primal
problem.
Now, lets look at a slightly different problem. We define
θD (α, β) = min L(w, α, β).
w
Here, the “D” subscript stands for “dual.” Note also that whereas in the
definition of θP we were optimizing (maximizing) with respect to α, β, here
are are minimizing with respect to w.
We can now pose the dual optimization problem:
max θD (α, β) = max min L(w, α, β).
α,β : αi ≥0 α,β : αi ≥0 w

This is exactly the same as our primal problem shown above, except that the
order of the “max” and the “min” are now exchanged. We also define the
optimal value of the dual problem’s objective to be d∗ = maxα,β : αi ≥0 θD (w).
How are the primal and the dual problems related? It can easily be shown
that
d∗ = max min L(w, α, β) ≤ min max L(w, α, β) = p∗ .
α,β : αi ≥0 w w α,β : αi ≥0

(You should convince yourself of this; this follows from the “max min” of a
function always being less than or equal to the “min max.”) However, under
certain conditions, we will have
d∗ = p ∗ ,
so that we can solve the dual problem in lieu of the primal problem. Lets
see what these conditions are.
Suppose f and the gi ’s are convex,3 and the hi ’s are affine.4 Suppose
further that the constraints gi are (strictly) feasible; this means that there
exists some w so that gi (w) < 0 for all i.
3
When f has a Hessian, then it is convex if and only if the hessian is positive semi-
definite. For instance, f (w) = w T w is convex; similarly, all linear (and affine) functions
are also convex. (A function f can also be convex without being differentiable, but we
won’t need those more general definitions of convexity here.)
4
I.e., there exists ai , bi , so that hi (w) = aTi w + bi . “Affine” means the same thing as
linear, except that we also allow the extra intercept term bi .
10

Under our above assumptions, there must exist w ∗ , α∗ , β ∗ so that w ∗ is the


solution to the primal problem, α∗ , β ∗ are the solution to the dual problem,
and moreover p∗ = d∗ = L(w∗ , α∗ , β ∗ ). Moreover, w ∗ , α∗ and β ∗ satisfy the
Karush-Kuhn-Tucker (KKT) conditions, which are as follows:

L(w∗ , α∗ , β ∗ ) = 0, i = 1, . . . , n (3)
∂wi

L(w∗ , α∗ , β ∗ ) = 0, i = 1, . . . , l (4)
∂βi
αi∗ gi (w∗ ) = 0, i = 1, . . . , k (5)
gi (w∗ ) ≤ 0, i = 1, . . . , k (6)
α∗ ≥ 0, i = 1, . . . , k (7)

Moreover, if some w ∗ , α∗ , β ∗ satisfy the KKT conditions, then it is also a


solution to the primal and dual problems.
We draw attention to Equation (5), which is called the KKT dual com-
plementarity condition. Specifically, it implies that if αi∗ > 0, then gi (w∗ ) =
0. (I.e., the “gi (w) ≤ 0” constraint is active, meaning it holds with equality
rather than with inequality.) Later on, this will be key for showing that the
SVM has only a small number of “support vectors”; the KKT dual comple-
mentarity condition will also give us our convergence test when we talk about
the SMO algorithm.

6 Optimal margin classifiers


Previously, we posed the following (primal) optimization problem for finding
the optimal margin classifier:
1
minγ,w,b ||w||2
2
s.t. y (i) (wT x(i) + b) ≥ 1, i = 1, . . . , m

We can write the constraints as

gi (w) = −y (i) (wT x(i) + b) + 1 ≤ 0.

We have one such constraint for each training example. Note that from the
KKT dual complementarity condition, we will have αi > 0 only for the train-
ing examples that have functional margin exactly equal to one (i.e., the ones
11

corresponding to constraints that hold with equality, gi (w) = 0). Consider


the figure below, in which a maximum margin separating hyperplane is shown
by the solid line.

The points with the smallest margins are exactly the ones closest to the
decision boundary; here, these are the three points (one negative and two pos-
itive examples) that lie on the dashed lines parallel to the decision boundary.
Thus, only three of the αi ’s—namely, the ones corresponding to these three
training examples—will be non-zero at the optimal solution to our optimiza-
tion problem. These three points are called the support vectors in this
problem. The fact that the number of support vectors can be much smaller
than the size the training set will be useful later.
Lets move on. Looking ahead, as we develop the dual form of the problem,
one key idea to watch out for is that we’ll try to write our algorithm in terms
of only the inner product hx(i) , x(j) i (think of this as (x(i) )T x(j) ) between
points in the input feature space. The fact that we can express our algorithm
in terms of these inner products will be key when we apply the kernel trick.
When we construct the Lagrangian for our optimization problem we have:
m
1 X 
L(w, b, α) = ||w||2 − αi y (i) (wT x(i) + b) − 1 .

(8)
2 i=1

Note that there’re only “αi ” but no “βi ” Lagrange multipliers, since the
problem has only inequality constraints.
Lets find the dual form of the problem. To do so, we need to first minimize
L(w, b, α) with respect to w and b (for fixed α), to get θD , which we’ll do by
12

setting the derivatives of L with respect to w and b to zero. We have:


m
X
∇w L(w, b, α) = w − αi y (i) x(i) = 0
i=1

This implies that


m
X
w= αi y (i) x(i) . (9)
i=1

As for the derivative with respect to b, we obtain


m
∂ X
L(w, b, α) = αi y (i) = 0. (10)
∂b i=1

If we take the definition of w in Equation (9) and plug that back into the
Lagrangian (Equation 8), and simplify, we get
m m m
X 1 X (i) (j) (i) T (j)
X
L(w, b, α) = αi − y y αi αj (x ) x − b αi y (i) .
i=1
2 i,j=1 i=1

But from Equation (10), the last term must be zero, so we obtain
m m
X 1 X (i) (j)
L(w, b, α) = αi − y y αi αj (x(i) )T x(j) .
i=1
2 i,j=1

Recall that we got to the equation above by minimizing L with respect to w


and b. Putting this together with the constraints αi ≥ 0 (that we always had)
and the constraint (10), we obtain the following dual optimization problem:
m m
X 1 X (i) (j)
maxα W (α) = αi − y y αi αj hx(i) , x(j) i.
i=1
2 i,j=1
s.t. αi ≥ 0, i = 1, . . . , m
Xm
αi y (i) = 0,
i=1

You should also be able to verify that the conditions required for p∗ =
d∗ and the KKT conditions (Equations 3–7) to hold are indeed satisfied in
our optimization problem. Hence, we can solve the dual in lieu of solving
the primal problem. Specifically, in the dual problem above, we have a
maximization problem in which the parameters are the αi ’s. We’ll talk later
13

about the specific algorithm that we’re going to use to solve the dual problem,
but if we are indeed able to solve it (i.e., find the α’s that maximize W (α)
subject to the constraints), then we can use Equation (9) to go back and find
the optimal w’s as a function of the α’s. Having found w ∗ , by considering
the primal problem, it is also straightforward to find the optimal value for
the intercept term b as
maxi:y(i) =−1 w∗ T x(i) + mini:y(i) =1 w∗ T x(i)
b∗ = − . (11)
2
(Check for yourself that this is correct.)
Before moving on, lets also take a more careful look at Equation (9), which
gives the optimal value of w in terms of (the optimal value of) α. Suppose
we’ve fit our model’s parameters to a training set, and now wish to make a
prediction at a new point input x. We would then calculate w T x + b, and
predict y = 1 if and only if this quantity is bigger than zero. But using (9),
this quantity can also be written:
m
!T
X
wT x + b = αi y (i) x(i) x+b (12)
i=1
m
X
= αi y (i) hx(i) , xi + b. (13)
i=1

Hence, if we’ve found the αi ’s, in order to make a prediction, we have to


calculate a quantity that depends only on the inner product between x and
the points in the training set. Moreover, we saw earlier that the αi ’s will all
be zero except for the support vectors. Thus, many of the terms in the sum
above will be zero, and we really need to find only the inner products between
x and the support vectors (of which there is often only a small number) in
order calculate (13) and make our prediction.
By examining the dual form of the optimization problem, we gained sig-
nificant insight into the structure of the problem, and were also able to write
the entire algorithm in terms of only inner products between input feature
vectors. In the next section, we will exploit this property to apply the ker-
nels to our classification problem. The resulting algorithm, support vector
machines, will be able to efficiently learn in very high dimensional spaces.

7 Kernels
Back in our discussion of linear regression, we had a problem in which the
input x was the living area of a house, and we considered performing regres-
14

sion using the features x, x2 and x3 (say) to obtain a cubic function. To


distinguish between these two sets of variables, we’ll call the “original” input
value the input attributes of a problem (in this case, x, the living area).
When that is mapped to some new set of quantities that are then passed to
the learning algorithm, we’ll call those new quantities the input features.
(Unfortunately, different authors use different terms to describe these two
things, but we’ll try to use this terminology consistently in these notes.) We
will also let φ denote the feature mapping, which maps from the attributes
to the features. For instance, in our example, we had
 
x
φ(x) =  x2  .
x3

Rather than applying SVMs using the original input attributes x, we may
instead want to learn using some features φ(x). To do so, we simply need to
go over our previous algorithm, and replace x everywhere in it with φ(x).
Since the algorithm can be written entirely in terms of the inner prod-
ucts hx, zi, this means that we would replace all those inner products with
hφ(x), φ(z)i. Specificically, given a feature mapping φ, we define the corre-
sponding Kernel to be

K(x, z) = φ(x)T φ(z).

Then, everywhere we previously had hx, zi in our algorithm, we could simply


replace it with K(x, z), and our algorithm would now be learning using the
features φ.
Now, given φ, we could easily compute K(x, z) by finding φ(x) and φ(z)
and taking their inner product. But what’s more interesting is that often,
K(x, z) may be very inexpensive to calculate, even though φ(x) itself may
be very expensive to calculate (perhaps because it is an extremely high di-
mensional vector). In such settings, by using in our algorithm an efficient
way to calculate K(x, z), we can get SVMs to learn in the high dimensional
feature space space given by φ, but without ever having to explicitly find or
represent vectors φ(x).
Lets see an example. Suppose x, z ∈ Rn , and consider

K(x, z) = (xT z)2 .


15

We can also write this as


n
! n
!
X X
K(x, z) = xi z i xi z i
i=1 j=1
n
XX n
= xi xj z i z j
i=1 j=1
Xn
= (xi xj )(zi zj )
i,j=1

Thus, we see that K(x, z) = φ(x)T φ(z), where the feature mapping φ is given
(shown here for the case of n = 3) by
 
x1 x1
 x1 x2 
 
 x1 x3 
 
 x2 x1 
 
φ(x) = 
 x 2 x 2
.

 x2 x3 
 
 x3 x1 
 
 x3 x2 
x3 x3

Note that whereas calculating the high-dimensional φ(x) requires O(n2 ) time,
finding K(x, z) takes only O(n) time—linear in the dimension of the input
attributes.
For a related kernel, also consider

K(x, z) = (xT z + c)2


n n
X X √ √
= (xi xj )(zi zj ) + ( 2cxi )( 2czi ) + c2 .
i,j=1 i=1

(Check this yourself.) This corresponds to the feature mapping (again shown
16

for n = 3)
x1 x1
 

 x1 x2 


 x1 x3 


 x2 x1 


 x2 x2 


 x2 x3 

φ(x) = 
 x3 x1 ,


 x3 x2 

√ 3 x3
x
 
 
√2cx1
 
 
√2cx2
 
 
 2cx3 
c
and the parameter c controls the relative weighting between the xi (first
order) and the xi xj (second order) terms.
More broadly, the kernel K(x, z) = (xT z + c)d corresponds to a feature
mapping to an n+d d feature space, corresponding of all monomials of the
form xi1 xi2 . . . xik that are up to order d. However, despite working in this
O(nd )-dimensional space, computing K(x, z) still takes only O(n) time, and
hence we never need to explicitly represent feature vectors in this very high
dimensional feature space.
Now, lets talk about a slightly different view of kernels. Intuitively, (and
there are things wrong with this intuition, but nevermind), if φ(x) and φ(z)
are close together, then we might expect K(x, z) = φ(x)T φ(z) to be large.
Conversely, if φ(x) and φ(z) are far apart—say nearly orthogonal to each
other—then K(x, z) = φ(x)T φ(z) will be small. So, we can think of K(x, z)
as some measurement of how similar are φ(x) and φ(z), or of how similar are
x and z.
Given this intuition, suppose that for some learning problem that you’re
working on, you’ve come up with some function K(x, z) that you think might
be a reasonable measure of how similar x and z are. For instance, perhaps
you chose
||x − z||2
 
K(x, z) = exp − .
2σ 2
This is a resonable measure of x and z’s similarity, and is close to 1 when
x and z are close, and near 0 when x and z are far apart. Can we use this
definition of K as the kernel in an SVM? In this particular example, the
answer is yes. (This kernel is called the Gaussian kernel, and corresponds
17

to an infinite dimensional feature mapping φ.) But more broadly, given some
function K, how can we tell if it’s a valid kernel; i.e., can we tell if there is
some feature mapping φ so that K(x, z) = φ(x)T φ(z) for all x, z?
Suppose for now that K is indeed a valid kernel corresponding to some
feature mapping φ. Now, consider some finite set of m points (not necessarily
the training set) {x(1) , . . . , x(m) }, and let a square, m-by-m matrix K be
defined so that its (i, j)-entry is given by Kij = K(x(i) , x(j) ). This matrix
is called the Kernel matrix. Note that we’ve overloaded the notation and
used K to denote both the kernel function K(x, z) and the kernel matrix K,
due to their obvious close relationship.
Now, if K is a valid Kernel, then Kij = K(x(i) , x(j) ) = φ(x(i) )T φ(x(j) ) =
φ(x(j) )T φ(x(i) ) = K(x(j) , x(i) ) = Kji , and hence K must be symmetric. More-
over, letting φk (x) denote the k-th coordinate of the vector φ(x), we find that
for any vector z, we have
XX
z T Kz = zi Kij zj
i j
XX
= zi φ(x(i) )T φ(x(j) )zj
i j
XX X
= zi φk (x(i) )φk (x(j) )zj
i j k
XXX
= zi φk (x(i) )φk (x(j) )zj
k i j
!2
X X
= zi φk (x(i) )
k i
≥ 0.

The second-to-last step above used the same trick as you saw in Problem
set 1 Q1. Since z was arbitrary, this shows that K is positive semi-definite
(K ≥ 0).
Hence, we’ve shown that if K is a valid kernel (i.e., if it corresponds to
some feature mapping φ), then the corresponding Kernel matrix K ∈ Rm×m
is symmetric positive semidefinite. More generally, this turns out to be not
only a necessary, but also a sufficient, condition for K to be a valid kernel
(also called a Mercer kernel). The following result is due to Mercer.5
5
Many texts present Mercer’s theorem in a slightly more complicated form involving
2
L functions, but when the input attributes take values in Rn , the version given here is
equivalent.
18

Theorem (Mercer). Let K : Rn × Rn 7→ R be given. Then for K


to be a valid (Mercer) kernel, it is necessary and sufficient that for any
{x(1) , . . . , x(m) }, (m < ∞), the corresponding kernel matrix is symmetric
positive semi-definite.

Given a function K, apart from trying to find a feature mapping φ that


corresponds to it, this theorem therefore gives another way of testing if it is
a valid kernel. You’ll also have a chance to play with these ideas more in
problem set 2.
In class, we also briefly talked about a couple of other examples of ker-
nels. For instance, consider the digit recognition problem, in which given
an image (16x16 pixels) of a handwritten digit (0-9), we have to figure out
which digit it was. Using either a simple polynomial kernel K(x, z) = (x T z)d
or the Gaussian kernel, SVMs were able to obtain extremely good perfor-
mance on this problem. This was particularly surprising since the input
attributes x were just a 256-dimensional vector of the image pixel intensity
values, and the system had no prior knowledge about vision, or even about
which pixels are adjacent to which other ones. Another example that we
briefly talked about in lecture was that if the objects x that we are trying
to classify are strings (say, x is a list of amino acids, which strung together
form a protein), then it seems hard to construct a reasonable, “small” set of
features for most learning algorithms, especially if different strings have dif-
ferent lengths. However, consider letting φ(x) be a feature vector that counts
the number of occurrences of each length-k substring in x. If we’re consider-
ing strings of english alphabets, then there’re 26k such strings. Hence, φ(x)
is a 26k dimensional vector; even for moderate values of k, this is probably
too big for us to efficiently work with. (e.g., 264 ≈ 460000.) However, using
(dynamic programming-ish) string matching algorithms, it is possible to ef-
ficiently compute K(x, z) = φ(x)T φ(z), so that we can now implicitly work
in this 26k -dimensional feature space, but without ever explicitly computing
feature vectors in this space.
The application of kernels to support vector machines should already
be clear and so we won’t dwell too much longer on it here. Keep in mind
however that the idea of kernels has significantly broader applicability than
SVMs. Specifically, if you have any learning algorithm that you can write
in terms of only inner products hx, zi between input attribute vectors, then
by replacing this with K(x, z) where K is a kernel, you can “magically”
allow your algorithm to work efficiently in the high dimensional feature space
corresponding to K. For instance, this kernel trick can be applied with
the perceptron to to derive a kernel perceptron algorithm. Many of the
19

algorithms that we’ll see later in this class will also be amenable to this
method, which has come to be known as the “kernel trick.”

8 Regularization and the non-separable case


The derivation of the SVM as presented so far assumed that the data is
linearly separable. While mapping data to a high dimensional feature space
via φ does generally increase the likelihood that the data is separable, we
can’t guarantee that it always will be so. Also, in some cases it is not clear
that finding a separating hyperplane is exactly what we’d want to do, since
that might be susceptible to outliers. For instance, the left figure below
shows an optimal margin classifier, and when a single outlier is added in the
upper-left region (right figure), it causes the decision boundary to make a
dramatic swing, and the resulting classifier has a much smaller margin.

To make the algorithm work for non-linearly separable datasets as well


as be less sensitive to outliers, we reformulate our optimization (using `1
regularization) as follows:
m
1 X
minγ,w,b ||w||2 + C ξi
2 i=1

s.t. y (i) (wT x(i) + b) ≥ 1 − ξi , i = 1, . . . , m


ξi ≥ 0, i = 1, . . . , m.

Thus, examples are now permitted to have (functional) margin less than 1,
and if an example whose functional margin is 1 − ξi , we would pay a cost of
the objective function being increased by Cξi . The parameter C controls the
relative weighting between the twin goals of making the ||w||2 large (which
we saw earlier makes the margin small) and of ensuring that most examples
have functional margin at least 1.
20

As before, we can form the Lagrangian:


m m m
1 X X   X
L(w, b, ξ, α, r) = wT w + C ξi − αi y (i) (xT w + b) − 1 + ξi − ri ξ i .
2 i=1 i=1 i=1

Here, the αi ’s and ri ’s are our Lagrange multipliers (constrained to be ≥ 0).


We won’t go through the derivation of the dual again in detail, but after
setting the derivatives with respect to w and b to zero as before, substituting
them back in, and simplifying, we obtain the following dual form of the
problem:
m m
X 1 X (i) (j)
maxα W (α) = αi − y y αi αj hx(i) , x(j) i
i=1
2 i,j=1
s.t. 0 ≤ αi ≤ C, i = 1, . . . , m
Xm
αi y (i) = 0,
i=1

As before, we also have that w can be expressed in terms of the αi ’s


as given in Equation (9), so that after solving the dual problem, we can
continue to use Equation (13) to make our predictions. Note that, somewhat
surprisingly, in adding `1 regularization, the only change to the dual problem
is that what was originally a constraint that 0 ≤ αi has now become 0 ≤
αi ≤ C. The calculation for b∗ also has to be modified (Equation 11 is no
longer valid); see the comments in the next section/Platt’s paper.
Also, the KKT dual-complementarity conditions (which in the next sec-
tion will be useful for testing for the convergence of the SMO algorithm)
are:

αi = 0 ⇒ y (i) (wT x(i) + b) ≥ 1 (14)


αi = C ⇒ y (i) (wT x(i) + b) ≤ 1 (15)
0 < αi < C ⇒ y (i) (wT x(i) + b) = 1. (16)

Now, all that remains is to give an algorithm for actually solving the dual
problem, which we will do in the next section.

9 The SMO algorithm


The SMO (sequential minimal optimization) algorithm, due to John Platt,
gives an efficient way of solving the dual problem arising from the derivation
21

of the SVM. Partly to motivate the SMO algorithm, and partly because it’s
interesting in its own right, lets first take another digression to talk about
the coordinate ascent algorithm.

9.1 Coordinate ascent


Consider trying to solve the unconstrained optimization problem

max W (α1 , α2 , . . . , αm ).
α

Here, we think of W as just some function of the parameters αi ’s, and for now
ignore any relationship between this problem and SVMs. We’ve already seen
two optimization algorithms, gradient ascent and Newton’s method. The
new algorithm we’re going to consider here is called coordinate ascent:

Loop until convergence: {

For i = 1, . . . , m, {
αi := arg maxα̂i W (α1 , . . . , αi−1 , α̂i , αi+1 , . . . , αm ).
}

Thus, in the innermost loop of this algorithm, we will hold all the vari-
ables except for some αi fixed, and reoptimize W with respect to just the
parameter αi . In the version of this method presented here, the inner-loop
reoptimizes the variables in order α1 , α2 , . . . , αm , α1 , α2 , . . .. (A more sophis-
ticated version might choose other orderings; for instance, we may choose
the next variable to update according to which one we expect to allow us to
make the largest increase in W (α).)
When the function W happens to be of such a form that the “arg max”
in the inner loop can be performed efficiently, then coordinate ascent can be
a fairly efficient algorithm. Here’s a picture of coordinate ascent in action:
22

2.5

1.5

0.5

−0.5

−1

−1.5

−2

−2 −1.5 −1 −0.5 0 0.5 1 1.5 2 2.5

The ellipses in the figure are the contours of a quadratic function that
we want to optimize. Coordinate ascent was initialized at (2, −2), and also
plotted in the figure is the path that it took on its way to the global maximum.
Notice that on each step, coordinate ascent takes a step that’s parallel to one
of the axes, since only one variable is being optimized at a time.

9.2 SMO
We close off the discussion of SVMs by sketching the derivation of the SMO
algorithm. Some details will be left to the homework, and for others you
may refer to the paper excerpt handed out in class.
Here’s the (dual) optimization problem that we want to solve:
m m
X 1 X (i) (j)
maxα W (α) = αi − y y αi αj hx(i) , x(j) i. (17)
i=1
2 i,j=1
s.t. 0 ≤ αi ≤ C, i = 1, . . . , m (18)
Xm
αi y (i) = 0. (19)
i=1

Lets say we have set of αi ’s that satisfy the constraints (18-19). Now,
suppose we want to hold α2 , . . . , αm fixed, and take a coordinate ascent step
and reoptimize the objective with respect to α1 . Can we make any progress?
The answer is no, because the constraint (19) ensures that
m
X
(1)
α1 y =− αi y (i) .
i=2
23

Or, by multiplying both sides by y (1) , we equivalently have


m
X
α1 = −y (1) αi y (i) .
i=2

(This step used the fact that y (1) ∈ {−1, 1}, and hence (y (1) )2 = 1.) Hence,
α1 is exactly determined by the other αi ’s, and if we were to hold α2 , . . . , αm
fixed, then we can’t make any change to α1 without violating the con-
straint (19) in the optimization problem.
Thus, if we want to update some subject of the αi ’s, we must update at
least two of them simultaneously in order to keep satisfying the constraints.
This motivates the SMO algorithm, which simply does the following:
Repeat till convergence {
1. Select some pair αi and αj to update next (using a heuristic that
tries to pick the two that will allow us to make the biggest progress
towards the global maximum).
2. Reoptimize W (α) with respect to αi and αj , while holding all the
other αk ’s (k 6= i, j) fixed.
}
To test for convergence of this algorithm, we can check whether the KKT
conditions (Equations 14-16) are satisfied to within some tol. Here, tol is
the convergence tolerance parameter, and is typically set to around 0.01 to
0.001. (See the paper and pseudocode for details.)
The key reason that SMO is an efficient algorithm is that the update to
αi , αj can be computed very efficiently. Lets now briefly sketch the main
ideas for deriving the efficient update.
Lets say we currently have some setting of the αi ’s that satisfy the con-
straints (18-19), and suppose we’ve decided to hold α3 , . . . , αm fixed, and
want to reoptimize W (α1 , α2 , . . . , αm ) with respect to α1 and α2 (subject to
the constraints). From (19), we require that
m
X
(1) (2)
α1 y + α2 y =− αi y (i) .
i=3

Since the right hand side is fixed (as we’ve fixed α3 , . . . αm ), we can just let
it be denoted by some constant ζ:
α1 y (1) + α2 y (2) = ζ. (20)
We can thus picture the constraints on α1 and α2 as follows:
24

H α1y(1)+ α2y(2)=ζ
α2

L
α1 C

From the constraints (18), we know that α1 and α2 must lie within the box
[0, C] × [0, C] shown. Also plotted is the line α1 y (1) + α2 y (2) = ζ, on which we
know α1 and α2 must lie. Note also that, from these constraints, we know
L ≤ α2 ≤ H; otherwise, (α1 , α2 ) can’t simultaneously satisfy both the box
and the straight line constraint. In this example, L = 0. But depending on
what the line α1 y (1) + α2 y (2) = ζ looks like, this won’t always necessarily be
the case; but more generally, there will be some lower-bound L and some
upper-bound H on the permissable values for α2 that will ensure that α1 , α2
lie within the box [0, C] × [0, C].
Using Equation (20), we can also write α1 as a function of α2 :

α1 = (ζ − α2 y (2) )y (1) .

(Check this derivation yourself; we again used the fact that y (1) ∈ {−1, 1} so
that (y (1) )2 = 1.) Hence, the objective W (α) can be written

W (α1 , α2 , . . . , αm ) = W ((ζ − α2 y (2) )y (1) , α2 , . . . , αm ).

Treating α3 , . . . , αm as constants, you should be able to verify that this is


just some quadratic function in α2 . I.e., this can also be expressed in the
form aα22 + bα2 + c for some appropriate a, b, and c. If we ignore the “box”
constraints (18) (or, equivalently, that L ≤ α2 ≤ H), then we can easily
maximize this quadratic function by setting its derivative to zero and solving.
We’ll let α2new,unclipped denote the resulting value of α2 . You should also be
able to convince yourself that if we had instead wanted to maximize W with
respect to α2 but subject to the box constraint, then we can find the resulting
value optimal simply by taking α2new,unclipped and “clipping” it to lie in the
25

[L, H] interval, to get



 H if α2new,unclipped > H
α2new = αnew,unclipped if L ≤ α2new,unclipped ≤ H
 2
L if α2new,unclipped < L

Finally, having found the α2new , we can use Equation (20) to go back and find
the optimal value of α1new .
There’re a couple more details that are quite easy but that we’ll leave you
to read about yourself in Platt’s paper: One is the choice of the heuristics
used to select the next αi , αj to update; the other is how to update b as the
SMO algorithm is run.

You might also like