Login to your account

Username *
Password *
Remember Me

Create an account

Fields marked with an asterisk (*) are required.
Name *
Username *
Password *
Verify password *
Email *
Verify email *
Captcha *
Reload Captcha

Machine Learning

Machine Learning

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive

 

I. Large margin classification:

   a. Optimization objective:

There's one more algorithm that is very powerful and is very widely used both within industry and academia, and that's called the support vector machine. And compared to both logistic regression and neural networks, the Support Vector Machine, or SVM sometimes gives a cleaner, and sometimes more powerful way of learning complex non-linear functions.

Machine Learning

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive

Naïve Bayes

Definition:

  • Naïve Bayes overview:
    • Relationships between input features and class expressed as probabilities.
    • Label for sample is class with highest probability given input. 
  • Naïve Bayes classifier:
    • Classification using probability
    • Bayes theorem: it makes estimating the probabilities easier.
    • Feature independence assumption: For a given class, the value of one feature does not affect the value of any other feature.
  • The naïve independence assumption and the use of Bayes theorem gives this classification model its name.
  • Probability of event:
    • Probability is measure of how likely an event is
    • Probability of event ‘A’ occurring:

     

  • Joint probability:
    • Probability of events A and B occurring together:                                     
      • If the 2 events are independent: P(A, B) = P(A) * P(B)
      • Conditional probability:
        1. Probability of event A occurring, given that event B occurred.
        2. Event A is conditioned on event B. P(A|B) = P(A,B)/P(B) 

          It provides the means to specify the probability of a class label, given the input values.                           

  • Bayes’ theorem:
    • Relationship between P(B|A) and P(A|B) can be expressed through Bayes’ theorem:

       

  • Classification with probabilities:

    Given features X = {X1, X2,……,Xn}, predict class C. Do this by finding value of C that maximizes P(C|X)

  • Bayes theorem for classification:
    • But estimating P(C|X) is difficult, we should use Bayes’ theorem to simplifies the problem:
    • So to get P(C|X), only need to find P(X|C) and P(C).
    • Estimating P(C): To estimate P(C), calculate fraction of samples for class C in training data.
    • Estimating P(X|C):
      • Independence assumption: Features are independent of one another: 

        P (X1, X2,…Xn|C) = P(X1|C) * P(X2|C) * …….. * P(Xn|C)

      • To estimate P(X|C), only need to estimate P(Xi|C) individually

Advantages and Disadvantages:

a. Advantages:

  • Naïve Bayes classification:
    • Fast and simple: the probabilities that are needed can be calculated with a single scan of the data set and stored in a table.
    • Scales well:
      • Model building and testing of both task, it scales well.
      • Due to the independent assumption:
        1. The probability for each feature can be independently estimated.
        2. Featured probability is can be calculated in very low.
        3. The data set size does not have to grow exponentially with a number of features.
        4. This avoid the many problems associated with the curse of dimensionality.
        5. No need to a lot of data to build the model.
        6. Number of parameters scales linearly with the number of features.

b. Disadvantages:

  • The independence assumption may not hold true
    • In practice, still works quite well.
  • Does not model interactions between features.

 

author: LASSRI Safae
PhD at faculty of science Ben M'Sik.

Machine Learning

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive

Logistic Regression:

Scores range from minus infinity to plus infinity, probabilities range between 0 and 1. The question is how do we relate score from minus infinity to plus infinity, to probability 0 and 1. How do we link these two things?

We are going to take the score, which is between minus infinity and plus infinity, we are going to push it through a function g that squeezes that huge line into the interval 0, 1. And uses it to predict the probability that y equals +1.

And when you're taking a linear model, w transpose h minus infinity to plus infinity and you're squeezing it into 0,1 using link functions you are building what's called a generalized linear model.

what's a generalized linear model?

It's just like a regression model, but you squeeze it into 0, 1 by pushing through a link function.

The sigmoid (or logistic) link function:

  a. Classification and representation:

    i. Classification:

