Docsity

CS 229 Notes: Machine Learning, Study notes of Artificial Intelligence

Toggle sidebar
bg1
CS 229 NOTES: MACHINE LEARNING
ARUN DEBRAY
DECEMBER 2, 2013
CONT ENT S
Part 1. Supervised Learning 1
1. Introduction: 9/23/13 1
2. Linear Regression, Gradient Ascent, and the Normal Equation: 9/25/13 3
3. Linear Algebra and Matrix Calculus Problem Session: 9/27/13 6
4. Locally Weighted Regression, MLE, and Logistic Regression: 9/30/13 8
5. Generalized Linear Models: 10/2/13 12
6. Probability and Statistics Problem Session: 10/4/13 13
7. Generative Learning Algorithms: 10/7/13 15
8. Laplace Smoothing: 10/9/13 17
9. MATL AB Tutorial: 10/11/13 20
10. Support Vector Machines: 10/14/13 22
11. Support Vector Machines II: 10/16/13 24
12. Convex Optimization I: 10/18/13 26
13. Support Vector Machines III: 10/21/13 27
Part 2. Learning Theory 30
14. Learning Theory: 10/23/13 30
15. Convex Optimization II: 10/25/13 32
16. The VC Bound and Model Selection: 10/28/13 34
17. Bayesian Statistics: 10/30/13 35
Part 3. Unsupervised Learning 37
18. Clustering: 11/4/13 37
19. k-means: 11/6/13 38
20. Factor Analysis: 11/11/13 38
21. Principal Components Analysis and Independent Components Analysis: 11/13/13 39
22. Independent Components Analysis: 11/18/13 40
Part 4. Reinforcement Learning and Control 41
23. Introduction to Reinforcement Learning: 11/20/13 41
24. State Action Models and Linear Dynamical Systems: 12/2/13 42
Part 1. Supervised Learning
1. INT RODU CTI ON: 9/23/13
“A few days ago, the enrollment in this class was 650 students. I imagine it’s a bit higher now.” [Ed. note: There
are 735 people enrolled in this class as of today.1]
First, it’s worth asking: what is machine learning? It grew out of work in AI and attempts to understand data and create
self-customizing programs that can’t be made by hand. Machine learning algorithms are everywhere, such as web search,
photo tagging, and spam detection. Machine learning has become the preferred approach to handling large amounts of data.
1For comparison, there are “only” 656 people in CS 106A.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a

Partial preview of the text

Download CS 229 Notes: Machine Learning and more Study notes Artificial Intelligence in PDF only on Docsity!

CS 229 NOTES: MACHINE LEARNING

ARUN DEBRAY DECEMBER 2, 2013

CONTENTS

Part 1. Supervised Learning 1

  1. Introduction: 9/ 23 / 13 1
  2. Linear Regression, Gradient Ascent, and the Normal Equation: 9/ 25 / 13 3
  3. Linear Algebra and Matrix Calculus Problem Session: 9/ 27 / 13 6
  4. Locally Weighted Regression, MLE, and Logistic Regression: 9/ 30 / 13 8
  5. Generalized Linear Models: 10/ 2 / 13 12
  6. Probability and Statistics Problem Session: 10/ 4 / 13 13
  7. Generative Learning Algorithms: 10/ 7 / 13 15
  8. Laplace Smoothing: 10/ 9 / 13 17
  9. MATLAB Tutorial: 10/ 11 / 13 20
  10. Support Vector Machines: 10/ 14 / 13 22
  11. Support Vector Machines II: 10/ 16 / 13 24
  12. Convex Optimization I: 10/ 18 / 13 26
  13. Support Vector Machines III: 10/ 21 / 13 27

Part 2. Learning Theory 30

  1. Learning Theory: 10/ 23 / 13 30
  2. Convex Optimization II: 10/ 25 / 13 32
  3. The VC Bound and Model Selection: 10/ 28 / 13 34
  4. Bayesian Statistics: 10/ 30 / 13 35

Part 3. Unsupervised Learning 37

  1. Clustering: 11/ 4 / 13 37
  2. k-means: 11/ 6 / 13 38
  3. Factor Analysis: 11/ 11 / 13 38
  4. Principal Components Analysis and Independent Components Analysis: 11/ 13 / 13 39
  5. Independent Components Analysis: 11/ 18 / 13 40

Part 4. Reinforcement Learning and Control 41

  1. Introduction to Reinforcement Learning: 11/ 20 / 13 41
  2. State Action Models and Linear Dynamical Systems: 12/ 2 / 13 42

Part 1. Supervised Learning

  1. INTRODUCTION: 9/ 23 / 13 “A few days ago, the enrollment in this class was 650 students. I imagine it’s a bit higher now.” [Ed. note: There are 735 people enrolled in this class as of today.^1 ]

First, it’s worth asking: what is machine learning? It grew out of work in AI and attempts to understand data and create self-customizing programs that can’t be made by hand. Machine learning algorithms are everywhere, such as web search, photo tagging, and spam detection. Machine learning has become the preferred approach to handling large amounts of data.

(^1) For comparison, there are “only” 656 people in CS 106A.

In the past several years, there have been a surprising number of startups that use machine learning to deal with large amounts of data. This class is not about startups, but this is an illustration of its increasing utility. Interestingly, some of these companies are very happy to hear that you get an A in this class!

Prerequisites. There are three kinds of prerequisites:

  • It will be necessary to know enough computer science principles to be able to write programs.
  • It’s going to be necessary to understand basic probability theory, e.g. random variables and such. If this is a problem, there will be a review session.
  • Linear algebra on the order of Math 51 or 104.^2 This is things such as the idea of vectors and matrices, matrix inverses, etc. Knowing things like eigenvalues and eigenvectors is great, but not strictly necessary.

In addition to this, it will be necessary to use Matlab (or its open source alternative, Octave) for some of the programming assignments. It is one of the best languages for prototyping machine learning algorithms, though larger-scale algorithms tend to be reimplemented in C++ or Java. SciPy and NumPy are also useful prototyping choices. There are other reasons Matlab is useful, too. However, some of the Friday discussion sections will teach Matlab for those who do not know it.

