Study Note of Machine Learning (III)

Chap 4 - Neural Networks: Representation

Non-linear Hypotheses

Performing linear regression with a complex set of data with many features is very unwieldy. Say you wanted to create a hypothesis from three (3) features that included all the quadratic terms:

That gives us 6 features. The exact way to calculate how many features for all polynomial terms is the combination function with repetition link. . In this case we are taking all two-element combinations of three features: = . (Note: you do not have to know these formulas, I just found it helpful for understanding).

For 100 features, if we wanted to make them quadratic we would get resulting new features.

We can approximate the growth of the number of new features we get with all quadratic terms with . And if you wanted to include all cubic terms in your hypothesis, the features would grow asymptotically at . These are very steep growths, so as the number of our features increase, the number of quadratic or cubic features increase very rapidly and becomes quickly impractical.

Example: let our training set be a collection of 50 x 50 pixel black-and-white photographs, and our goal will be to classify which ones are photos of cars. Our feature set size is then n = 2500 if we compare every pair of pixels.

Now let’s say we need to make a quadratic hypothesis function. With quadratic features, our growth is . So our total features will be about , which is very impractical.

Neural networks offers an alternate way to perform machine learning when we have complex hypotheses with many features.

Neurons and the Brain

Neural networks are limited imitations of how our own brains work. They’ve had a big recent resurgence because of advances in computer hardware.

There is evidence that the brain uses only one “learning algorithm” for all its different functions. Scientists have tried cutting (in an animal brain) the connection between the ears and the auditory cortex and rewiring the optical nerve with the auditory cortex to find that the auditory cortex literally learns to see.

This principle is called “neuroplasticity” and has many examples and experimental evidence.

Model Representation I

Let’s examine how we will represent a hypothesis function using neural networks.

At a very simple level, neurons are basically computational units that take input (dendrites) as electrical input (called “spikes”) that are channeled to outputs (axons).

In our model, our dendrites are like the input features , and the output is the result of our hypothesis function:

In this model our x0 input node is sometimes called the “bias unit.” It is always equal to 1.

In neural networks, we use the same logistic function as in classification: . In neural networks however we sometimes call it a sigmoid (logistic) activation function.

Our “theta” parameters are sometimes instead called “weights” in the neural networks model.

Visually, a simplistic representation looks like:

Our input nodes (layer 1) go into another node (layer 2), and are output as the hypothesis function.

The first layer is called the “input layer” and the final layer the “output layer,” which gives the final value computed on the hypothesis.

We can have intermediate layers of nodes between the input and output layers called the “hidden layer.”

We label these intermediate or “hidden” layer nodes and call them “activation units.”

If we had one hidden layer, it would look visually something like:

The values for each of the “activation” nodes is obtained as follows:

This is saying that we compute our activation nodes by using a 3×4 matrix of parameters. We apply each row of the parameters to our inputs to obtain the value for one activation node. Our hypothesis output is the logistic function applied to the sum of the values of our activation nodes, which have been multiplied by yet another parameter matrix containing the weights for our second layer of nodes.

Each layer gets its own matrix of weights, .

The dimensions of these matrices of weights is determined as follows:

The +1 comes from the addition in of the “bias nodes,” and . In other words the output nodes will not include the bias nodes while the inputs will.

Example: layer 1 has 2 input nodes and layer 2 has 4 activation nodes. Dimension of is going to be 4×3 where and , so .

Model Representation II

In this section we’ll do a vectorized implementation of the above functions. We’re going to define a new variable that encompasses the parameters inside our g function. In our previous example if we replaced the variable z for all the parameters we would get:

In other words, for layer j=2 and node k, the variable z will be:

The vector representation of x and is:

Setting , we can rewrite the equation as:

We are multiplying our matrix with dimensions (where is the number of our activation nodes) by our vector with height (n+1). This gives us our vector with height .

Now we can get a vector of our activation nodes for layer j as follows:

Where our function g can be applied element-wise to our vector .

We can then add a bias unit (equal to 1) to layer j after we have computed . This will be element and will be equal to 1.

To compute our final hypothesis, let’s first compute another z vector:

We get this final z vector by multiplying the next theta matrix after with the values of all the activation nodes we just got.

This last theta matrix will have only one row so that our result is a single number.

We then get our final result with:

Notice that in this last step, between layer j and layer j+1, we are doing exactly the same thing as we did in logistic regression.

Adding all these intermediate layers in neural networks allows us to more elegantly produce interesting and more complex non-linear hypotheses.

Examples and Intuitions I

A simple example of applying neural networks is by predicting AND , which is the logical ‘and’ operator and is only true if both and are 1.