To attempt classification, one method is to use linear regression and map all predictions greater than 0.5 as a 1 and all less than 0.5 as a 0. However, this method doesn't work well because classification is not actually a linear function.

The classification problem 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, x(i) then   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. Hence, y∈ {0,1}. 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.

    ii. Hypotheses representation:

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, let’s change the form for our hypotheses hθ(x) to satisfy 0≤hθ(x)≤1. This is accomplished by plugging θTx  into the Logistic Function.

Our new form uses the "Sigmoid Function," also called the "Logistic Function":

The following image shows us what the sigmoid function looks like:

The function g(z), shown here, maps any real number to the (0, 1) interval, making it useful for transforming an arbitrary-valued function into a function better suited for classification.

hθ(x) will give us the probability that our output is 1. For example, hθ(x)= 0.7 gives us a probability of 70% that our output is 1. Our probability that our prediction is 0 is just the complement of our probability that it is 1 (e.g. if probability that it is 1 is 70%, then the probability that it is 0 is 30%).

    iii. Decision Boundary:

In order to get our discrete 0 or 1 classification, we can translate the output of the hypothesis function as follows:

 

The way our logistic function g behaves is that when its input is greater than or equal to zero, its output is greater than or equal to 0.5:

Remember:

So, if our input to g is x, then that means:

From these statements we can now say:

The decision boundary is the line that separates the area where y = 0 and where y = 1. It is created by our hypothesis function.

Example:

In this case, our decision boundary is a straight vertical line placed on the graph where x1 = 5, and everything to the left of that denotes y = 1, while everything to the right denotes y = 0.

Again, the input to the sigmoid function g(z) (e.g. θTx) doesn't need to be linear and could be a function that describes a circle (e.g. z=θ01x122x22) or any shape to fit our data.

  b. Logistic regression model:

    i. Cost Function:

We cannot use the same cost function that we use for linear regression because the Logistic Function will cause the output to be wavy, causing many local optima. In other words, it will not be a convex function.

Instead, our cost function for logistic regression looks like:

When y = 1, we get the following plot for J(θ) vs hθ(x):

Similarly, when y = 0, we get the following plot for J(θ) vs hθ(x):

If our correct answer 'y' is 0, then the cost function will be 0 if our hypothesis function also outputs 0. If our hypothesis approaches 1, then the cost function will approach infinity.

If our correct answer 'y' is 1, then the cost function will be 0 if our hypothesis function outputs 1. If our hypothesis approaches 0, then the cost function will approach infinity.

Note that writing the cost function in this way guarantees that J(θ) is convex for logistic regression.

    ii. Simplified Cost Function and Gradient Descent:

We can compress our cost function's two conditional cases into one case:

Notice that when y is equal to 1, then the second term (1-y)log(1-hθ(x)) will be zero and will not affect the result. If y is equal to 0, then the first term -ylog(hθ(x))will be zero and will not affect the result.

We can fully write out our entire cost function as follows:

A vectorized implementation is:

Remember that the general form of gradient descent is:

Repeat {

}

We can work out the derivative part using calculus to get:

Repeat {

}

Notice that this algorithm is identical to the one we used in linear regression. We still have to simultaneously update all values in theta.

A vectorized implementation is:

    iii. Advanced Optimization:

"Conjugate gradient", "BFGS", and "L-BFGS" are more sophisticated, faster ways to optimize θ that can be used instead of gradient descent. We suggest that you should not write these more sophisticated algorithms yourself (unless you are an expert in numerical computing) but use the libraries instead, as they're already tested and highly optimized. Octave provides them.

We first need to provide a function that evaluates the following two functions for a given input value θ:

We can write a single function that returns both of these:

Then we can use octave's "fminunc()" optimization algorithm along with the "optimset()" function that creates an object containing the options we want to send to "fminunc()". (Note: the value for MaxIter should be an integer, not a character string - errata in the video at 7:30)

We give to the function "fminunc()" our cost function, our initial vector of theta values, and the "options" object that we created beforehand.

  c. Multiclass classification:

    i. Multiclass Classification: One-vs-all :