Project. This class will have a significant final project at the end. Most people approach this by using machine learning algorithms to implement something interesting. When choosing your project, take a look at the past projects posted on the course website. There are lots of places to get project ideas. In addition to looking at past projects, there are research groups across campus have project ideas that they would be happy to see you work on. A list of this will be posted on the course website at some point.

Cool Stuff. As is traditional, we will begin with a definition.

Definition (Arthur Samuel, 1959). Machine learning is the field of study that gives computers the ability to learn without being explicitly programmed.

Samuel wrote a checkers-playing program that played thousands of games against itself, and eventually managed to consistently beat him. This was a milestone in the history of artificial intelligence, one of the first (if not the first) of the programs to exceed the ability of its creator. There’s a more modern definition that is more commonly cited today:

Definition (Tom Mitchell, 1998). A computer program is said to learn from an experience E with respect to some task T and some performance measure P if its performance on T , measured with respect to P , improves after E.

Example 1.1 (Supervised Learning and Regression). Consider a graph that plots the area of a house against its price. Then, the goal is to understand how much to sell a house for given its size. This is an example of supervised learning; for example, the algorithm might fit a line or a quadratic curve to the data. Specifically, this is an example of a regression problem, because the price is a continuous variable (or at least close enough).

Example 1.2 (Classification). If the dependent variable is discrete, then one has a classification problem. For example, one may have a set of images of a tumor and want to predict whether it is malignant or benign (e.g. given some feature of it, such as its size). One may also estimate probabilities rather than just picking one output.

Though both examples above make predictions based on a single feature, other problems might need to use multiple features (e.g. the tumor size and the age of the patient for Example 1.2). Then, classifying these into some number of features can be viewed as drawing a line or hyperplane between two sets of points. In general, knowing which sets of features to use is one of the most difficult questions in machine learning, and can lead to much more or less effective results, and there is even an effective algorithm with an infinite number of features. This leads to questions in infinite-dimensional space, and boils down to a powerful algorithm called a support vector machine (SVM). This leads to questions about how one can hold an infinite list in a finite computer’s memory, but there is a nice way to handle this — stay tuned. Supervised learning has nice applications to autonomous driving. Here,^3 the human driver demonstrates correct driving behavior in various conditions, and the car picks up on this to determine what to do in various situations. There’s a lot of trickery in getting the driver’s motions and the “circumstances” into plain, precise data. Also, if the experiment is successful enough, the car learns the particular habits of its driver... Impressively, the algorithms used for that car will be superseded by things taught in this class in week four. This class will also spend some time on the theory of learning.^4 As always, learning the theoretical tools will help one create better applications, such as by knowing which of many approaches is the most likely to be successful, causing one to use

(^2) Dr. Ng said Math 103, but I don’t believe that course exists. (^3) A video was shown from 20 years ago that demonstrated this. Scarily enough, it contained the sentence, “At first, the car steers randomly.” (^4) The professor has a mathematician friend who claims that he does math to understand the truth and beauty of the universe, but then claimed that in this class, “we’re not going to see any truth or beauty.”

Since one wants h θ (x) to be close to y, one might try to minimize the distance (squared error) between the two, so the goal is to minimize

J ( θ ) =

∑^ n

i= 1

h θ

Ä

x(i)^ − y(i)

ä 2 .

Here, the 1 / 2 is there for convenience (since it’s minimized anyways, this will make life easier). Squared-error is particularly helpful because it implies that the errors tend to be Gaussian, but other models exist.

Gradient Descent. This method for learning a linear function starts with some θ , such as θ = 0 , and then updates θ to minimize J ( θ ). Specifically, the goal is to update θ by a small amount in the direction of the steepest descent of J ( θ ) at θ.

FIGURE 1. An illustration of gradient descent, from Wikipedia. “A small step for man, a giant leap for machine learning.”

In each step, θ is updated as follows:

θ j := θ j − α

∂ θ j

J ( θ ). (1)

Here, α is a constant called the learning rate. Larger values of α correspond to larger step sizes overall, though as the minimum is approached the step sizes lessen. As an example of why one would want to compute the partial derivative, imagine m = 1. Then,

J ( θ ) =

(h θ (x) − y)^2

∂ θ j

J ( θ ) =

∂ θ j

(h(x) − y)^2

· (h θ (x) − y)

∂ θ j

(h θ (x) − y)

= (h θ (x) − y)

∂ θ j

( θ 0 x 0 + θ 1 x 1 + y)

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

Now, (1) is iterated until the algorithm converges to within some desired tolerance. By the above, this can be simplified slightly to

θ j := θ j − α

∑^ n

i= 1