The graph of our functions will look like:

Remember that is our bias variable and is always 1.

Let’s set our first theta matrix as:

This will cause the output of our hypothesis to only be positive if both and are 1. In other words:

So we have constructed one of the fundamental operations in computers by using a small neural network rather than using an actual AND gate. Neural networks can also be used to simulate all the other logical gates.

Examples and Intuitions II

The matrices for AND, NOR, and OR are:

We can combine these to get the XNOR logical operator (which gives 1 if and are both 0 or both 1).

For the transition between the first and second layer, we’ll use a matrix that combines the values for AND and NOR:

For the transition between the second and third layer, we’ll use a matrix that uses the value for OR:

Let’s write out the values for all our nodes:

And there we have the XNOR operator using two hidden layers!

Multiclass Classification

To classify data into multiple classes, we let our hypothesis function return a vector of values. Say we wanted to classify our data into one of four final resulting classes:

Our final layer of nodes, when multiplied by its theta matrix, will result in another vector, on which we will apply the g() logistic function to get a vector of hypothesis values.

Our resulting hypothesis for one set of inputs may look like:

In which case our resulting class is the third one down, or .

We can define our set of resulting classes as y:

Our final value of our hypothesis for a set of inputs will be one of the elements in y.

Chap 5 - ML:Neural Networks: Learning

Cost Function

Let’s first define a few variables that we will need to use:

a) L= total number of layers in the network

b) = number of units (not counting bias unit) in layer l

c) K= number of output units/classes

Recall that in neural networks, we may have many output nodes. We denote as being a hypothesis that results in the output.

Our cost function for neural networks is going to be a generalization of the one we used for logistic regression.

Recall that the cost function for regularized logistic regression was:

For neural networks, it is going to be slightly more complicated:

We have added a few nested summations to account for our multiple output nodes. In the first part of the equation, between the square brackets, we have an additional nested summation that loops through the number of output nodes.

In the regularization part, after the square brackets, we must account for multiple theta matrices. The number of columns in our current theta matrix is equal to the number of nodes in our current layer (including the bias unit). The number of rows in our current theta matrix is equal to the number of nodes in the next layer (excluding the bias unit). As before with logistic regression, we square every term.

Note:

  • the double sum simply adds up the logistic regression costs calculated for each cell in the output layer; and
  • the triple sum simply adds up the squares of all the individual Θs in the entire network.
  • the i in the triple sum does not refer to training example i

Backpropagation Algorithm

“Backpropagation” is neural-network terminology for minimizing our cost function, just like what we were doing with gradient descent in logistic and linear regression.

Our goal is to compute:

That is, we want to minimize our cost function J using an optimal set of parameters in theta.

In this section we’ll look at the equations we use to compute the partial derivative of J(Θ):

In back propagation we’re going to compute for every node:

= “error” of node j in layer l

Recall that is activation node j in layer l.

For the last layer, we can compute the vector of delta values with:

Where L is our total number of layers and is the vector of outputs of the activation units for the last layer. So our “error values” for the last layer are simply the differences of our actual results in the last layer and the correct outputs in y.

To get the delta values of the layers before the last layer, we can use an equation that steps us back from right to left:

The delta values of layer l are calculated by multiplying the delta values in the next layer with the theta matrix of layer l. We then element-wise multiply that with a function called g’, or g-prime, which is the derivative of the activation function g evaluated with the input values given by z(l).

The g-prime derivative terms can also be written out as:

The full back propagation equation for the inner nodes is then:

A. Ng states that the derivation and proofs are complicated and involved, but you can still implement the above equations to do back propagation without knowing the details.

We can compute our partial derivative terms by multiplying our activation values and our error values for each training example t:

This however ignores regularization, which we’ll deal with later.

Note: and are vectors with elements. Similarly, is a vector with elements. Multiplying them produces a matrix that is by which is the same dimension as . That is, the process produces a gradient term for every element in . (Actually, has + 1 column, so the dimensionality is not exactly the same).

We can now take all these equations and put them together into a backpropagation algorithm:

Back propagation Algorithm

Given training set

Set := 0 for all (l,i,j)

For training example t =1 to m:

  • Set
  • Perform forward propagation to compute for l=2,3,…,L
  • Using , compute
  • Compute using
  • or with vectorization,
  • If j≠0 NOTE: Typo in lecture slide omits outside parentheses. This version is correct.
  • If j=0

The capital-delta matrix is used as an “accumulator” to add up our values as we go along and eventually compute our partial derivative.

The actual proof is quite involved, but, the terms are the partial derivatives and the results we are looking for:

Backpropagation Intuition

The cost function is:

If we consider simple non-multiclass classification (k = 1) and disregard regularization, the cost is computed with:

More intuitively you can think of that equation roughly as:

Intuitively, is the “error” for (unit j in layer l)

More formally, the delta values are actually the derivative of the cost function:

Recall that our derivative is the slope of a line tangent to the cost function, so the steeper the slope the more incorrect we are.

Note: In lecture, sometimes i is used to index a training example. Sometimes it is used to index a unit in a layer. In the Back Propagation Algorithm described here, t is used to index a training example rather than overloading the use of i.

Implementation Note: Unrolling Parameters

With neural networks, we are working with sets of matrices:

In order to use optimizing functions such as “fminunc()”, we will want to “unroll” all the elements and put them into one long vector:

If the dimensions of Theta1 is 10x11, Theta2 is 10x11 and Theta3 is 1x11, then we can get back our original matrices from the “unrolled” versions as follows:

NOTE: The lecture slides show an example neural network with 3 layers. However, 3 theta matrices are defined: Theta1, Theta2, Theta3. There should be only 2 theta matrices: Theta1 (10 x 11), Theta2 (1 x 11).

Gradient Checking

Gradient checking will assure that our backpropagation works as intended.

We can approximate the derivative of our cost function with:

With multiple theta matrices, we can approximate the derivative with respect to as follows:

A good small value for (epsilon), guarantees the math above to become true. If the value be much smaller, may we will end up with numerical problems. The professor Andrew usually uses the value .

We are only adding or subtracting epsilon to the matrix. In octave we can do it as follows:

We then want to check that gradApprox ≈ deltaVector.

Once you’ve verified once that your backpropagation algorithm is correct, then you don’t need to compute gradApprox again. The code to compute gradApprox is very slow.

Random Initialization

Initializing all theta weights to zero does not work with neural networks. When we backpropagate, all nodes will update to the same value repeatedly.

Instead we can randomly initialize our weights:

Initialize each to a random value between:

rand(x,y) will initialize a matrix of random real numbers between 0 and 1. (Note: this epsilon is unrelated to the epsilon from Gradient Checking)

Why use this method? This paper may be useful: https://web.stanford.edu/class/ee373b/nninitialization.pdf

Putting it Together

First, pick a network architecture; choose the layout of your neural network, including how many hidden units in each layer and how many layers total.

Number of input units = dimension of features Number of output units = number of classes Number of hidden units per layer = usually more the better (must balance with cost of computation as it increases with more hidden units) Defaults: 1 hidden layer. If more than 1 hidden layer, then the same number of units in every hidden layer. Training a Neural Network

Randomly initialize the weights Implement forward propagation to get Implement the cost function Implement backpropagation to compute partial derivatives Use gradient checking to confirm that your backpropagation works. Then disable gradient checking. Use gradient descent or a built-in optimization function to minimize the cost function with the weights in theta. When we perform forward and back propagation, we loop on every training example:

Explanation of Derivatives Used in Backpropagation

We know that for a logistic regression classifier (which is what all of the output neurons in a neural network are), we use the cost function, , and apply this over the K output neurons, and for all m examples. he equation to compute the partial derivatives of the theta terms in the output neurons:

And the equation to compute partial derivatives of the theta terms in the [last] hidden layer neurons (layer L-1):

Clearly they share some pieces in common, so a delta term () can be used for the common pieces between the output layer and the hidden layer immediately before it (with the possibility that there could be many hidden layers if we wanted):

And we can go ahead and use another delta term () for the pieces that would be shared by the final hidden layer and a hidden layer before that, if we had one. Regardless, this delta term will still serve to make the math and implementation more concise.

With these delta terms, our equations become:

Now, time to evaluate these derivatives. Let’s start with the output layer:

Using , we need to evaluate both partial derivatives.

Given , where , the partial derivative is:

And given a=g(z), where , the partial derivative is:

So, let’s substitute these in for :

So, for a 3-layer network (L=3),

Note that this is the correct equation, as given in our notes. Now, given z=θ∗input, and in layer L the input is , the partial derivative is:

Put it together for the output layer:

Let’s continue on for the hidden layer (let’s assume we only have 1 hidden layer):

Let’s figure out . Once again, given z=θ∗input, the partial derivative is:

And:

So, let’s substitute these in for :

So, for a 3-layer network,

Put it together for the [last] hidden layer:

Deriving the Sigmoid Gradient Function

We let the sigmoid function be

Deriving the equation above yields to

Which is equal to

Additional Resources for Backpropagation

Reference

0%