Now we will approach the classification of data when we have more than two categories. Instead of y = {0,1} we will expand our definition so that y = {0,1...n}.

Since y = {0,1...n}, we divide our problem into n+1 (+1 because the index starts at 0) binary classification problems; in each one, we predict the probability that 'y' is a member of one of our classes.

We are basically choosing one class and then lumping all the others into a single second class. We do this repeatedly, applying binary logistic regression to each case, and then use the hypothesis that returned the highest value as our prediction.

The following image shows how one could classify 3 classes:

To summarize:

Train a logistic regression classifier hθ(x) for each class to predict the probability that y = i.

To make a prediction on a new x, pick the class that maximizes hθ(x).

auhor: LASSRI Safae
PhD at faculty of science Ben M'Sik.
 

Machine Learning

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive

1- Linear classifier:

A linear classifier:

  • Using a training data to learn a weight or coefficient for each word.
  • Calling a linear classifier, because output is weighted sum of input.

Decision boundries:

Decision boundries separates positive and negative predictions:

  • For linear classifiers:
    • When 2 coefficients are non-zero Line
    • When 3 coefficients are non-zero Plane
    • When many coefficients are non-zero Hyper plane
  • For more general classifiers More complicated shapes.

Linear classifier model:

a- Linear regression with one variable:

    i- Model and cost function:

       1-Model representation:

Our first learning algorithm will be linear regression.

More formally, in supervised learning, we have a data set and this data set is called a training set.

Let's define some notation that we're using throughout this course. We're going to define quite a lot of

symbols.

  • m: to denote the number of training examples.
  • x: to denote the input variables often also called the features.
  • y: to denote my output variables or the target variable which i'm going to predict.
  • (x,y): to denote a single training example.

To establish notation for future use, we’ll use  to denote the “input” variables (living area in this example), also called input features, and  to denote the “output” or target variable that we are trying to predict (price). A pair   is called a training example, and the dataset that we’ll be using to learn—a list of m training examples  —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 to denote the space of input values, and Y to denote the space of output values. In this example, X = Y = ℝ.

To describe the supervised learning problem slightly more formally, our goal is, given a training set, to learn a function h: X → 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:

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 problem. 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.

         2-Cost function:

We can measure the accuracy of our hypothesis function by using a cost function. This takes an inputs from x's and the actual output y's.

To break it apart, it is  where   is the mean of the squares of   , or the difference between the predicted value and the actual value.

This function is otherwise called the "Squared error function", or "Mean squared error". The mean is halved  as a convenience for the computation of the gradient descent, as the derivative term of the square function will cancel out the.

          3-Cost function - Intuition 1

If we try to think of it in visual terms, our training data set is scattered on the x-y plane. We are trying to make a straight line (defined by ) which passes through these scattered data points.

Our objective is to get the best possible line. The best possible line will be such so that the average squared vertical distances of the scattered points from the line will be the least. Ideally, the line should pass through all the points of our training data set. In such a case, the value of  will be 0. The following example shows the ideal situation where we have a cost function of 0.

When θ1=1, we get a slope of 1 which goes through every single data point in our model. Conversely, when θ1=0.5, we see the vertical distance from our fit to the data points increase.

This increases our cost function to 0.58. Plotting several other points yields to the following graph:

Thus as a goal, we should try to minimize the cost function. In this case, =1 is our global minimum.

    ii- Parameter learning:

       1- Gradient descent:

So we have our hypothesis function and we have a way of measuring how well it fits into the data. Now we need to estimate the parameters in the hypothesis function. That's where gradient descent comes in.

Imagine that we graph our hypothesis function based on its fields  and  (actually we are graphing the cost function as a function of the parameter estimates). We are not graphing x and y itself, but the parameter range of our hypothesis function and the cost resulting from selecting a particular set of parameters.

We put  on the x axis and  on the y axis, with the cost function on the vertical z axis. The points on our graph will be the result of the cost function using our hypothesis with those specific theta parameters. The graph below depicts such a setup.