(h θ

Ä

x(i)^ − y(i)

ä x (i) j.

In gradient descent, it is important to remember the difference between a local and a global minimum; otherwise, the function could just get caught in a local minimum. However, if J ( θ ) is convex, then there is a single local minimum and it is also a global minimum, so gradient descent necessarily converges to the optimum. In some sense, the function is minimized by finding a θ such that ∇J ( θ ) = 0; that is exactly what gradient descent finds, and other methods do the same thing in a different way. One disadvantage of gradient descent is that each step requires summing over all m examples, which is extremely bad when m is large (what if you’re working with m = 3 · 108 , as in the United States Census data?). This algorithm is specifically called batch gradient descent, which means that the entire input is looked at in each step. A different algorithm called stochastic gradient descent deals with this problem better and faster; but it will be covered in more depth in the lecture notes. For some classes of functions, one can analytically solve for the minimum. This tends to involve lots of ugly calculations, but a simplified notation of calculus of matrices makes all of these derivations much less complicated. These will be covered in better depth in the lecture notes and in section.

Definition. The derivative of J with respect to θ is the vector

∇ θ (J ) =

∂ J ∂ θ 0 .. . ∂ J ∂ θ n

∈ Rn+^1 ,

since θ ∈ Rn+^1 as well.

Now, it is possible to simplify gradient ascent into θ := θ − α ∇ θ J.

The n lines of equations are efficiently condensed into one.

More generally, suppose A ∈ Rm×n^ is a matrix and f : Rm×n^ → R, such as A =

A 11 A 12

A 21 A 22

and f (A) = A 11 + A^212. Then,

∇A f (A) =

∂ f ∂ A 11...^

∂ f ∂ A 1 n .. .

∂ f ∂ Am 1...^

∂ f ∂ Amn

∈ Rm×n^.

This is a compact way of collecting all of the component partial derivatives. The derivative matrix always has the same dimension as the original one.

With f as above, ∇A f (A) =

1 2 A 12

Now, some properties of matrices will be presented without proof. You can prove them on your own if you like.

Definition. If A is a square n × n matrix, the trace is the sum of its diagonal entries: tr A =

∑n i= 1 Ai i^. Though this is a function, it can use this operator-like notation. Also, note the special case a ∈ R, for which tr a = a. We have the following facts:

  • If A and B are square matrices of the same dimension, then tr AB = tr BA.
  • The cyclic permutation of trace: tr ABC = tr C AB = tr BC A.
  • ∇A tr AB = ∇A tr BA = BT. This should be thought of as a function in A, where B is a provided constant: f (A) = tr AB.
  • ∇A tr AATC = C A + C TA.

Definition. The design matrix of some training data is made by stacking all of the training examples as rows:

X =

x(^1 ) .. . x(n)

 ∈^ R

n×n (^).

Thus,

X θ =

x(^1 )T^ · θ .. . x(n)T^ · θ

h(x(^1 )) .. . h(x(n))

• (AB)T^ = BTAT.

• (AT)T^ = A.

Again, these are things you can prove yourself if you want.

Definition. A matrix is symmetric if AT^ = A. A matrix for which AT^ = −A is called anti-symmetric.

Symmetric matrices have interesting properties, and thus come up in the material more often. The inverse of a matrix doesn’t always exist; if it does, then it is the matrix A−^1 of A such that A−^1 A = AA−^1 = I (the identity matrix, with 1 along the diagonal and 0 elsewhere). If such an inverse exists, A is called nonsingular. We have some more properties:

  • (A−^1 )−^1 = A.
  • (AT)−^1 = (A−^1 )T. Sometimes, this is denoted A−T.
  • (AB)−^1 = B−^1 A−^1.

These properties hold when everything is well-behaved and invertible, so don’t forget that and misapply them. We saw the trace tr(A) in class, which is linear: tr(A + B) = tr(A) + tr(B). tr(AT) = tr(A), additionally, and tr(AB) = tr(BA). This last property is particularly useful for computations, and can be generalized to larger products: tr(ABC ) = tr(C AB) = tr(BC A) and so on. However, this is not true for random orders: they must be cyclical.

Definition. The Frobenius norm of a matrix A is

‖A‖F =

tr(AAT) =

∑m

i= 1

∑^ n

j = 1

A^2 i j.

Proving the last equality above would be a good way to get better at using these definitions. Another useful function is the determinant. It will be briefly discussed here, and a better explanation with a more geometric angle^7 is presented. The formal definition is

det A = |A| =

∑^ m

i= 1

(− 1 )i+^ j^ ai j A / i / j ,

where A / i / j (the cofactor matrix) is the matrix obtained by removing the ith^ row and the j th^ column. Also, note that j doesn’t

appear in the definition; its choice happens to be arbitrary. Here are some properties of the determinant:

  • det(AB) = det(A) det(B).
  • det(A) = 0 iff A is singular (i.e. noninvertible).
  • det(AT) = det(A).
  • If A is nonsingular, det(A−^1 ) = 1 / det(A).

Definition. A family u 1 ,... , un of vectors is linearly independent if for every family ( α 1 ,... , α n ) ∈ Rn^ , α 1 u 1 + · · · + α n un = 0 implies that α 1 = 0,... , α n = 0.

The notion of linear independence can be used to define the rank of a matrix; see the lecture notes for this concept.

Definition. The range of a matrix A, denoted R(A), is the set R(A) = {Ax | x ∈ Rm^ }. The null space of A, denoted N (A), is the set N (A) = {x ∈ Rm^ | Ax = 0 }.

Notice that R(A) ⊂ Rn^ , but N (A) ⊂ Rm^ , which can be remembered by tracking which corresponds to the input space and which corresponds to the output space. The null space is sometimes also denoted the kernel, but not in this class.

Definition. ( λ , x) is an eigenvalue-eigenvector of A if x 6 = 0 and Ax = λ x.

For small matrices, one finds the eigenvalues by computing the roots to det( λ I − A) = 0. This polynomial (since it ends up being a polynomial) is called the characteristic polynomial. Eigenvectors and eigenvalues play a role in a lot of fields, but will be the most useful in this class in principal component analysis.

Definition. A matrix U ∈ Rm×m^ is orthogonal if U TU = U U T^ = I.

In other words, U −^1 = U T.

Claim. If U is an orthogonal matrix, then‖U x‖ 2 = ‖x‖ 2 for any x ∈ Rm^.

(^7) No pun intended.

Proof. ‖U x‖^22 = (U x)TU x = xTU TU x = xTx = ‖x‖ 2. Ç

This result is very useful in the matrix calculus, so don’t forget it!

Claim. Let A be a symmetric^8 n × n mstrix and λ 1 ,... , λ n be its eigenvalues. Then, tr(A) =

∑n i= 1 λ i^. Proof. One useful property is that every symmetric matrix A is of the form A = U ΛU T, where U is orthogonal and Λ is diagonal. Because of this equality, tr(A) = tr(U ΛU T) = tr(ΛU TU ) = tr(Λ) =

∑n i= 1 λ i^.^ Ç The key ingredient in the proof, other than the decomposition, is that tr(AB) = tr(BA). Similarly to the above proof, it is possible to show that det(A) =

∏n i= 1 λ i^. If A ∈ Rm×m^ is a symmetric matrix, then the quadratic form associated with A is the function xTAx ∈ R.^9

Definition.

  • A matrix A is positive definite if for all x ∈ Rn^ \ 0, xTAx > 0.
  • A matrix A is semi-positive definite if for all x ∈ Rn^ , xTAx ≥ 0.
  • Negative definiteness and semi-negative definiteness are defined similarly.

An important fact is that all of the eigenvalues of a positive definite matrix are positive, and all those of a semi-positive definite matrix are nonnegative. These are also good, not too difficult things to prove. Similar results hold for negative (semi)-definite matrices.

Matrix Calculus. Suppose f : Rn^ → R (i.e. it is a vector-valued function), such as f (a) = bTa for some b ∈ Rn^. Then, the gradient of f is defined to be ∇v f (x)i = ∂ f ∂ xi^. With^ f^ as in the example,^

∂ f ∂ xk^ =^ bk^ , so^ ∇v^ f^ (x) =^ b^ for all^ v^ ∈^ R

n (^).

Now, if f is a function of a matrix, as in f (A) = xTATAx for some x, then (∇A f )pq = (^) ∂∂ A^ f pq

. Ask yourself: how is this function defined on Apq? Then,

xTATAx =

∑^ n

i, j = 1

xi A^2 i j xj.

if M = ATA, then this simplifies a bit: xTM x =

xi Mi j xj. Thus, ∇M fk (x) is nonzero when i = k or j = k; in the first case, this gives

∑m j = 1 Mk j^ xj^ , and when^ k^ =^ j^ , one adds^

∑n i= 1 AMi k^ xi^ , so the result is ∑^ m

j = 1

Mk j xj +

∑^ n

i= 1

AMi k xi.

Since M is symmetric, this is the kth^ component of 2M x, so ∇x f (x) = 2 M x. For another example, if f (x) = ‖Ax − b‖^22 , then

f (x) = (Ax − b)T(Ax − b) = xTATAx − bTAx − xTATb + bTb = xTATAx − 2 bTAx + bTb. Since the gradient is linear, this simplifies to ∇x f (x) = 2 ATAx − 2 ATb,

since bTAx = (ATb)T, and the gradient of the inner product is already known. Since we wish to find the global minimum, where this gradient is nonzero, then ATAx = ATb at the gradient, or x = (ATA)−^1 ATb.

4. LOCALLY WEIGHTED REGRESSION, MLE, AND LOGISTIC REGRESSION: 9/ 30 / 13

“I’m still not entirely sure why I showed you that [ video ] .” Recall the definitions provided last lecture: the function h θ (x) =

θ j xj = θ Tx, the function J ( θ ) = ( 1 / 2 )

h θ (x(i)^ − y(i)) is the sum of squares (to be minimized), and a direct solution can be given by θ = (X TX )−^1 X Ty.

(^8) This condition happens to be completely unnecessary for the result; it is true for any square matrix A. (^9) Consult the lecture notes to see why symmetry is necessary.

To make calculations more tractable, one takes the logarithm, producing the creatively named log-likelihood:

` ( θ ) = log L( θ ) = log

∏^ n

i= 1

σ

p 2 π

exp −

(y(i)^ − θ Tx(i))^2 2 σ^2

∑^ n

i= 1

log

σ

p 2 π

  • log exp −

(y(i)^ − θ Tx(i))^2 2 σ^2

= m log

σ

p 2 π

∑^ m

i= 1

(y(i)^ − θ Tx(i))^2 2 σ^2

and since the first term is invariant, then to maximize ` ( θ ) and therefore L( θ ), one wishes to minimize

J ( θ ) =

∑^ m

i= 1

(y(i)^ − θ Tx(i))^2 2 σ^2

Notice that the final answer doesn’t depend on σ^2. This will be significant when this class turns to generalized linear models.

Logistic Regression. Now we turn to a classification problem, where y(i)^ ∈ { 0 , 1 }. Here, a linear regression isn’t the smartest, though it does work sometimes. One can add a training example with y(m+^1 )^ = 1 to the far right, which makes the data fit very differently. This is a problem, because it shouldn’t make any difference to the prediction... This is why it is bad to use linear regression on classification problems; sometimes it works, but often it doesn’t, and in any case predicting values outside of [ 0 , 1 ] is a problem. Thus, an algorithm called logistic regression is used to address both of these problems.^11 Here, h θ (x) ∈ [0, 1] is given by

h θ (x) =

1 + e− θ

Tx =^ g^ ( θ

Tx).

Here, g (z) = 1 / ( 1 + e−z^ ) is called the sigmoid or logistic function, with graph given in Figure 2. This is convenient because

FIGURE 2. The sigmoid function g (z). Source: Wikipedia.

statistical outliers that messed up the linear model are okay for the logistic one, and all of the predicted values lie in [ 0 , 1 ]. The function smoothly goes between 0 and 1 along the real line, but it’s particularly useful to make the algorithm convex (which implies a unique global solution), and because it ends up being a special case of a generalized linear model. This makes it possible for more powerful, general algorithms to work on logistic regression.

(^11) Logistic regression is a classification algorithm, not a regression algorithm. Take care to not confuse this.

The probabilistic interpretation of this model is that P (y = 1 | x; θ ) = h θ (x), and similarly, P (y = 0 | x; θ ) = 1 − h θ (x). In other words, since y ∈ {0, 1}, then

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

This can be checked by filling in the two possibilities for y. Now, let’s apply a maximum likelihood estimate:

L( θ ) =

∏^ m

i= 1

P (y(i)^ | x(i); θ )

∏^ m

i= 1

h(x(i))y

(i) ( 1 − h(x(i)))^1 −y

(i) .

It is again possible to calculate the log-likelihood ` ( θ ) = log L( θ ) as before. This allows one to use gradient ascent to maximize the log-likelihood, by updating the parameters by

θ j := θ j + α

∂ θ j

` ( θ ),

where we are trying to maximize ` ( θ ) rather than minimizing (which is the same after flipping a sign, so it’s not huge). Here α is again the learning rate. After all the math is bashed out (as is done in the provided lecture notes), the rule is

θ j := θ j + α

∑^ m

i= 1

(y(i)^ − h θ (x(i)))x( j i).

The surprising thing about this is that cosmetically, it looks identical to the rule provided for gradient-descent for linear regression. These two algorithms were invented independently, and people at first wondered if they were the same, but since h θ is different in each case, then these are different algorithms, and in particular will have different results when run on different data. These algorithms aren’t particularly new; computers called Perceptrons used a similar algorithm in the 1960s. In general, logistic regression is a very common machine learning algorithm. Targeted advertisements, for example, often use it or a small variant.

Newton’s Method. There are multiple ways of optimizing a function; here’s another one called Newton’s method. For the presentation in today’s lecture, we will consider θ ∈ R rather than θ ∈ Rn+^1. Then, the goal is to maximize the log-likelihood,

so define f ( θ ) = (^) dd θ ` ( θ ), so the goal is to find a theta such that f ( θ ) = 0. Unlike linear regression, there is no known way to solve this in closed form.^12 However, Newton’s method is a very effective way of approximating solutions. Similarly to gradient-descent, this method starts with an initial guess θ 0. Take the tangent like to f at θ 0 , and let θ 1 be the place where that line intersects the x-axis. Then,repeat with the tangent line to f at θ 1 , and so on. Now for the math: how does one obtain θ 1 from θ 0? Let ∆ = | θ 1 − θ 0 |. Thus, the slope of f at θ 0 is f ′( θ 0 ), but also f ( θ 0 ) / ∆, so one calculates ∆ = f ( θ 0 ) / f ′( θ 0 ), so the updating step is

θ (i+^1 )^ := θ (i)^ −

f ( θ (i)) f ′( θ (i))

Alternatively, dispense with f entirely to get

θ (^1 )^ = θ (^0 )^ −

_ ′( _θ_ ) _ ′′( θ )

Newton’s method converges very quickly. Specifically, it has quadratic convergence; each iteration, the error is roughly squared (which sounds bad, but for small errors is of course very good!). This is much faster than gradient descent, though it is more computationally intensive. In the more general case where θ ∈ Rn+^1 , this becomes

θ (t^ +^1 )^ = θ (t^ )^ + H −^1 (∇ θ J ),

where H is the Hessian matrix of ` ( θ ). This is explained more fully in the notes and the problem set. Inverting a matrix is generally computationally expensive, which is the primary drawback of this method.

(^12) Hello, Galois!

(1) Write out the formula for the distribution that is being learned. (2) Show that it is an exponential family for some appropriate choice of parameters. (3) Setting η = θ Tx, write h θ (x) in terms of θ and x as in Example 5.1.

This has a big advantage in that the GLM is guaranteed to have a convex optimization problem when one uses maximum likelihood estimation. This means that gradient ascent always finds the global maximum, which is really nice. Thus, the formula

θ j := θ j − α

∑^ m

i= 1

Ä

h θ (x(i)^ − y)

ä x( ji)

also still applies. The assumptions and machinery behind GLMs are kind of tricky; while the mathematics are all fairly reasonable, the overarching understanding, seeing how the pieces fit together, is harder and can be seen by deriving one of the examples for oneself. For example, a good choice (e.g. on our problem set) is the Poisson model.

Softpass Regression. Using the generalized linear model, one can use the multinomial distribution to obtain a useful algorithm. This is a bit more complex, because T (y) 6 = y, but it’s useful for algorithms that classify y into k > 2 choices, which lends itself to many types of applications. Geometrically, this algorithm draws boxes across the data, rather than a separating line (hyperplane). For this derivation, assume k = 4; the lecture notes contain the general case, but this will simplify the derivation a bit. The first step is to express the multinomial distribution as an exponential one. Let the parameters be φ 1 ,... , φ 3 so that P (y = i) = φ i. However, since the probabilities have to sum to 1, φ 4 = 1 − ( φ 1 + φ 2 + φ 3 ), so they’re not independent. Let φ = ( φ 1 , φ 2 , φ 3 ); φ 4 exists but is not considered a separate parameter. These can be compressed into more compact notation, similarly to what was done in the case of the Bernoulli distribution earlier: let T (i) = ei for i = 1 ,... , 3, and T 4 = 0 ; in general, T (i) ∈ Rk−^1 if there were k parameters. It will be useful to have something called indicator notation, which can be considered as mapping true statements to 1 and false ones to zero: I {True} = 1 and I {False} = 0. For example, I { 2 + 3 = 5 } = 1. This means that T (y)i = {y = i}, and

P (y) =

∏^ k

j = 1

φ I j^ {y=^ j^ }

= φ T (y) 1 1 φ

T (y) 2 2 φ

T (y) 3 3 φ

1 −T (y) 1 −T (y) 2 −T (y) 3

After some amount of massaging, this becomes

= b (y) exp( η TT (y) − a( η )),

where T is as above, a( η ) = − log φ 4 , b (y) = 1, and η = ( φ 1 /φ 4 , φ 2 /φ 4 , φ 3 /φ 4 )T. Once these assumptions have been made, along with η i = θ T i x, then under this model,

P (y = i) =

θ T i x

1 + e θ

T 1 x

  • e θ

T 2 x

  • e θ

T 3 x.^ (3)

In order to fit this model, the final step is to write down the learning algorithm: if (x(i), y(i)) is the training set, with i = 1 ,... , m, then one can make the maximum likelihood estimate

L( θ ) =

∏^ m

i= 1

P (y(i)^ | x(i); θ ) =

∏^ m

i= 1

∏^4

j = 1

φ I^ {y

(i)= j } j ,

where the φ i are given as in (3). Given a training set, one fits the parameters to the model by writing out the likelihood and maximizing it as a function of θ , which is nice because it’s a convex function.

  1. PROBABILITY AND STATISTICS PROBLEM SESSION: 10/ 4 / 13 “Statistics is rigorous machine learning.” – Steven Boyd

This session will give a handwavy definition of probability, followed by useful properties of it for the problem sets. First, consider an example:

Example 6.1. If one rolls a die, the sample space is the set of all possible outcomes: Ω = { 1 , 2 , 3 , 4 , 5 , 6 }. One might have subsets of these, such as F = {1, 2}.

Formally, probability is a way of assigning numbers to subsets of a sample space Ω. It is required to satisfy certain axioms:

  • P (A) ≥ 0 for every A ⊂ Ω.
  • If A 1 and A 2 are disjoint sets, P (A 1 ∪ A 2 ) = P (A 1 ) + P (A 2 ). Geometrically, assigning probability in a sense like area makes these notions both make sense.
  • P (Ω) = 1.
  • If A ⊂ B, then P (A) ≤ P (B). This also makes sense geometrically: their intersection is A itself.
  • More generally, for any sets A and B, P (A ∩ B) ≤ min(P (A), P (B)). This is akin to the statement that the area of two overlapping sets A and B is less than the area of A (since the intersection is contained in A), and less than the area of B (since it’s also contained in B).
  • P (¬A) = 1 − P (A). There’s also something called the Law of Total Probability: if {Ai } is any collection of disjoint events, then

i P^ (Ai ) =^ 1. Next, consider conditional probability. This is the chance of something happening given (already known) that something else happened. For example, for dice the probability of rolling a 1 given that an odd number is rolled is P ( 1 | 1 , 3 , 5 ) = 1 / 3, which differs from the total probability P ( 1 ) = 1 / 6. There’s a nice formula for this, which is P (X | Y ) = P (X ∩ Y ) / P (Y ). In terms of a Venn diagram, one just works inside one blob Y rather than the whole space; then, the goal is to ask how much of this blob is X. Conditional probability leads naturally into independence: two events A and B are independent if P (A ∩ B) = P (A)P (B). Intuitively, this means that the two events have no effect on each other, or no causal relationship. It can be more complicated than that, but this is a useful first way to think about it. If A and B are independent events, then P (A | B) = P (A); intutively, this says that if two events are independent, then knowing one has no effect on the other. Though thus far only events have been discussed, but one can speak of random variables. A random variable is a variable that could take on several values corresponding to different events. Though this sounds questionable, it’s mostly a piece of useful notation, as it allows for one to chart the different outcomes of an experiment. In the discrete case, a random variable X takes on at a value x the probability P (x), which makes a lot of sense, but in the continuous case things are a bit weirder, since at a single value P (x) = 0 is perfectly fine, but over some interval [x 1 , x 2 ] the probability P ([x 1 , x 2 ]) is nonzero, and in fact is given by P (a ≤ x ≤ b ) =

∫ (^) b a p(x)^ dx. In the discrete case, the random variable described above gives the function called the probability mass function; in the continuous case, p(x) is called the probability density function. Interestingly, the probability density function may be larger than 1 at some value, as long as

−∞ p(x)^ dx^ =^ 1. For example, if p(x) = 0 if |x| ≥ 1 / 4 and p(x) = 2 otherwise, then p is a valid probability density function, but it is everywhere larger than

In a maximum likelihood estimate, one has a distribution parameterized by θ to maximize P (y | x, θ ). This can be thought of as changing the probability distribution (which is what is given by θ ) to fit the model. Another useful idea is that of expectation. The expectation of a function g is E[ g (x)] =

x g^ (x)^ p(x). This is the “average value” of g (x), weighted by the probability of each input x. For example, in a lottery with a 0.25 chance of winning $100, 0. 5 chance of winning $50, and 0 .25 chance of winning nothing, then in expectation, one would win $50 from this lottery (which is the average, albeit over a large number of games). For continuous variables, the sum becomes an integral:

E[g (x)] =

−∞

g (x) p(x) dx,

where p(x) is now a probability density function, not a probability mass function. Some useful properties of expectation:

  • The expected value of a constant is that constant: E[a] = a for a ∈ R.
  • Constants can be pulled out of an expectation: E[a f (x)] = aE[ f (x)].
  • Expectation commutes with sums: E[ f (x) + g (x)] = E[ f (x)] + E[g (x)]. There’s another quantity, called variance. This is defined as Var(X ) = E[(X − E[X ])^2 ]. This measures how far all of the data is from the mean. The units of variance are the units of the x-axis, squared, which could be important in some sorts of problems. It’s possible to derive a useful formula for the variance: let μ = E[X ] be the mean of the dataset.

Var(X ) = E[(X − E[X ])^2 ] = E[(X − μ )^2 ] = E[X 2 − 2 X μ + μ^2 ] = E[X ]^2 − 2 μ E[X ] + μ^2 = E[X ]^2 − μ^2

since μ is a constant. Sometimes this is also written as E[X 2 ] − E[X ]^2. This tends to be much easier to compute than the formula given in the definition. Some properties of variance:

  • If a is a constant, then Var(a) = 0.
  • Var(a f (x)) = a^2 Var( f (x)), where a is again a constant. Notice that this is different from the result for the expected value!

−

−

−

0

1

2

3

−

−

−

0

1

2

3

0

1

FIGURE 3. A graph of the multivariate Gaussian when n = 2. Source: Wikipedia.

estimate takes on these values:

φ =

m

∑^ m

i= 1

y(i)^ =

m

∑^ m

i= 1

1 {y(i)^ = 1 }.

μ 0 =

∑m i= 1 1 {y

(i) (^) = 0 }x(i) ∑m i= 1 1 {y

(i) (^) = 0 }.

This is the mean of all of the examples x(i)^ such that y(i)^ = 0, which is what makes the most sense. Thus, μ 1 is calculated in effectively the same way:

μ 1 =

∑m i= 1 1 {y

(i) (^) = 1 }x(i) ∑m i= 1 1 {y

(i) (^) = 1 }.

Σ is given in the lecture notes, since it’s a little messier. Then, the prediction for y is

arg max y

P (y | x) = arg max y

P (x | y)P (y) P (x)

If you haven’t seen arg max before, it just means to choose the value of y such that the quantity is maximized: minz (z − 5 )^2 = 0, but arg minz (z − 5 )^2 = 5. In some sense, rather than partitioning the plane into two parts, one calculates Gaussians for each of the positive and negative datasets, and asks which one is more likely. Thus, the decision boundary is actually different in these two cases: if one plots P (y = 1 | x) (for example, in a single-variate distribution), it has a logistic form as one goes from μ 0 to μ 1 , given the assumptions of GDA. However, the converse is not true: if this function is logistic, the assumptions of the generative model might not hold. This means that generative algorithms make stronger assumptions than discriminatory ones. Specifically, these assume y ∼ Bernoulli( φ ) and x | y = 0 and x | y = 1 are both Gaussian. In these cases, of course, this model will perform better, but otherwise it might be smarter to try something else. Here’s another set of assumptions that make P (y = 1 | x) logistic: that x | y = 0 ∼ Poi( λ 0 ), x | y = 1 ∼ Poi( λ 1 ), and y ∼ Bernoulli( φ ) again. This is actually a much more general assumption. However, logistic regression can handle any

exponential model, which shows that it is more robust in some cases; however, generative models are often more useful for small datasets. There are many such assumptions that lead it to be logistic.

Naïve Bayes. One nice advantage of GLMs is that they are fairly easy to implement and train, since there’s no iteration, and so on. Thus, though they might not be the best algorithms for the job, generative algorithms are useful for quick prototyping (such as for the project). A good example of this is the Naïve Bayes algorithm, which is rarely the best algorithm for the problem, but is fairly quick to set up. For a motivational example, consider spam detection, in which one examines an email and tries to classify it as spam or ham. More generally, one might want to sort emails into categories such as social, professional, etc., or eBay might wish to classify its auctions into different genres (which is actually what happens; they don’t ask the user to choose a category). Emails are interesting because they are different lengths, so obtaining a feature set requires a little thinking. A common way to do this is to take a list of English words {a, aa,... , zymurgy}, and let the feature vector of an email be a vector of the size of this list with a 1 in a given entry if the corresponding email has that word and a 0 if otherwise.^14 So write n = 10000, so that x ∈ { 0 , 1 }^10000. Thus, there are 2^10000 possibilities for x, so modeling this distribution explicitly over all of these outcomes (e.g. a multinomial distribution), unfortunate things clearly happen, so a different approach is necessary. Naïve Bayes adds one additional assumption, called the conditional independence assumption or the Naïve Bayes assumption: that the xi are independent given y. This means that

P (x 1 , x 2 , x 3 ,... , x 10000 | y) =

i= 1

P (xi | x 1 ,... , xi− 1 , y),

which is always true, but under the Naïve Bayes assumption, this simplifies to

P (x 1 , x 2 , x 3 ,... , x 10000 | y) =

i= 1

P (xi | y).

One way of explaining this is: suppose x 3 is the word “buy,” and x 1000 is the word “drugs.” Plenty of emails associate the two words. But: once you know an email is spam, there’s no correlation between these two words. This is not completely true, but it is convenient enough to be useful, and is the “conditional” in conditional independence. The parameters of this model are φ j |y= 1 = P (xj = 1 | y = 1 ), or the probability of a word appearing in a spam message, and φ j |y= 0 = P (xj = 1 | y = 0 ) (probability of a word appearing in a ham message), and φ j = P (y = 1 ). Then, one can write down the joint likelihood

L( φ y , φ j |y= 1 , φ j |y= 0 ) =

∏^ m

i= 1

P (x(i), y(i)).

Once one has a training set, one can fit the parameters by making a maximum likelihood estimate of the parameters as

φ y =

m

∑^ m

i= 1

1 {y(i)^ = 1 }

φ j |y= 1 =

∑m i= 1 1 {x

(i) j =^ 1,^ y

(i) (^) = 1 } ∑m i= 1 1 {y

(i) (^) = 1 } (5)

φ j |y= 0 =

∑m i= 1 1 {x

(i) j =^ 1,^ y

(i) (^) = 0 } ∑m i= 1 1 {y

(i) (^) = 0 } (6)

For the φ j |y , the intuition is to ask: of all emails in this bucket (spam or ham), what fraction of them contain this word? To implement a Naïve Bayes classifier, compute these parameters and then classify by setting P (y | x) = P (x | y)P (y), which follow from the above. In summary, generative models look at each component of the classification separately, forming independent models that lead to the classification.

8. LAPLACE SMOOTHING: 10/ 9 / 13

“I actually know the president of [ the University of ] Arizona pretty well. He’s a nice guy, an interesting guy.”

(^14) One more practical strategy is to take only the 10000 words most commonly seen in the recipient’s inbox.

parameters are

φ k|y= 0 =

∑m i= 1 1 {y

(i) (^) = 0 } ∑ni j = 1 1 {x

(i) j =^ k} ∑m i= 1 1 {y

(i) (^) = 0 }n i

where ni is the length of the ith^ email, so that x(i)^ ∈ Rni^. The numerator looks at all spam emails and counts up the number of times a given word is counted, and the denominator normalizes this by the total length of all ham emails. Though this was only written for ham, there is a φ k|y= 1 which looks very similar. However, we need to add Laplace smoothing to it, yielding

φ k|y= 0 =

∑m i= 1 1 {y

(i) (^) = 0 } ∑ni j = 1 1 {x

(i) j =^ k} 10000 +

∑m i= 1 1 {y

(i) (^) = 0 }n i

If 10000 seems arbitrary, then it is because that is the number of words in the dictionary. This classifier is better at handling variable-length data. As mentioned, this is not a particularly competent algorithm. However, it is easy to build and trains very quickly, so where it really shines is where one wants to quickly implement a learning algorithm on some dataset. Then, one can look at all of the mistakes that algorithm makes and fix them. This is particularly effective because one’s gut feelings about what is easy, difficult, or effective tend to be misleading, so getting some quick insight or feedback on a quick project (such as this class’ project) is very helpful. Note that the professor, one of the leading experts on spam and machine learning, doubts his intuition, which is significant. Spammers have of course tried to work around these classifiers. The most obvious solution is to misspell words to trip up the classifier, and some other spammers also spoof their email headers. And on the other side, the creation of honeypots has lead to an immense amount of training data. Thus, there are lots of potential approaches to a project, which are selected by gut feeling surprisingly often. However, clever or complicated models sometimes have hidden problems behind them that make them not work as effectively, so especially in industry or elsewhere where a working program is better than a clever one, looking for a simpler algorithm’s mistakes is easier than doing something fancy, and is likely to end up being more effective. Thus, a good starting point is to initialize a dataset and quickly build an end-to-end system, even if it’s known to not be very good. Then, it’s easier to find places to focus one’s time and optimize the algorithm. Notice how incompatible this is with the advice from CS 106A, but it jives with the notion that premature optimization is the root of all evil. Other than prototyping, Naïve Bayes doesn’t have too many uses. In some cases, the prototype is sufficient for the application, and in others, it’s so inefficient that it makes one rethink their data set. And there are plenty of other quick and dirty ways to prototype an algorithm, depending on the problem itself.

Nonlinear Classifiers and Neural Networks. Neural networks are an algorithm that were very popular about twenty years ago, and then fell out of favor relative to SVMs and the like. Though there has been a slight resurgence in its use recently, it is still a difficult technique to use. There is a lot of stuff happening in neural network research, though. To motivate this, suppose one has a classification problem with a very clear quadratic decision boundary (or a more generally nonlinear one). How would one modify this to return a nonlinear boundary? The following diagram can be used to represent logistic regression.

x 0

x 1 % % x 2 // //

1 + e− θ

Tx

x 3

The circle in the middle is some computational unit that derives the parameters. A neural network, originally designed to model how the brain works, took logistic regression to represent a neuron. This is a bad model, but not completely awful, so all that a neural network does is take these nodes and string them together, as so:

x 1 // & &

 

a 1 & & x 2

a (^2) // // h θ (x)

x 3

A A

a 3

x 4

E E

This diagram represents the following computation: a 1 = g (xT θ (^1 )), a 2 = g (xT θ (^2 )), and a 3 = g (xT θ (^4 )), and h θ (x) = g (aT θ (^4 )),

where a =

a 1 a 2 a 3

Thus, h θ (x) is a function of the parameters θ (^1 ),... , θ (^4 ), so the goal is to minimize the squared error, or some optimization objective akin to

min θ

∑^ m

i= 1

(h θ (x(i)) − y(i))^2.

This algorithm can output nonlinear classifiers because the sigmoid function is nonlinear, so one learns some set of nonlinear features {a 1 , a 2 , a 3 }, upon which logistic regression can be preformed again. The maximization problem is often solved with gradient descent, though in this specific context it tends to be called back-propagation. However, this optimization problem is nonconvex, so one might not necessarily find the global optimum, but it seems to work well enough in practice, if slowly. More complicated neural networks exist, with several layers of stacked “neurons.” One use of this was handwriting analysis for zip codes (though today, this is preformed on the entire address). It as able to handle some pretty pathological examples of numbers. Another example is text-to-speech conversion.

9. MATLAB TUTORIAL: 10/ 11 / 13

This class heavily stresses MATLAB^18 for the implementation. This is because it makes for an effective prototyping tool for quick development and testing, and after everything is set up it can be translated to a faster or lower-level language. Everything in this lecture can be found in the file session.m. In MATLAB, all numbers are treated as doubles, so 1/2 evaluates to 1/2. Most operations are the same as in other languages, though 6 = is ~= and xor is xor( , ). Strings are denoted with single quotes, and expressions are perfectly fine (e.g. c = 3 >= 1). Every operation has some sort of output, which can be suppressed by appending a semicolon. How about printing? If one sets a = pi, which does what one might expect, printing a truncates it to four places. However, the disp and sprintf commands allow one to work around this: disp(sprintf(’6 decimals: %0.6f’, a)) will print π to six decimal places, preceded by the words “6 decimals.” Some commands make this easier: format long permanently sets decimals to display with higher accuracy, and format short returns to four digits.

The power of MATLAB is in its vectors and matrices. For example, one generates the matrix A =

 with the

command A = [1 2; 3 4; 5 6], and one generates the row vector v = [1 2 3] as v = [1 2 3], and the column vector

v′^ =

 as^ v’ = [1; 2; 3]. Vectors can be automatically generated:^ v = [1:0.1:2]^ generates a vector that steps from 1

to 2 with a step size of 0.1 (which defaults to 1; 1:6 is equivalent to the array [1 2 3 4 5 6]). Some commonly used matrices have shortcuts: ones(m,n) creates an m × n matrix of entirely ones (which reduces to a vector if m or n is 1). The zeros command does the same thin, but returns the zero matrix. Similarly, the rand function takes arguments in the same way and returns a matrix with random numbers uniformly distributed in [ 0 , 1 ], The randn function returns random numbers chosen from the standard unit normal distribution. All of these are called in exactly the same way. The empty matrix or vector, a 0 × 0 matrix, is given by e = [], and the n × n identity matrix is given by eye(n). If a matrix is read from a file (for example) and you don’t know its dimension, you can use the size command, which returns a vector of the dimensions of the matrix (or vector, in which case one of the entries is 1). Then, the length command returns the length of the longest directory. This is mostly useful for vectors, and can do unexpected things with matrices if you’re not careful. Now, on to loading files: the pwd command does exactly what it does in any actual shell, and so do cd and ls. Then, the command load filename will read the files and store their contents as directed by the file. Then, one can use the who command to determine which variables exist (and therefore which were affected by loading the file), and whos provides more information (e.g. the dimensions of the variables). The clear command deletes a given variable, but without an argument it deletes every variable, so be careful! Dually, the save filename variable saves the given variable to the specified file. Note that Octave appends an Octave-specific header unless one passes the ascii flag to save.

(^18) Or its open-source equivalent, Octave.