We will know that we have succeeded when our cost function is at the very bottom of the pits in our graph, i.e. when its value is the minimum. The red arrows show the minimum points in the graph.

The way we do this is by taking the derivative (the tangential line to a function) of our cost function. The slope of the tangent is the derivative at that point and it will give us a direction to move towards. We make steps down the cost function in the direction with the steepest descent. The size of each step is determined by the parameter α, which is called the learning rate.

For example, the distance between each 'star' in the graph above represents a step determined by our parameter α. A smaller α would result in a smaller step and a larger α results in a larger step. The direction in which the step is taken is determined by the partial derivative of  . Depending on where one starts on the graph, one could end up at different points. The image above shows us two different starting points that end up in two different places.

The gradient descent algorithm is:

repeat until convergence:

Where j=0,1 represents the feature index number.

At each iteration j, one should simultaneously update the parameters  . Updating a specific parameter prior to calculating another one on the  iteration would yield to a wrong implementation

       2. Gradient descent intuition:

In this paragraph we will explore the scenario where we use one parameter θ1 and plotte its cost function to implement a gradient descent. Our formula for a single parameter is:

Repeat until convergence:

Regardless of the slope's sign for    eventually converges to its minimum value. The following graph shows that when the slope is negative, the value of  increases and when it is positive, the value of  decreases.

On a side note, we should adjust our parameter α to ensure that the gradient descent algorithm converges in a reasonable time. Failure to converge or too much time to obtain the minimum value imply that our step size is wrong.

  • How does gradient descent converge with a fixed step size α?

The intuition behind the convergence is that      approaches 0 as we approach the bottom of our convex function. At the minimum, the derivative will always be 0 and thus we get:

      3- Gradient descent for linear regression:

When specifically applied to the case of linear regression, a new form of the gradient descent equation can be derived. We can substitute our actual cost function and our actual hypothesis function and modify the equation to:

Where m is the size of the training set, ​ a constant that will be changing simultaneously with θ1 and xi, yi are values of the given training set (data)

Note that we have separated out the two cases for ​θj into separate equations for θ0 and θ1; and that for θ1 we are multiplying xi at the end due to the derivative . the following is a derivation of   for a single example:

The point of all this is that if we start with a guess for our hypothesis and then repeatedly apply these gradient descent equations, our hypothesis will become more and more accurate.

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.

The ellipses shown above are the contours of a quadratic function. Also shown is the trajectory taken by gradient descent, which 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 as it converged to its minimum.

b- Linear regression with multiple variables:

    i- Multivariate linear regression:

       1-Multiple features:

Linear regression with multiple variables is also known as "multivariate linear regression". We now introduce notation for equations where we can have any number of input variables.

The multivariable form of the hypothesis function accommodating these multiple features is as follows:

In order to develop intuition about this function, we can think about θ0 as the basic price of a house, θ1 as the price per square meter, θ2 as the price per floor, etc.  x1 will be the number of square meters in the house,  x2 the number of floors, etc.

Using the definition of matrix multiplication, our multivariable hypothesis function can be concisely represented as:

This is a vectorization of our hypothesis function for one training example;

Remark: Note that for convenience reasons in this course we assume .This allows us to do matrix operations with theta and x. Hence making the two vectors 'theta' and  match each other element-wise (that is, have the same number of elements: n+1).]

The training examples are stored in X row-wise. The following example shows us the reason behind setting  :

As a result, you can calculate the hypothesis as a column vector of size (m x 1) with: 

       2-Gradient descent for multiple variables:

The gradient descent equation itself is generally the same form; we just have to repeat it for our 'n' features:

In other words:

repeat until convergence: {

     

}

The following image compares gradient descent with one variable to gradient descent with multiple variables:

       3-Gradient Descent in Practice I - Feature Scaling:

We can speed up gradient descent by having each of our input values in roughly the same range. This is because θ will descend quickly on small ranges and slowly on large ranges, and so will oscillate inefficiently down to the optimum when the variables are very uneven.

The way to prevent this is to modify the ranges of our input variables so that they are all roughly the same. Ideally:

−1 ≤ x(i) ≤ 1

or

−0.5 ≤ x(i) ≤ 0.5

These aren't exact requirements; we are only trying to speed things up. The goal is to get all input variables into roughly one of these ranges, give or take a few.

Two techniques to help with this are feature scaling and mean normalization. Feature scaling involves dividing the input values by the range (i.e. the maximum value minus the minimum value) of the input variable, resulting in a new range of just 1. Mean normalization involves subtracting the average value for an input variable from the values for that input variable resulting in a new average value for the input variable of just zero. To implement both of these techniques, adjust your input values as shown in this formula:

Where   is the average of all the values for feature (i) and si is the range of values (max - min), or si is the standard deviation.

Note that dividing by the range, or dividing by the standard deviation, give different results. The quizzes in this course use range - the programming exercises use standard deviation.  For example, if xi represents housing prices with a range of 100 to 2000 and a mean value of 1000, then 

       4-Gradient Descent in Practice II - Learning Rate:

Debugging gradient descent. Make a plot with number of iterations on the x-axis. Now plot the cost function, J(θ) over the number of iterations of gradient descent. If J(θ) ever increases, then you probably need to decrease α.

Automatic convergence test. Declare convergence if J(θ) decreases by less than E in one iteration, where E is some small value such as 10−3. However, in practice it's difficult to choose this threshold value.

It has been proven that if learning rate α is sufficiently small, then J(θ) will decrease on every iteration.

To summarize:

If α is too small: slow convergence.

If α is too large: may not decrease on every iteration and thus may not converge.

       5- Features and Polynomial Regression:

We can improve our features and the form of our hypothesis function in a couple different ways.

We can combine multiple features into one. For example, we can combine x1 and x2 into a new feature x3 by taking x1 ⋅ x2 .

Polynomial Regression

Our hypothesis function need not be linear (a straight line) if that does not fit the data well.

We can change the behavior or curve of our hypothesis function by making it a quadratic, cubic or square root function (or any other form).

For example, if our hypothesis function is   then we can create additional features based on , to get the quadratic function   or the cubic function 

In the cubic version, we have created new features x2 and x3 where x2 = x1² and x3 = x1³.

To make it a square root function, we could do:   One important thing to keep in mind is, if you choose your features this way then feature scaling becomes very important.

eg. if x1 has range 1 - 1000 then range of x1² becomes 1 - 1000000 and that of x1³ becomes 1 - 1000000000.

    ii- Computing parametres analyticallly:

       1- Normal Equation:

Gradient descent gives one way of minimizing J. Let’s discuss a second way of doing so, this time performing the minimization explicitly and without resorting to an iterative algorithm. In the "Normal Equation" method, we will minimize J by explicitly taking its derivatives with respect to the θj ’s, and setting them to zero. This allows us to find the optimum theta without iteration. The normal equation formula is given below:

There is no need to do feature scaling with the normal equation.

The following is a comparison of gradient descent and the normal equation:

Gradient Descent

Normal Equation

Need to choose alpha

No need to choose alpha

Needs many iterations

No need to iterate

O (kn2)

O (n3), need to calculate inverse of XTX

Works well when n is large

Slow if n is very large

With the normal equation, computing the inversion has complexity O(n³). So if we have a very large number of features, the normal equation will be slow. In practice, when n exceeds 10,000 it might be a good time to go from a normal solution to an iterative process.

       2- Normal Equation Noninvertibility

When implementing the normal equation in octave we want to use the 'pinv' function rather than 'inv.' The 'pinv' function will give you a value of θ even if XTX is not invertible. 

If XTX is noninvertible, the common causes might be having :

  • Redundant features, where two features are very closely related (i.e. they are linearly dependent)
  • Too many features (e.g. m ≤ n). In this case, delete some features or use "regularization" (to be explained in a later lesson).

Solutions to the above problems include deleting a feature that is linearly dependent with another or deleting one or more features when there are too many features.

author: LASSRI Safae
PhD at faculty of science Ben M'Sik.