diff --git a/doc/pub/week39/html/._week39-bs000.html b/doc/pub/week39/html/._week39-bs000.html new file mode 100644 index 000000000..8ee7bad96 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs000.html @@ -0,0 +1,353 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + + + +
+

Week 39: Optimization and Gradient Methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs001.html b/doc/pub/week39/html/._week39-bs001.html new file mode 100644 index 000000000..2491cd7e5 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs001.html @@ -0,0 +1,333 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Plan for week 39

+ + + +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs002.html b/doc/pub/week39/html/._week39-bs002.html new file mode 100644 index 000000000..d1484f9aa --- /dev/null +++ b/doc/pub/week39/html/._week39-bs002.html @@ -0,0 +1,330 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Thursday September 24

+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs003.html b/doc/pub/week39/html/._week39-bs003.html new file mode 100644 index 000000000..494124c91 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs003.html @@ -0,0 +1,341 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Optimization, the central part of any Machine Learning algortithm

+ +

+Almost every problem in machine learning and data science starts with +a dataset \( X \), a model \( g(\beta) \), which is a function of the +parameters \( \beta \) and a cost function \( C(X, g(\beta)) \) that allows +us to judge how well the model \( g(\beta) \) explains the observations +\( X \). The model is fit by finding the values of \( \beta \) that minimize +the cost function. Ideally we would be able to solve for \( \beta \) +analytically, however this is not possible in general and we must use +some approximative/numerical method to compute the minimum. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs004.html b/doc/pub/week39/html/._week39-bs004.html new file mode 100644 index 000000000..2c623810e --- /dev/null +++ b/doc/pub/week39/html/._week39-bs004.html @@ -0,0 +1,349 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Revisiting our Logistic Regression case

+ +

+In our discussion on Logistic Regression we studied the +case of +two classes, with \( y_i \) either +\( 0 \) or \( 1 \). Furthermore we assumed also that we have only two +parameters \( \beta \) in our fitting, that is we +defined probabilities + +$$ +\begin{align*} +p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ +p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), +\end{align*} +$$ + +where \( \hat{\beta} \) are the weights we wish to extract from data, in our case \( \beta_0 \) and \( \beta_1 \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs005.html b/doc/pub/week39/html/._week39-bs005.html new file mode 100644 index 000000000..2f2e88eea --- /dev/null +++ b/doc/pub/week39/html/._week39-bs005.html @@ -0,0 +1,354 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The equations to solve

+ +

+Our compact equations used a definition of a vector \( \hat{y} \) with \( n \) +elements \( y_i \), an \( n\times p \) matrix \( \hat{X} \) which contains the +\( x_i \) values and a vector \( \hat{p} \) of fitted probabilities +\( p(y_i\vert x_i,\hat{\beta}) \). We rewrote in a more compact form +the first derivative of the cost function as + +$$ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). +$$ + +

+If we in addition define a diagonal matrix \( \hat{W} \) with elements +\( p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta}) \), we can obtain a compact expression of the second derivative as + +$$ +\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. +$$ + +This defines what is called the Hessian matrix. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs006.html b/doc/pub/week39/html/._week39-bs006.html new file mode 100644 index 000000000..fb2334de4 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs006.html @@ -0,0 +1,355 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Solving using Newton-Raphson's method

+ +

+If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. + +

+Our iterative scheme is then given by + +$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T}\right)^{-1}_{\hat{\beta}^{\mathrm{old}}}\times \left(\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}}\right)_{\hat{\beta}^{\mathrm{old}}}, +$$ + +or in matrix form as + +$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\hat{X}^T\hat{W}\hat{X} \right)^{-1}\times \left(-\hat{X}^T(\hat{y}-\hat{p}) \right)_{\hat{\beta}^{\mathrm{old}}}. +$$ + +The right-hand side is computed with the old values of \( \beta \). + +

+If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs007.html b/doc/pub/week39/html/._week39-bs007.html new file mode 100644 index 000000000..b63c0673f --- /dev/null +++ b/doc/pub/week39/html/._week39-bs007.html @@ -0,0 +1,347 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Brief reminder on Newton-Raphson's method

+ +

+Let us quickly remind ourselves how we derive the above method. + +

+Perhaps the most celebrated of all one-dimensional root-finding +routines is Newton's method, also called the Newton-Raphson +method. This method requires the evaluation of both the +function \( f \) and its derivative \( f' \) at arbitrary points. +If you can only calculate the derivative +numerically and/or your function is not of the smooth type, we +normally discourage the use of this method. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs008.html b/doc/pub/week39/html/._week39-bs008.html new file mode 100644 index 000000000..b62b324a6 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs008.html @@ -0,0 +1,367 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The equations

+ +

+The Newton-Raphson formula consists geometrically of extending the +tangent line at a current point until it crosses zero, then setting +the next guess to the abscissa of that zero-crossing. The mathematics +behind this method is rather simple. Employing a Taylor expansion for +\( x \) sufficiently close to the solution \( s \), we have + +$$ + f(s)=0=f(x)+(s-x)f'(x)+\frac{(s-x)^2}{2}f''(x) +\dots. + \tag{1} +$$ + +

+For small enough values of the function and for well-behaved +functions, the terms beyond linear are unimportant, hence we obtain + +$$ + f(x)+(s-x)f'(x)\approx 0, +$$ + +yielding +$$ + s\approx x-\frac{f(x)}{f'(x)}. +$$ + +

+Having in mind an iterative procedure, it is natural to start iterating with +$$ + x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs009.html b/doc/pub/week39/html/._week39-bs009.html new file mode 100644 index 000000000..4722fb061 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs009.html @@ -0,0 +1,350 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Simple geometric interpretation

+ +

+The above is Newton-Raphson's method. It has a simple geometric +interpretation, namely \( x_{n+1} \) is the point where the tangent from +\( (x_n,f(x_n)) \) crosses the \( x \)-axis. Close to the solution, +Newton-Raphson converges fast to the desired result. However, if we +are far from a root, where the higher-order terms in the series are +important, the Newton-Raphson formula can give grossly inaccurate +results. For instance, the initial guess for the root might be so far +from the true root as to let the search interval include a local +maximum or minimum of the function. If an iteration places a trial +guess near such a local extremum, so that the first derivative nearly +vanishes, then Newton-Raphson may fail totally + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs010.html b/doc/pub/week39/html/._week39-bs010.html new file mode 100644 index 000000000..27260c959 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs010.html @@ -0,0 +1,388 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Extending to more than one variable

+ +

+Newton's method can be generalized to systems of several non-linear equations +and variables. Consider the case with two equations +$$ + \begin{array}{cc} f_1(x_1,x_2) &=0\\ + f_2(x_1,x_2) &=0,\end{array} +$$ + +which we Taylor expand to obtain + +$$ + \begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1 + \partial f_1/\partial x_1+h_2 + \partial f_1/\partial x_2+\dots\\ + 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1 + \partial f_2/\partial x_1+h_2 + \partial f_2/\partial x_2+\dots + \end{array}. +$$ + +Defining the Jacobian matrix \( {\bf \hat{J}} \) we have +$$ + {\bf \hat{J}}=\left( \begin{array}{cc} + \partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\ + \partial f_2/\partial x_1 &\partial f_2/\partial x_2 + \end{array} \right), +$$ + +we can rephrase Newton's method as +$$ +\left(\begin{array}{c} x_1^{n+1} \\ x_2^{n+1} \end{array} \right)= +\left(\begin{array}{c} x_1^{n} \\ x_2^{n} \end{array} \right)+ +\left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right), +$$ + +where we have defined +$$ + \left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)= + -{\bf \hat{J}}^{-1} + \left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right). +$$ + +We need thus to compute the inverse of the Jacobian matrix and it +is to understand that difficulties may +arise in case \( {\bf \hat{J}} \) is nearly singular. + +

+It is rather straightforward to extend the above scheme to systems of +more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs011.html b/doc/pub/week39/html/._week39-bs011.html new file mode 100644 index 000000000..e0ae207fe --- /dev/null +++ b/doc/pub/week39/html/._week39-bs011.html @@ -0,0 +1,357 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Steepest descent

+ +

+The basic idea of gradient descent is +that a function \( F(\mathbf{x}) \), +\( \mathbf{x} \equiv (x_1,\cdots,x_n) \), decreases fastest if one goes from \( \bf {x} \) in the +direction of the negative gradient \( -\nabla F(\mathbf{x}) \). + +

+It can be shown that if +$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), +$$ + +with \( \gamma_k > 0 \). + +

+For \( \gamma_k \) small enough, then \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \). This means that for a sufficiently small \( \gamma_k \) +we are always moving towards smaller function values, i.e a minimum. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs012.html b/doc/pub/week39/html/._week39-bs012.html new file mode 100644 index 000000000..faec60080 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs012.html @@ -0,0 +1,352 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

More on Steepest descent

+ +

+The previous observation is the basis of the method of steepest +descent, which is also referred to as just gradient descent (GD). One +starts with an initial guess \( \mathbf{x}_0 \) for a minimum of \( F \) and +computes new approximations according to + +$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), \ \ k \geq 0. +$$ + +

+The parameter \( \gamma_k \) is often referred to as the step length or +the learning rate within the context of Machine Learning. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs013.html b/doc/pub/week39/html/._week39-bs013.html new file mode 100644 index 000000000..2069d79ae --- /dev/null +++ b/doc/pub/week39/html/._week39-bs013.html @@ -0,0 +1,359 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The ideal

+ +

+Ideally the sequence \( \{\mathbf{x}_k \}_{k=0} \) converges to a global +minimum of the function \( F \). In general we do not know if we are in a +global or local minimum. In the special case when \( F \) is a convex +function, all local minima are also global minima, so in this case +gradient descent can converge to the global solution. The advantage of +this scheme is that it is conceptually simple and straightforward to +implement. However the method in this form has some severe +limitations: + +

+In machine learing we are often faced with non-convex high dimensional +cost functions with many local minima. Since GD is deterministic we +will get stuck in a local minimum, if the method converges, unless we +have a very good intial guess. This also implies that the scheme is +sensitive to the chosen initial condition. + +

+Note that the gradient is a function of \( \mathbf{x} = +(x_1,\cdots,x_n) \) which makes it expensive to compute numerically. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs014.html b/doc/pub/week39/html/._week39-bs014.html new file mode 100644 index 000000000..3adf21aef --- /dev/null +++ b/doc/pub/week39/html/._week39-bs014.html @@ -0,0 +1,352 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The sensitiveness of the gradient descent

+ +

+The gradient descent method +is sensitive to the choice of learning rate \( \gamma_k \). This is due +to the fact that we are only guaranteed that \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \) for sufficiently small \( \gamma_k \). The problem is to +determine an optimal learning rate. If the learning rate is chosen too +small the method will take a long time to converge and if it is too +large we can experience erratic behavior. + +

+Many of these shortcomings can be alleviated by introducing +randomness. One such method is that of Stochastic Gradient Descent +(SGD), see below. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs015.html b/doc/pub/week39/html/._week39-bs015.html new file mode 100644 index 000000000..856201454 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs015.html @@ -0,0 +1,353 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Convex functions

+ +

+Ideally we want our cost/loss function to be convex(concave). + +

+First we give the definition of a convex set: A set \( C \) in +\( \mathbb{R}^n \) is said to be convex if, for all \( x \) and \( y \) in \( C \) and +all \( t \in (0,1) \) , the point \( (1 − t)x + ty \) also belongs to +C. Geometrically this means that every point on the line segment +connecting \( x \) and \( y \) is in \( C \) as discussed below. + +

+The convex subsets of \( \mathbb{R} \) are the intervals of +\( \mathbb{R} \). Examples of convex sets of \( \mathbb{R}^2 \) are the +regular polygons (triangles, rectangles, pentagons, etc...). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs016.html b/doc/pub/week39/html/._week39-bs016.html new file mode 100644 index 000000000..fdda8ef53 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs016.html @@ -0,0 +1,341 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Convex function

+ +

+Convex function: Let \( X \subset \mathbb{R}^n \) be a convex set. Assume that the function \( f: X \rightarrow \mathbb{R} \) is continuous, then \( f \) is said to be convex if $$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ for all \( x_1, x_2 \in X \) and for all \( t \in [0,1] \). If \( \leq \) is replaced with a strict inequaltiy in the definition, we demand \( x_1 \neq x_2 \) and \( t\in(0,1) \) then \( f \) is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting \( f(x_1) \) and \( f(x_2) \), the value of the function on the interval \( [x_1,x_2] \) is always below the line as illustrated below. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs017.html b/doc/pub/week39/html/._week39-bs017.html new file mode 100644 index 000000000..73d243077 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs017.html @@ -0,0 +1,377 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conditions on convex functions

+ +

+In the following we state first and second-order conditions which +ensures convexity of a function \( f \). We write \( D_f \) to denote the +domain of \( f \), i.e the subset of \( R^n \) where \( f \) is defined. For more +details and proofs we refer to: S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press. + +

+

+
+

+Suppose \( f \) is differentiable (i.e \( \nabla f(x) \) is well defined for +all \( x \) in the domain of \( f \)). Then \( f \) is convex if and only if \( D_f \) +is a convex set and $$f(y) \geq f(x) + \nabla f(x)^T (y-x) $$ holds +for all \( x,y \in D_f \). This condition means that for a convex function +the first order Taylor expansion (right hand side above) at any point +a global under estimator of the function. To convince yourself you can +make a drawing of \( f(x) = x^2+1 \) and draw the tangent line to \( f(x) \) and +note that it is always below the graph. +

+
+ + +

+

+
+

+Assume that \( f \) is twice +differentiable, i.e the Hessian matrix exists at each point in +\( D_f \). Then \( f \) is convex if and only if \( D_f \) is a convex set and its +Hessian is positive semi-definite for all \( x\in D_f \). For a +single-variable function this reduces to \( f''(x) \geq 0 \). Geometrically this means that \( f \) has nonnegative curvature +everywhere. +

+
+ + +

+This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs018.html b/doc/pub/week39/html/._week39-bs018.html new file mode 100644 index 000000000..c86f2308c --- /dev/null +++ b/doc/pub/week39/html/._week39-bs018.html @@ -0,0 +1,364 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

More on convex functions

+ +

+The next result is of great importance to us and the reason why we are +going on about convex functions. In machine learning we frequently +have to minimize a loss/cost function in order to find the best +parameters for the model we are considering. + +

+Ideally we want the +global minimum (for high-dimensional models it is hard to know +if we have local or global minimum). However, if the cost/loss function +is convex the following result provides invaluable information: + +

+

+
+

+Consider the problem of finding \( x \in \mathbb{R}^n \) such that \( f(x) \) +is minimal, where \( f \) is convex and differentiable. Then, any point +\( x^* \) that satisfies \( \nabla f(x^*) = 0 \) is a global minimum. +

+
+ + +

+This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs019.html b/doc/pub/week39/html/._week39-bs019.html new file mode 100644 index 000000000..95bc2bbea --- /dev/null +++ b/doc/pub/week39/html/._week39-bs019.html @@ -0,0 +1,360 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Some simple problems

+ +
    +
  1. Show that \( f(x)=x^2 \) is convex for \( x \in \mathbb{R} \) using the definition of convexity. Hint: If you re-write the definition, \( f \) is convex if the following holds for all \( x,y \in D_f \) and any \( \lambda \in [0,1] \) $\lambda f(x)+(1-\lambda)f(y)-f(\lambda x + (1-\lambda) y ) \geq 0$.
  2. +
  3. Using the second order condition show that the following functions are convex on the specified domain.
  4. + + + +
  5. Let \( f(x) = x^2 \) and \( g(x) = e^x \). Show that \( f(g(x)) \) and \( g(f(x)) \) is convex for \( x \in \mathbb{R} \). Also show that if \( f(x) \) is any convex function than \( h(x) = e^{f(x)} \) is convex.
  6. +
  7. A norm is any function that satisfy the following properties
  8. + + + +
+ +Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs020.html b/doc/pub/week39/html/._week39-bs020.html new file mode 100644 index 000000000..314e6521a --- /dev/null +++ b/doc/pub/week39/html/._week39-bs020.html @@ -0,0 +1,366 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Revisiting our first homework

+ +

+We will use linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: + +

    +
  1. An analytical solution (recall homework set 1).
  2. +
  3. The gradient can be computed analytically.
  4. +
  5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
  6. +
+ +We revisit the example from homework set 1 where we had +$$ +y_i = 5x_i^2 + 0.1\xi_i, \ i=1,\cdots,100 +$$ + +with \( x_i \in [0,1] \) chosen randomly with a uniform distribution. Additionally \( \xi_i \) represents stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +$$ +h_\beta(x) = \hat{y} = \beta_0 + \beta_1 x, +$$ + +such that +$$ +\hat{y}_i = \beta_0 + \beta_1 x_i. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs021.html b/doc/pub/week39/html/._week39-bs021.html new file mode 100644 index 000000000..6ee655550 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs021.html @@ -0,0 +1,358 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient descent example

+ +

+Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\hat{y}} = (\hat{y}_1,\cdots,\hat{y}_n)^T \) and \( \beta = (\beta_0, \beta_1)^T \) + +

+It is convenient to write \( \mathbf{\hat{y}} = X\beta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by +$$ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +$$ + +The loss function is given by +$$ +C(\beta) = ||X\beta-\mathbf{y}||^2 = ||X\beta||^2 - 2 \mathbf{y}^T X\beta + ||\mathbf{y}||^2 = \sum_{i=1}^{100} (\beta_0 + \beta_1 x_i)^2 - 2 y_i (\beta_0 + \beta_1 x_i) + y_i^2 +$$ + +and we want to find \( \beta \) such that \( C(\beta) \) is minimized. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs022.html b/doc/pub/week39/html/._week39-bs022.html new file mode 100644 index 000000000..9b5dc9569 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs022.html @@ -0,0 +1,348 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The derivative of the cost/loss function

+ +

+Computing \( \partial C(\beta) / \partial \beta_0 \) and \( \partial C(\beta) / \partial \beta_1 \) we can show that the gradient can be written as +$$ +\nabla_{\beta} C(\beta) = (\partial C(\beta) / \partial \beta_0, \partial C(\beta) / \partial \beta_1)^T = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = 2X^T(X\beta - \mathbf{y}), +$$ + +where \( X \) is the design matrix defined above. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs023.html b/doc/pub/week39/html/._week39-bs023.html new file mode 100644 index 000000000..93fb691e8 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs023.html @@ -0,0 +1,347 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The Hessian matrix

+The Hessian matrix of \( C(\beta) \) is given by +$$ +\hat{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\beta)}{\partial \beta_0^2} & \frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} \\ +\frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} & \frac{\partial^2 C(\beta)}{\partial \beta_1^2} & \\ +\end{bmatrix} = 2X^T X. +$$ + +This result implies that \( C(\beta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs024.html b/doc/pub/week39/html/._week39-bs024.html new file mode 100644 index 000000000..ebc3b52a9 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs024.html @@ -0,0 +1,353 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Simple program

+ +

+We can now write a program that minimizes \( C(\beta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to +$$ +\beta_{k+1} = \beta_k - \gamma \nabla_\beta C(\beta_k), \ k=0,1,\cdots +$$ + +

+We can use the expression we computed for the gradient and let use a +\( \beta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\beta C(\beta_k) || \leq \epsilon = 10^{-8} \). + +

+And finally we can compare our solution for \( \beta \) with the analytic result given by +\( \beta= (X^TX)^{-1} X^T \mathbf{y} \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs025.html b/doc/pub/week39/html/._week39-bs025.html new file mode 100644 index 000000000..2f5e565c5 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs025.html @@ -0,0 +1,383 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient Descent Example

+ +

+Here our simple example +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 1000
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T.dot(xb.dot(beta)-y)
+    beta -= eta*gradients
+
+print(beta)
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(beta)
+ypredict2 = xbnew.dot(beta_linreg)
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example')
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs026.html b/doc/pub/week39/html/._week39-bs026.html new file mode 100644 index 000000000..47e982f89 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs026.html @@ -0,0 +1,357 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

And a corresponding example using scikit-learn

+ +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+x = 2*np.random.rand(100,1)
+y = 4+3*x+np.random.randn(100,1)
+
+xb = np.c_[np.ones((100,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print(sgdreg.intercept_, sgdreg.coef_)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs027.html b/doc/pub/week39/html/._week39-bs027.html new file mode 100644 index 000000000..de681a49d --- /dev/null +++ b/doc/pub/week39/html/._week39-bs027.html @@ -0,0 +1,358 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient descent and Ridge

+ +

+We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \beta \), +$$ +C_{\text{ridge}}(\beta) = ||X\beta -\mathbf{y}||^2 + \lambda ||\beta||^2, \ \lambda \geq 0. +$$ + +

+In order to minimize \( C_{\text{ridge}}(\beta) \) using GD we only have adjust the gradient as follows +$$ +\nabla_\beta C_{\text{ridge}}(\beta) = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \beta_0 \\ \beta_1\end{bmatrix} = 2 (X^T(X\beta - \mathbf{y})+\lambda \beta). +$$ + +

+We can easily extend our program to minimize \( C_{\text{ridge}}(\beta) \) using gradient descent and compare with the analytical solution given by +$$ +\beta_{\text{ridge}} = \left(X^T X + \lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs028.html b/doc/pub/week39/html/._week39-bs028.html new file mode 100644 index 000000000..b9f46b937 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs028.html @@ -0,0 +1,384 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Program example for gradient descent with Ridge Regression

+

+ + +

from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+XT_X = xb.T @ xb
+
+#Ridge parameter lambda
+lmbda  = 0.001
+Id = lmbda* np.eye(XT_X.shape[0])
+
+beta_linreg = np.linalg.inv(XT_X+Id) @ xb.T @ y
+print(beta_linreg)
+# Start plain gradient descent
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 100
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ (xb @ (beta)-y)+2*lmbda*beta
+    beta -= eta*gradients
+
+print(beta)
+ypredict = xb @ beta
+ypredict2 = xb @ beta_linreg
+plt.plot(x, ypredict, "r-")
+plt.plot(x, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example for Ridge')
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs029.html b/doc/pub/week39/html/._week39-bs029.html new file mode 100644 index 000000000..32c3b7d04 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs029.html @@ -0,0 +1,346 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Using gradient descent methods, limitations

+ + + +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs030.html b/doc/pub/week39/html/._week39-bs030.html new file mode 100644 index 000000000..020f2691d --- /dev/null +++ b/doc/pub/week39/html/._week39-bs030.html @@ -0,0 +1,338 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Friday September 25

+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs031.html b/doc/pub/week39/html/._week39-bs031.html new file mode 100644 index 000000000..1ffb2de0f --- /dev/null +++ b/doc/pub/week39/html/._week39-bs031.html @@ -0,0 +1,351 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Stochastic Gradient Descent

+ +

+Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. + +

+The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs032.html b/doc/pub/week39/html/._week39-bs032.html new file mode 100644 index 000000000..131c59f90 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs032.html @@ -0,0 +1,353 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Computation of gradients

+ +

+This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

+Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs033.html b/doc/pub/week39/html/._week39-bs033.html new file mode 100644 index 000000000..78843ef81 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs033.html @@ -0,0 +1,357 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

SGD example

+As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). + +

+The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs034.html b/doc/pub/week39/html/._week39-bs034.html new file mode 100644 index 000000000..6c021bfb2 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs034.html @@ -0,0 +1,352 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The gradient step

+ +

+Thus a gradient descent step now looks like +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

+where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs035.html b/doc/pub/week39/html/._week39-bs035.html new file mode 100644 index 000000000..945b02ea2 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs035.html @@ -0,0 +1,365 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Simple example code

+ +

+ + +

import numpy as np 
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 10 #number of epochs
+
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for 
+        j += 1
+
+

+Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs036.html b/doc/pub/week39/html/._week39-bs036.html new file mode 100644 index 000000000..420267b2c --- /dev/null +++ b/doc/pub/week39/html/._week39-bs036.html @@ -0,0 +1,350 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

When do we stop?

+ +

+A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs037.html b/doc/pub/week39/html/._week39-bs037.html new file mode 100644 index 000000000..032687147 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs037.html @@ -0,0 +1,381 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Slightly different approach

+ +

+Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. + +

+As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \). + +

+In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. + +

+ + +

import numpy as np 
+
+def step_length(t,t0,t1):
+    return t0/(t+t1)
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 500 #number of epochs
+t0 = 1.0
+t1 = 10
+
+gamma_j = t0/t1
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for beta
+        t = epoch*m+i
+        gamma_j = step_length(t,t0,t1)
+        j += 1
+
+print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs038.html b/doc/pub/week39/html/._week39-bs038.html new file mode 100644 index 000000000..3b004e4a2 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs038.html @@ -0,0 +1,409 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Program for stochastic gradient

+ +

+ + +

# Importing various packages
+from math import exp, sqrt
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print("Own inversion")
+print(theta_linreg)
+sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print("sgdreg from scikit")
+print(sgdreg.intercept_, sgdreg.coef_)
+
+
+theta = np.random.randn(2,1)
+eta = 0.1
+Niterations = 1000
+
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ ((xb @ theta)-y)
+    theta -= eta*gradients
+print("theta frm own gd")
+print(theta)
+
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(theta)
+ypredict2 = xbnew.dot(theta_linreg)
+
+
+n_epochs = 50
+t0, t1 = 5, 50
+def learning_schedule(t):
+    return t0/(t+t1)
+
+theta = np.random.randn(2,1)
+
+for epoch in range(n_epochs):
+    for i in range(m):
+        random_index = np.random.randint(m)
+        xi = xb[random_index:random_index+1]
+        yi = y[random_index:random_index+1]
+        gradients = 2 * xi.T @ ((xi @ theta)-yi)
+        eta = learning_schedule(epoch*m+i)
+        theta = theta - eta*gradients
+print("theta from own sdg")
+print(theta)
+
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Random numbers ')
+plt.show()
+
+

+Challenge: try to write a similar code for a Logistic Regression case. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs039.html b/doc/pub/week39/html/._week39-bs039.html new file mode 100644 index 000000000..68c46b74d --- /dev/null +++ b/doc/pub/week39/html/._week39-bs039.html @@ -0,0 +1,370 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Momentum based GD

+ +

+The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\tag{2} +\end{align} +$$ + +

+where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is + +$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ + +where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs040.html b/doc/pub/week39/html/._week39-bs040.html new file mode 100644 index 000000000..1a90db0aa --- /dev/null +++ b/doc/pub/week39/html/._week39-bs040.html @@ -0,0 +1,363 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

More on momentum based approaches

+ +

+Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by + +$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ + +

+We can discretize this equation in the usual way to get + +$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ + +

+Rearranging this equation, we can rewrite this as + +$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs041.html b/doc/pub/week39/html/._week39-bs041.html new file mode 100644 index 000000000..d4cfb5787 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs041.html @@ -0,0 +1,389 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Momentum parameter

+ +

+Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: + +$$ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +$$ + +

+Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). + +

+Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. + +

+These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). + +

+In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\tag{3} +\end{align} +$$ + +

+One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs042.html b/doc/pub/week39/html/._week39-bs042.html new file mode 100644 index 000000000..b86a81c79 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs042.html @@ -0,0 +1,361 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Second moment of the gradient

+ +

+In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. + +

+Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and +ADAM. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs043.html b/doc/pub/week39/html/._week39-bs043.html new file mode 100644 index 000000000..3377e6091 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs043.html @@ -0,0 +1,364 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

RMS prop

+ +

+In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given by + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{4}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ + +

+where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs044.html b/doc/pub/week39/html/._week39-bs044.html new file mode 100644 index 000000000..f7a7c0eda --- /dev/null +++ b/doc/pub/week39/html/._week39-bs044.html @@ -0,0 +1,382 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

ADAM optimizer

+ +

+A related algorithm is the ADAM optimizer. In ADAM, we keep a running +average of both the first and second moment of the gradient and use +this information to adaptively change the learning rate for different +parameters. In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{5}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\hat{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\hat{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \hat{\mathbf{m}}_t \over \sqrt{\hat{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\tag{6} +\end{align} +$$ + +

+where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. + +

+Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \hat{\mathbf{s}}_t - +(\hat{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by + +$$ +\Delta \theta_{t+1}= -\eta_t { \hat{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs045.html b/doc/pub/week39/html/._week39-bs045.html new file mode 100644 index 000000000..7390fc2de --- /dev/null +++ b/doc/pub/week39/html/._week39-bs045.html @@ -0,0 +1,347 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Practical tips

+ + + +Geron's text, see chapter 11, has several interesting discussions. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs046.html b/doc/pub/week39/html/._week39-bs046.html new file mode 100644 index 000000000..39104ee0b --- /dev/null +++ b/doc/pub/week39/html/._week39-bs046.html @@ -0,0 +1,418 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Automatic differentiation

+ +

+Automatic differentiation (AD), +also called algorithmic +differentiation or computational differentiation,is a set of +techniques to numerically evaluate the derivative of a function +specified by a computer program. AD exploits the fact that every +computer program, no matter how complicated, executes a sequence of +elementary arithmetic operations (addition, subtraction, +multiplication, division, etc.) and elementary functions (exp, log, +sin, cos, etc.). By applying the chain rule repeatedly to these +operations, derivatives of arbitrary order can be computed +automatically, accurately to working precision, and using at most a +small constant factor more arithmetic operations than the original +program. + +

+Automatic differentiation is neither: + +

+ +Symbolic differentiation can lead to inefficient code and faces the +difficulty of converting a computer program into a single expression, +while numerical differentiation can introduce round-off errors in the +discretization process and cancellation + +

+Python has tools for so-called automatic differentiation. +Consider the following example +$$ +f(x) = \sin\left(2\pi x + x^2\right) +$$ + +which has the following derivative +$$ +f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) +$$ + +Using autograd we have + +

+ + +

import autograd.numpy as np
+
+# To do elementwise differentiation:
+from autograd import elementwise_grad as egrad 
+
+# To plot:
+import matplotlib.pyplot as plt 
+
+
+def f(x):
+    return np.sin(2*np.pi*x + x**2)
+
+def f_grad_analytic(x):
+    return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
+
+# Do the comparison:
+x = np.linspace(0,1,1000)
+
+f_grad = egrad(f)
+
+computed = f_grad(x)
+analytic = f_grad_analytic(x)
+
+plt.title('Derivative computed from Autograd compared with the analytical derivative')
+plt.plot(x,computed,label='autograd')
+plt.plot(x,analytic,label='analytic')
+
+plt.xlabel('x')
+plt.ylabel('y')
+plt.legend()
+
+plt.show()
+
+print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs047.html b/doc/pub/week39/html/._week39-bs047.html new file mode 100644 index 000000000..cd3d8e82b --- /dev/null +++ b/doc/pub/week39/html/._week39-bs047.html @@ -0,0 +1,366 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Using autograd

+ +

+Here we +experiment with what kind of functions Autograd is capable +of finding the gradient of. The following Python functions are just +meant to illustrate what Autograd can do, but please feel free to +experiment with other, possibly more complicated, functions as well. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f1(x):
+    return x**3 + 1
+
+f1_grad = grad(f1)
+
+# Remember to send in float as argument to the computed gradient from Autograd!
+a = 1.0
+
+# See the evaluated gradient at a using autograd:
+print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a)))
+
+# Compare with the analytical derivative, that is f1'(x) = 3*x**2 
+grad_analytical = 3*a**2
+print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs048.html b/doc/pub/week39/html/._week39-bs048.html new file mode 100644 index 000000000..557adc05a --- /dev/null +++ b/doc/pub/week39/html/._week39-bs048.html @@ -0,0 +1,383 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Autograd with more complicated functions

+ +

+To differentiate with respect to two (or more) arguments of a Python +function, Autograd need to know at which variable the function if +being differentiated with respect to. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f2(x1,x2):
+    return 3*x1**3 + x2*(x1 - 5) + 1
+
+# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1
+f2_grad_x1 = grad(f2,0)
+
+# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad
+f2_grad_x2 = grad(f2,1)
+
+x1 = 1.0
+x2 = 3.0 
+
+print("Evaluating at x1 = %g, x2 = %g"%(x1,x2))
+print("-"*30)
+
+# Compare with the analytical derivatives:
+
+# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:
+f2_grad_x1_analytical = 9*x1**2 + x2
+
+# Derivative of f2 w.r.t x2 is: x1 - 5:
+f2_grad_x2_analytical = x1 - 5
+
+# See the evaluated derivations:
+print("The derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+
+print()
+
+print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+
+

+Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs049.html b/doc/pub/week39/html/._week39-bs049.html new file mode 100644 index 000000000..7e6074737 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs049.html @@ -0,0 +1,367 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

More complicated functions using the elements of their arguments directly

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f3(x): # Assumes x is an array of length 5 or higher
+    return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
+
+f3_grad = grad(f3)
+
+x = np.linspace(0,4,5)
+
+# Print the computed gradient:
+print("The computed gradient of f3 is: ", f3_grad(x))
+
+# The analytical gradient is: (2, 3, 5, 7, 22*x[4])
+f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])
+
+# Print the analytical gradient:
+print("The analytical gradient of f3 is: ", f3_grad_analytical)
+
+

+Note that in this case, when sending an array as input argument, the +output from Autograd is another array. This is the true gradient of +the function, as opposed to the function in the previous example. By +using arrays to represent the variables, the output from Autograd +might be easier to work with, as the output is closer to what one +could expect form a gradient-evaluting function. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs050.html b/doc/pub/week39/html/._week39-bs050.html new file mode 100644 index 000000000..2729af8b2 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs050.html @@ -0,0 +1,359 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Functions using mathematical functions from Numpy

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f4(x):
+    return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
+
+f4_grad = grad(f4)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x)))
+
+# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi
+f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi
+
+# Print the analytical gradient:
+print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs051.html b/doc/pub/week39/html/._week39-bs051.html new file mode 100644 index 000000000..8ae82d470 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs051.html @@ -0,0 +1,356 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

More autograd

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f5(x):
+    if x >= 0:
+        return x**2
+    else:
+        return -3*x + 1
+
+f5_grad = grad(f5)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs052.html b/doc/pub/week39/html/._week39-bs052.html new file mode 100644 index 000000000..7115363fe --- /dev/null +++ b/doc/pub/week39/html/._week39-bs052.html @@ -0,0 +1,379 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

And with loops

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f6_for(x):
+    val = 0
+    for i in range(10):
+        val = val + x**i
+    return val
+
+def f6_while(x):
+    val = 0
+    i = 0
+    while i < 10:
+        val = val + x**i
+        i = i + 1
+    return val
+
+f6_for_grad = grad(f6_for)
+f6_while_grad = grad(f6_while)
+
+x = 0.5
+
+# Print the computed derivaties of f6_for and f6_while
+print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
+print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
+
+

+ + +

import autograd.numpy as np
+from autograd import grad
+# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
+# The analytical derivative is: sum(i*x**(i-1)) 
+f6_grad_analytical = 0
+for i in range(10):
+    f6_grad_analytical += i*x**(i-1)
+
+print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs053.html b/doc/pub/week39/html/._week39-bs053.html new file mode 100644 index 000000000..13559746a --- /dev/null +++ b/doc/pub/week39/html/._week39-bs053.html @@ -0,0 +1,371 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Using recursion

+

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f7(n): # Assume that n is an integer
+    if n == 1 or n == 0:
+        return 1
+    else:
+        return n*f7(n-1)
+
+f7_grad = grad(f7)
+
+n = 2.0
+
+print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n)))
+
+# The function f7 is an implementation of the factorial of n.
+# By using the product rule, one can find that the derivative is:
+
+f7_grad_analytical = 0
+for i in range(int(n)-1):
+    tmp = 1
+    for k in range(int(n)-1):
+        if k != i:
+            tmp *= (n - k)
+    f7_grad_analytical += tmp
+
+print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
+
+

+Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs054.html b/doc/pub/week39/html/._week39-bs054.html new file mode 100644 index 000000000..ce003f63f --- /dev/null +++ b/doc/pub/week39/html/._week39-bs054.html @@ -0,0 +1,359 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Unsupported functions

+Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. + +

+Assigning a value to the variable being differentiated with respect to +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f8(x): # Assume x is an array
+    x[2] = 3
+    return x*2
+
+f8_grad = grad(f8)
+
+x = 8.4
+
+print("The derivative of f8 is:",f8_grad(x))
+
+

+Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs055.html b/doc/pub/week39/html/._week39-bs055.html new file mode 100644 index 000000000..40f96bf8b --- /dev/null +++ b/doc/pub/week39/html/._week39-bs055.html @@ -0,0 +1,375 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The syntax a.dot(b) when finding the dot product

+

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9(a): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return a.dot(b)
+
+f9_grad = grad(f9)
+
+x = np.array([1.0,0.0])
+
+print("The derivative of f9 is:",f9_grad(x))
+
+

+Here we are told that the 'dot' function does not belong to Autograd's +version of a Numpy array. To overcome this, an alternative syntax +which also computed the dot product can be used: + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9_alternative(x): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2
+
+f9_alternative_grad = grad(f9_alternative)
+
+x = np.array([3.0,0.0])
+
+print("The gradient of f9 is:",f9_alternative_grad(x))
+
+# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
+# w.r.t x is (b_1, b_2).
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs056.html b/doc/pub/week39/html/._week39-bs056.html new file mode 100644 index 000000000..41f7c3c63 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs056.html @@ -0,0 +1,346 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Recommended to avoid

+The documentation recommends to avoid inplace operations such as +

+ + +

a += b
+a -= b
+a*= b
+a /=b
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs057.html b/doc/pub/week39/html/._week39-bs057.html new file mode 100644 index 000000000..f73ca1f77 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs057.html @@ -0,0 +1,369 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Standard steepest descent

+ +

+Before we proceed, we would like to discuss the approach called the +standard Steepest descent, which again leads to us having to be able +to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG). + +

+The success of the CG method +for finding solutions of non-linear problems is based on the theory +of conjugate gradients for linear systems of equations. It belongs to +the class of iterative methods for solving problems from linear +algebra of the type +$$ +\begin{equation*} +\hat{A}\hat{x} = \hat{b}. +\end{equation*} +$$ + +

+In the iterative process we end up with a problem like + +$$ +\begin{equation*} + \hat{r}= \hat{b}-\hat{A}\hat{x}, +\end{equation*} +$$ + +where \( \hat{r} \) is the so-called residual or error in the iterative process. + +

+When we have found the exact solution, \( \hat{r}=0 \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs058.html b/doc/pub/week39/html/._week39-bs058.html new file mode 100644 index 000000000..c2a266507 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs058.html @@ -0,0 +1,350 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient method

+ +

+The residual is zero when we reach the minimum of the quadratic equation +$$ +\begin{equation*} + P(\hat{x})=\frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T\hat{b}, +\end{equation*} +$$ + +

+with the constraint that the matrix \( \hat{A} \) is positive definite and +symmetric. This defines also the Hessian and we want it to be positive definite. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs059.html b/doc/pub/week39/html/._week39-bs059.html new file mode 100644 index 000000000..25240201f --- /dev/null +++ b/doc/pub/week39/html/._week39-bs059.html @@ -0,0 +1,356 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Steepest descent method

+ +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ + +or consider the system +$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ + +instead. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs060.html b/doc/pub/week39/html/._week39-bs060.html new file mode 100644 index 000000000..77f11031b --- /dev/null +++ b/doc/pub/week39/html/._week39-bs060.html @@ -0,0 +1,364 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Steepest descent method

+
+
+

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ + +This suggests taking the first basis vector \( \hat{r}_1 \) (see below for definition) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ + +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). + +

+

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs061.html b/doc/pub/week39/html/._week39-bs061.html new file mode 100644 index 000000000..a22244a09 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs061.html @@ -0,0 +1,377 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Final expressions

+
+
+

+We can compute the residual iteratively as +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ + +which equals +$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{r}_k), + \end{equation*} +$$ + +or +$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{r}_k, + \end{equation*} +$$ + +which gives + +$$ +\alpha_k = \frac{\hat{r}_k^T\hat{r}_k}{\hat{r}_k^T\hat{A}\hat{r}_k} +$$ + +leading to the iterative scheme +$$ +\begin{equation*} +\hat{x}_{k+1}=\hat{x}_k-\alpha_k\hat{r}_{k}, + \end{equation*} +$$ +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs062.html b/doc/pub/week39/html/._week39-bs062.html new file mode 100644 index 000000000..645ec4e3d --- /dev/null +++ b/doc/pub/week39/html/._week39-bs062.html @@ -0,0 +1,338 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Code examples for steepest descent

+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs063.html b/doc/pub/week39/html/._week39-bs063.html new file mode 100644 index 000000000..92d4f6d06 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs063.html @@ -0,0 +1,374 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Simple codes for steepest descent and conjugate gradient using a \( 2\times 2 \) matrix, in c++, Python code to come

+
+
+

+

+ + +

#include <cmath>
+#include <iostream>
+#include <fstream>
+#include <iomanip>
+#include "vectormatrixclass.h"
+using namespace  std;
+//   Main function begins here
+int main(int  argc, char * argv[]){
+  int dim = 2;
+  Vector x(dim),xsd(dim), b(dim),x0(dim);
+  Matrix A(dim,dim);
+
+  // Set our initial guess
+  x0(0) = x0(1) = 0;
+  // Set the matrix
+  A(0,0) =  3;    A(1,0) =  2;   A(0,1) =  2;   A(1,1) =  6;
+  b(0) = 2; b(1) = -8;
+  cout << "The Matrix A that we are using: " << endl;
+  A.Print();
+  cout << endl;
+  xsd = SteepestDescent(A,b,x0);
+  cout << "The approximate solution using Steepest Descent is: " << endl;
+  xsd.Print();
+  cout << endl;
+}
+
+

+

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs064.html b/doc/pub/week39/html/._week39-bs064.html new file mode 100644 index 000000000..bfd71eecf --- /dev/null +++ b/doc/pub/week39/html/._week39-bs064.html @@ -0,0 +1,370 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The routine for the steepest descent method

+
+
+

+

+ + +

Vector SteepestDescent(Matrix A, Vector b, Vector x0){
+  int IterMax, i;
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),f(dim),z(dim);
+  double c,alpha,d;
+  IterMax = 30;
+  x = x0;
+  r = A*x-b;
+  i = 0;
+  while (i <= IterMax){
+    z = A*r;
+    c = dot(r,r);
+    alpha = c/dot(r,z);
+    x = x - alpha*r;
+    r =  A*x-b;
+    if(sqrt(dot(r,r)) < tolerance) break;
+    i++;
+  }
+  return x;
+}
+
+

+

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs065.html b/doc/pub/week39/html/._week39-bs065.html new file mode 100644 index 000000000..26c2773f9 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs065.html @@ -0,0 +1,402 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Steepest descent example

+ +

+ + +

import numpy as np
+import numpy.linalg as la
+
+import scipy.optimize as sopt
+
+import matplotlib.pyplot as pt
+from mpl_toolkits.mplot3d import axes3d
+
+def f(x):
+    return 0.5*x[0]**2 + 2.5*x[1]**2
+
+def df(x):
+    return np.array([x[0], 5*x[1]])
+
+fig = pt.figure()
+ax = fig.gca(projection="3d")
+
+xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
+fmesh = f(np.array([xmesh, ymesh]))
+ax.plot_surface(xmesh, ymesh, fmesh)
+
+

+And then as countor plot +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh)
+guesses = [np.array([2, 2./5])]
+
+

+Find guesses +

+ + +

x = guesses[-1]
+s = -df(x)
+
+

+Run it! +

+ + +

def f1d(alpha):
+    return f(x + alpha*s)
+
+alpha_opt = sopt.golden(f1d)
+next_guess = x + alpha_opt * s
+guesses.append(next_guess)
+print(next_guess)
+
+

+What happened? +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh, 50)
+it_array = np.array(guesses)
+pt.plot(it_array.T[0], it_array.T[1], "x-")
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs066.html b/doc/pub/week39/html/._week39-bs066.html new file mode 100644 index 000000000..e6ff07457 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs066.html @@ -0,0 +1,362 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method

+
+
+

+In the CG method we define so-called conjugate directions and two vectors +\( \hat{s} \) and \( \hat{t} \) +are said to be +conjugate if +$$ +\begin{equation*} +\hat{s}^T\hat{A}\hat{t}= 0. +\end{equation*} +$$ + +The philosophy of the CG method is to perform searches in various conjugate directions +of our vectors \( \hat{x}_i \) obeying the above criterion, namely +$$ +\begin{equation*} +\hat{x}_i^T\hat{A}\hat{x}_j= 0. +\end{equation*} +$$ + +Two vectors are conjugate if they are orthogonal with respect to +this inner product. Being conjugate is a symmetric relation: if \( \hat{s} \) is conjugate to \( \hat{t} \), then \( \hat{t} \) is conjugate to \( \hat{s} \). +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs067.html b/doc/pub/week39/html/._week39-bs067.html new file mode 100644 index 000000000..a9ff00f3a --- /dev/null +++ b/doc/pub/week39/html/._week39-bs067.html @@ -0,0 +1,349 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method

+
+
+

+An example is given by the eigenvectors of the matrix +$$ +\begin{equation*} +\hat{v}_i^T\hat{A}\hat{v}_j= \lambda\hat{v}_i^T\hat{v}_j, +\end{equation*} +$$ + +which is zero unless \( i=j \). +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs068.html b/doc/pub/week39/html/._week39-bs068.html new file mode 100644 index 000000000..6c1e7919c --- /dev/null +++ b/doc/pub/week39/html/._week39-bs068.html @@ -0,0 +1,357 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method

+
+
+

+Assume now that we have a symmetric positive-definite matrix \( \hat{A} \) of size +\( n\times n \). At each iteration \( i+1 \) we obtain the conjugate direction of a vector +$$ +\begin{equation*} +\hat{x}_{i+1}=\hat{x}_{i}+\alpha_i\hat{p}_{i}. +\end{equation*} +$$ + +We assume that \( \hat{p}_{i} \) is a sequence of \( n \) mutually conjugate directions. +Then the \( \hat{p}_{i} \) form a basis of \( R^n \) and we can expand the solution +$ \hat{A}\hat{x} = \hat{b}$ in this basis, namely + +$$ +\begin{equation*} + \hat{x} = \sum^{n}_{i=1} \alpha_i \hat{p}_i. +\end{equation*} +$$ +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs069.html b/doc/pub/week39/html/._week39-bs069.html new file mode 100644 index 000000000..c9aa99a4d --- /dev/null +++ b/doc/pub/week39/html/._week39-bs069.html @@ -0,0 +1,361 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method

+
+
+

+The coefficients are given by +$$ +\begin{equation*} + \mathbf{A}\mathbf{x} = \sum^{n}_{i=1} \alpha_i \mathbf{A} \mathbf{p}_i = \mathbf{b}. +\end{equation*} +$$ + +Multiplying with \( \hat{p}_k^T \) from the left gives + +$$ +\begin{equation*} + \hat{p}_k^T \hat{A}\hat{x} = \sum^{n}_{i=1} \alpha_i\hat{p}_k^T \hat{A}\hat{p}_i= \hat{p}_k^T \hat{b}, +\end{equation*} +$$ + +and we can define the coefficients \( \alpha_k \) as + +$$ +\begin{equation*} + \alpha_k = \frac{\hat{p}_k^T \hat{b}}{\hat{p}_k^T \hat{A} \hat{p}_k} +\end{equation*} +$$ +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs070.html b/doc/pub/week39/html/._week39-bs070.html new file mode 100644 index 000000000..46944c9e0 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs070.html @@ -0,0 +1,364 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method and iterations

+
+
+

+ +

+If we choose the conjugate vectors \( \hat{p}_k \) carefully, +then we may not need all of them to obtain a good approximation to the solution +\( \hat{x} \). +We want to regard the conjugate gradient method as an iterative method. +This will us to solve systems where \( n \) is so large that the direct +method would take too much time. + +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ + +or consider the system +$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ + +instead. +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs071.html b/doc/pub/week39/html/._week39-bs071.html new file mode 100644 index 000000000..e267c1139 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs071.html @@ -0,0 +1,357 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method

+
+
+

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ + +This suggests taking the first basis vector \( \hat{p}_1 \) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ + +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). +The other vectors in the basis will be conjugate to the gradient, +hence the name conjugate gradient method. +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs072.html b/doc/pub/week39/html/._week39-bs072.html new file mode 100644 index 000000000..53c0187ac --- /dev/null +++ b/doc/pub/week39/html/._week39-bs072.html @@ -0,0 +1,355 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method

+
+
+

+Let \( \hat{r}_k \) be the residual at the \( k \)-th step: +$$ +\begin{equation*} +\hat{r}_k=\hat{b}-\hat{A}\hat{x}_k. +\end{equation*} +$$ + +Note that \( \hat{r}_k \) is the negative gradient of \( f \) at +\( \hat{x}=\hat{x}_k \), +so the gradient descent method would be to move in the direction \( \hat{r}_k \). +Here, we insist that the directions \( \hat{p}_k \) are conjugate to each other, +so we take the direction closest to the gradient \( \hat{r}_k \) +under the conjugacy constraint. +This gives the following expression +$$ +\begin{equation*} +\hat{p}_{k+1}=\hat{r}_k-\frac{\hat{p}_k^T \hat{A}\hat{r}_k}{\hat{p}_k^T\hat{A}\hat{p}_k} \hat{p}_k. +\end{equation*} +$$ +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs073.html b/doc/pub/week39/html/._week39-bs073.html new file mode 100644 index 000000000..b2691b13f --- /dev/null +++ b/doc/pub/week39/html/._week39-bs073.html @@ -0,0 +1,363 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Conjugate gradient method

+
+
+

+We can also compute the residual iteratively as +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ + +which equals +$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{p}_k), + \end{equation*} +$$ + +or +$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{p}_k, + \end{equation*} +$$ + +which gives + +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{r}_k-\hat{A}\hat{p}_{k}, + \end{equation*} +$$ +

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs074.html b/doc/pub/week39/html/._week39-bs074.html new file mode 100644 index 000000000..9ce7a8b3b --- /dev/null +++ b/doc/pub/week39/html/._week39-bs074.html @@ -0,0 +1,363 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Simple implementation of the Conjugate gradient algorithm

+
+
+

+

+ + +

  Vector ConjugateGradient(Matrix A, Vector b, Vector x0){
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),r(dim),v(dim),z(dim);
+  double c,t,d;
+
+  x = x0;
+  r = b - A*x;
+  v = r;
+  c = dot(r,r);
+  int i = 0; IterMax = dim;
+  while(i <= IterMax){
+    z = A*v;
+    t = c/dot(v,z);
+    x = x + t*v;
+    r = r - t*z;
+    d = dot(r,r);
+    if(sqrt(d) < tolerance)
+      break;
+    v = r + (d/c)*v;
+    c = d;  i++;
+  }
+  return x;
+} 
+
+

+

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/._week39-bs075.html b/doc/pub/week39/html/._week39-bs075.html new file mode 100644 index 000000000..b94e79c80 --- /dev/null +++ b/doc/pub/week39/html/._week39-bs075.html @@ -0,0 +1,358 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Broyden–Fletcher–Goldfarb–Shanno algorithm

+
+
+

+The optimization problem is to minimize \( f(\mathbf {x} ) \) where \( \mathbf {x} \) is a vector in \( R^{n} \), and \( f \) is a differentiable scalar function. There are no constraints on the values that \( \mathbf {x} \) can take. + +

+The algorithm begins at an initial estimate for the optimal value \( \mathbf {x}_{0} \) and proceeds iteratively to get a better estimate at each stage. + +

+The search direction \( p_k \) at stage \( k \) is given by the solution of the analogue of the Newton equation +$$ +B_{k}\mathbf {p} _{k}=-\nabla f(\mathbf {x}_{k}), +$$ + +

+where \( B_{k} \) is an approximation to the Hessian matrix, which is +updated iteratively at each stage, and \( \nabla f(\mathbf {x} _{k}) \) +is the gradient of the function +evaluated at \( x_k \). +A line search in the direction \( p_k \) is then used to +find the next point \( x_{k+1} \) by minimising +$$ +f(\mathbf {x}_{k}+\alpha \mathbf {p}_{k}), +$$ + +over the scalar \( \alpha > 0 \). + +

+

+
+ + +

+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week39/html/reveal.js/.gitignore b/doc/pub/week39/html/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/pub/week39/html/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/pub/week39/html/reveal.js/.travis.yml b/doc/pub/week39/html/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/pub/week39/html/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/week39/html/reveal.js/CONTRIBUTING.md b/doc/pub/week39/html/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/pub/week39/html/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/pub/week39/html/reveal.js/Gruntfile.js b/doc/pub/week39/html/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/pub/week39/html/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/pub/week39/html/reveal.js/LICENSE b/doc/pub/week39/html/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/pub/week39/html/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/pub/week39/html/reveal.js/README.md b/doc/pub/week39/html/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/pub/week39/html/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
+
+
Single Horizontal Slide
+
+
Vertical Slide 1
+
Vertical Slide 2
+
+
+
+``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` +
+``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
+
+``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
+ +
+``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. + +```html +
+ +
+``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
+``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
+

All CSS color formats are supported, like rgba() or hsl().

+
+
+

This slide will have a full-size background image.

+
+
+

This background image will be sized to 100px and repeated.

+
+
+

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

+
+
+

Embeds a web page as a background. Note that the page won't be interactive.

+
+``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
+

This slide will override the presentation transition and zoom!

+
+ +
+

Choose from three transition speeds: default, fast or slow!

+
+``` + +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
+

grow

+

shrink

+

fade-out

+

visible only once

+

blue only once

+

highlight-red

+

highlight-green

+

highlight-blue

+
+``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
+ + I'll fade in, then out + +
+``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
+

Appears last

+

Appears first

+

Appears second

+
+``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
+

+(def lazy-fib
+  (concat
+   [0 1]
+   ((fn rfib [a b]
+        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
+	
+
+``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `
+ +
+ +

 

 

 

+ + + + + + +
+

Week 39: Optimization and Gradient Methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week39/html/week39-reveal.html b/doc/pub/week39/html/week39-reveal.html new file mode 100644 index 000000000..2b9866219 --- /dev/null +++ b/doc/pub/week39/html/week39-reveal.html @@ -0,0 +1,2702 @@ + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + + + + + + + + + + +
+ + + + +

Week 39: Optimization and Gradient Methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

 
+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

 
+

Sep 16, 2020

+
+

+ +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+
+ + +
+

Plan for week 39

+ +
    +

  • Thursday: Repetition of Logistic regression equations and discussion of Gradient methods
  • +

  • Friday: Stochastic Gradient descent with examples and automatic differeantion
  • +
+
+ + +
+

Thursday September 24

+
+ + +
+

Optimization, the central part of any Machine Learning algortithm

+ +

+Almost every problem in machine learning and data science starts with +a dataset \( X \), a model \( g(\beta) \), which is a function of the +parameters \( \beta \) and a cost function \( C(X, g(\beta)) \) that allows +us to judge how well the model \( g(\beta) \) explains the observations +\( X \). The model is fit by finding the values of \( \beta \) that minimize +the cost function. Ideally we would be able to solve for \( \beta \) +analytically, however this is not possible in general and we must use +some approximative/numerical method to compute the minimum. +

+ + +
+

Revisiting our Logistic Regression case

+ +

+In our discussion on Logistic Regression we studied the +case of +two classes, with \( y_i \) either +\( 0 \) or \( 1 \). Furthermore we assumed also that we have only two +parameters \( \beta \) in our fitting, that is we +defined probabilities + +

 
+$$ +\begin{align*} +p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ +p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), +\end{align*} +$$ +

 
+ +where \( \hat{\beta} \) are the weights we wish to extract from data, in our case \( \beta_0 \) and \( \beta_1 \). +

+ + +
+

The equations to solve

+ +

+Our compact equations used a definition of a vector \( \hat{y} \) with \( n \) +elements \( y_i \), an \( n\times p \) matrix \( \hat{X} \) which contains the +\( x_i \) values and a vector \( \hat{p} \) of fitted probabilities +\( p(y_i\vert x_i,\hat{\beta}) \). We rewrote in a more compact form +the first derivative of the cost function as + +

 
+$$ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). +$$ +

 
+ +

+If we in addition define a diagonal matrix \( \hat{W} \) with elements +\( p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta}) \), we can obtain a compact expression of the second derivative as + +

 
+$$ +\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. +$$ +

 
+ +This defines what is called the Hessian matrix. +

+ + +
+

Solving using Newton-Raphson's method

+ +

+If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. + +

+Our iterative scheme is then given by + +

 
+$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T}\right)^{-1}_{\hat{\beta}^{\mathrm{old}}}\times \left(\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}}\right)_{\hat{\beta}^{\mathrm{old}}}, +$$ +

 
+ +or in matrix form as + +

 
+$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\hat{X}^T\hat{W}\hat{X} \right)^{-1}\times \left(-\hat{X}^T(\hat{y}-\hat{p}) \right)_{\hat{\beta}^{\mathrm{old}}}. +$$ +

 
+ +The right-hand side is computed with the old values of \( \beta \). + +

+If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement. +

+ + +
+

Brief reminder on Newton-Raphson's method

+ +

+Let us quickly remind ourselves how we derive the above method. + +

+Perhaps the most celebrated of all one-dimensional root-finding +routines is Newton's method, also called the Newton-Raphson +method. This method requires the evaluation of both the +function \( f \) and its derivative \( f' \) at arbitrary points. +If you can only calculate the derivative +numerically and/or your function is not of the smooth type, we +normally discourage the use of this method. +

+ + +
+

The equations

+ +

+The Newton-Raphson formula consists geometrically of extending the +tangent line at a current point until it crosses zero, then setting +the next guess to the abscissa of that zero-crossing. The mathematics +behind this method is rather simple. Employing a Taylor expansion for +\( x \) sufficiently close to the solution \( s \), we have + +

 
+$$ + f(s)=0=f(x)+(s-x)f'(x)+\frac{(s-x)^2}{2}f''(x) +\dots. + \tag{1} +$$ +

 
+ +

+For small enough values of the function and for well-behaved +functions, the terms beyond linear are unimportant, hence we obtain + +

 
+$$ + f(x)+(s-x)f'(x)\approx 0, +$$ +

 
+ +yielding +

 
+$$ + s\approx x-\frac{f(x)}{f'(x)}. +$$ +

 
+ +

+Having in mind an iterative procedure, it is natural to start iterating with +

 
+$$ + x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}. +$$ +

 
+

+ + +
+

Simple geometric interpretation

+ +

+The above is Newton-Raphson's method. It has a simple geometric +interpretation, namely \( x_{n+1} \) is the point where the tangent from +\( (x_n,f(x_n)) \) crosses the \( x \)-axis. Close to the solution, +Newton-Raphson converges fast to the desired result. However, if we +are far from a root, where the higher-order terms in the series are +important, the Newton-Raphson formula can give grossly inaccurate +results. For instance, the initial guess for the root might be so far +from the true root as to let the search interval include a local +maximum or minimum of the function. If an iteration places a trial +guess near such a local extremum, so that the first derivative nearly +vanishes, then Newton-Raphson may fail totally +

+ + +
+

Extending to more than one variable

+ +

+Newton's method can be generalized to systems of several non-linear equations +and variables. Consider the case with two equations +

 
+$$ + \begin{array}{cc} f_1(x_1,x_2) &=0\\ + f_2(x_1,x_2) &=0,\end{array} +$$ +

 
+ +which we Taylor expand to obtain + +

 
+$$ + \begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1 + \partial f_1/\partial x_1+h_2 + \partial f_1/\partial x_2+\dots\\ + 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1 + \partial f_2/\partial x_1+h_2 + \partial f_2/\partial x_2+\dots + \end{array}. +$$ +

 
+ +Defining the Jacobian matrix \( {\bf \hat{J}} \) we have +

 
+$$ + {\bf \hat{J}}=\left( \begin{array}{cc} + \partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\ + \partial f_2/\partial x_1 &\partial f_2/\partial x_2 + \end{array} \right), +$$ +

 
+ +we can rephrase Newton's method as +

 
+$$ +\left(\begin{array}{c} x_1^{n+1} \\ x_2^{n+1} \end{array} \right)= +\left(\begin{array}{c} x_1^{n} \\ x_2^{n} \end{array} \right)+ +\left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right), +$$ +

 
+ +where we have defined +

 
+$$ + \left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)= + -{\bf \hat{J}}^{-1} + \left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right). +$$ +

 
+ +We need thus to compute the inverse of the Jacobian matrix and it +is to understand that difficulties may +arise in case \( {\bf \hat{J}} \) is nearly singular. + +

+It is rather straightforward to extend the above scheme to systems of +more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. +

+ + +
+

Steepest descent

+ +

+The basic idea of gradient descent is +that a function \( F(\mathbf{x}) \), +\( \mathbf{x} \equiv (x_1,\cdots,x_n) \), decreases fastest if one goes from \( \bf {x} \) in the +direction of the negative gradient \( -\nabla F(\mathbf{x}) \). + +

+It can be shown that if +

 
+$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), +$$ +

 
+ +with \( \gamma_k > 0 \). + +

+For \( \gamma_k \) small enough, then \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \). This means that for a sufficiently small \( \gamma_k \) +we are always moving towards smaller function values, i.e a minimum. +

+ + +
+

More on Steepest descent

+ +

+The previous observation is the basis of the method of steepest +descent, which is also referred to as just gradient descent (GD). One +starts with an initial guess \( \mathbf{x}_0 \) for a minimum of \( F \) and +computes new approximations according to + +

 
+$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), \ \ k \geq 0. +$$ +

 
+ +

+The parameter \( \gamma_k \) is often referred to as the step length or +the learning rate within the context of Machine Learning. +

+ + +
+

The ideal

+ +

+Ideally the sequence \( \{\mathbf{x}_k \}_{k=0} \) converges to a global +minimum of the function \( F \). In general we do not know if we are in a +global or local minimum. In the special case when \( F \) is a convex +function, all local minima are also global minima, so in this case +gradient descent can converge to the global solution. The advantage of +this scheme is that it is conceptually simple and straightforward to +implement. However the method in this form has some severe +limitations: + +

+In machine learing we are often faced with non-convex high dimensional +cost functions with many local minima. Since GD is deterministic we +will get stuck in a local minimum, if the method converges, unless we +have a very good intial guess. This also implies that the scheme is +sensitive to the chosen initial condition. + +

+Note that the gradient is a function of \( \mathbf{x} = +(x_1,\cdots,x_n) \) which makes it expensive to compute numerically. +

+ + +
+

The sensitiveness of the gradient descent

+ +

+The gradient descent method +is sensitive to the choice of learning rate \( \gamma_k \). This is due +to the fact that we are only guaranteed that \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \) for sufficiently small \( \gamma_k \). The problem is to +determine an optimal learning rate. If the learning rate is chosen too +small the method will take a long time to converge and if it is too +large we can experience erratic behavior. + +

+Many of these shortcomings can be alleviated by introducing +randomness. One such method is that of Stochastic Gradient Descent +(SGD), see below. +

+ + +
+

Convex functions

+ +

+Ideally we want our cost/loss function to be convex(concave). + +

+First we give the definition of a convex set: A set \( C \) in +\( \mathbb{R}^n \) is said to be convex if, for all \( x \) and \( y \) in \( C \) and +all \( t \in (0,1) \) , the point \( (1 − t)x + ty \) also belongs to +C. Geometrically this means that every point on the line segment +connecting \( x \) and \( y \) is in \( C \) as discussed below. + +

+The convex subsets of \( \mathbb{R} \) are the intervals of +\( \mathbb{R} \). Examples of convex sets of \( \mathbb{R}^2 \) are the +regular polygons (triangles, rectangles, pentagons, etc...). +

+ + +
+

Convex function

+ +

+Convex function: Let \( X \subset \mathbb{R}^n \) be a convex set. Assume that the function \( f: X \rightarrow \mathbb{R} \) is continuous, then \( f \) is said to be convex if

 
+$$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ +

 
for all \( x_1, x_2 \in X \) and for all \( t \in [0,1] \). If \( \leq \) is replaced with a strict inequaltiy in the definition, we demand \( x_1 \neq x_2 \) and \( t\in(0,1) \) then \( f \) is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting \( f(x_1) \) and \( f(x_2) \), the value of the function on the interval \( [x_1,x_2] \) is always below the line as illustrated below. +

+ + +
+

Conditions on convex functions

+ +

+In the following we state first and second-order conditions which +ensures convexity of a function \( f \). We write \( D_f \) to denote the +domain of \( f \), i.e the subset of \( R^n \) where \( f \) is defined. For more +details and proofs we refer to: S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press. + +

+

+First order condition. +

+Suppose \( f \) is differentiable (i.e \( \nabla f(x) \) is well defined for +all \( x \) in the domain of \( f \)). Then \( f \) is convex if and only if \( D_f \) +is a convex set and

 
+$$f(y) \geq f(x) + \nabla f(x)^T (y-x) $$ +

 
holds +for all \( x,y \in D_f \). This condition means that for a convex function +the first order Taylor expansion (right hand side above) at any point +a global under estimator of the function. To convince yourself you can +make a drawing of \( f(x) = x^2+1 \) and draw the tangent line to \( f(x) \) and +note that it is always below the graph. +

+ +

+

+Second order condition. +

+Assume that \( f \) is twice +differentiable, i.e the Hessian matrix exists at each point in +\( D_f \). Then \( f \) is convex if and only if \( D_f \) is a convex set and its +Hessian is positive semi-definite for all \( x\in D_f \). For a +single-variable function this reduces to \( f''(x) \geq 0 \). Geometrically this means that \( f \) has nonnegative curvature +everywhere. +

+ +

+This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition. +

+ + +
+

More on convex functions

+ +

+The next result is of great importance to us and the reason why we are +going on about convex functions. In machine learning we frequently +have to minimize a loss/cost function in order to find the best +parameters for the model we are considering. + +

+Ideally we want the +global minimum (for high-dimensional models it is hard to know +if we have local or global minimum). However, if the cost/loss function +is convex the following result provides invaluable information: + +

+

+Any minimum is global for convex functions. +

+Consider the problem of finding \( x \in \mathbb{R}^n \) such that \( f(x) \) +is minimal, where \( f \) is convex and differentiable. Then, any point +\( x^* \) that satisfies \( \nabla f(x^*) = 0 \) is a global minimum. +

+ +

+This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum. +

+ + +
+

Some simple problems

+ +
    +

  1. Show that \( f(x)=x^2 \) is convex for \( x \in \mathbb{R} \) using the definition of convexity. Hint: If you re-write the definition, \( f \) is convex if the following holds for all \( x,y \in D_f \) and any \( \lambda \in [0,1] \) $\lambda f(x)+(1-\lambda)f(y)-f(\lambda x + (1-\lambda) y ) \geq 0$.
  2. +

  3. Using the second order condition show that the following functions are convex on the specified domain.
  4. + +
      +

    • \( f(x) = e^x \) is convex for \( x \in \mathbb{R} \).
    • +

    • \( g(x) = -\ln(x) \) is convex for \( x \in (0,\infty) \).
    • +
    +

  5. Let \( f(x) = x^2 \) and \( g(x) = e^x \). Show that \( f(g(x)) \) and \( g(f(x)) \) is convex for \( x \in \mathbb{R} \). Also show that if \( f(x) \) is any convex function than \( h(x) = e^{f(x)} \) is convex.
  6. +

  7. A norm is any function that satisfy the following properties
  8. + +
      +

    • \( f(\alpha x) = |\alpha| f(x) \) for all \( \alpha \in \mathbb{R} \).
    • +

    • \( f(x+y) \leq f(x) + f(y) \)
    • +

    • \( f(x) \leq 0 \) for all \( x \in \mathbb{R}^n \) with equality if and only if \( x = 0 \)
    • +
    +

    +

+

+ +Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this). +

+ + +
+

Revisiting our first homework

+ +

+We will use linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: + +

    +

  1. An analytical solution (recall homework set 1).
  2. +

  3. The gradient can be computed analytically.
  4. +

  5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
  6. +
+

+ +We revisit the example from homework set 1 where we had +

 
+$$ +y_i = 5x_i^2 + 0.1\xi_i, \ i=1,\cdots,100 +$$ +

 
+ +with \( x_i \in [0,1] \) chosen randomly with a uniform distribution. Additionally \( \xi_i \) represents stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +

 
+$$ +h_\beta(x) = \hat{y} = \beta_0 + \beta_1 x, +$$ +

 
+ +such that +

 
+$$ +\hat{y}_i = \beta_0 + \beta_1 x_i. +$$ +

 
+

+ + +
+

Gradient descent example

+ +

+Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\hat{y}} = (\hat{y}_1,\cdots,\hat{y}_n)^T \) and \( \beta = (\beta_0, \beta_1)^T \) + +

+It is convenient to write \( \mathbf{\hat{y}} = X\beta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by +

 
+$$ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +$$ +

 
+ +The loss function is given by +

 
+$$ +C(\beta) = ||X\beta-\mathbf{y}||^2 = ||X\beta||^2 - 2 \mathbf{y}^T X\beta + ||\mathbf{y}||^2 = \sum_{i=1}^{100} (\beta_0 + \beta_1 x_i)^2 - 2 y_i (\beta_0 + \beta_1 x_i) + y_i^2 +$$ +

 
+ +and we want to find \( \beta \) such that \( C(\beta) \) is minimized. +

+ + +
+

The derivative of the cost/loss function

+ +

+Computing \( \partial C(\beta) / \partial \beta_0 \) and \( \partial C(\beta) / \partial \beta_1 \) we can show that the gradient can be written as +

 
+$$ +\nabla_{\beta} C(\beta) = (\partial C(\beta) / \partial \beta_0, \partial C(\beta) / \partial \beta_1)^T = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = 2X^T(X\beta - \mathbf{y}), +$$ +

 
+ +where \( X \) is the design matrix defined above. +

+ + +
+

The Hessian matrix

+The Hessian matrix of \( C(\beta) \) is given by +

 
+$$ +\hat{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\beta)}{\partial \beta_0^2} & \frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} \\ +\frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} & \frac{\partial^2 C(\beta)}{\partial \beta_1^2} & \\ +\end{bmatrix} = 2X^T X. +$$ +

 
+ +This result implies that \( C(\beta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite. +

+ + +
+

Simple program

+ +

+We can now write a program that minimizes \( C(\beta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to +

 
+$$ +\beta_{k+1} = \beta_k - \gamma \nabla_\beta C(\beta_k), \ k=0,1,\cdots +$$ +

 
+ +

+We can use the expression we computed for the gradient and let use a +\( \beta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\beta C(\beta_k) || \leq \epsilon = 10^{-8} \). + +

+And finally we can compare our solution for \( \beta \) with the analytic result given by +\( \beta= (X^TX)^{-1} X^T \mathbf{y} \). +

+ + +
+

Gradient Descent Example

+ +

+Here our simple example +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 1000
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T.dot(xb.dot(beta)-y)
+    beta -= eta*gradients
+
+print(beta)
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(beta)
+ypredict2 = xbnew.dot(beta_linreg)
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example')
+plt.show()
+
+
+ + +
+

And a corresponding example using scikit-learn

+ +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+x = 2*np.random.rand(100,1)
+y = 4+3*x+np.random.randn(100,1)
+
+xb = np.c_[np.ones((100,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print(sgdreg.intercept_, sgdreg.coef_)
+
+
+ + +
+

Gradient descent and Ridge

+ +

+We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \beta \), +

 
+$$ +C_{\text{ridge}}(\beta) = ||X\beta -\mathbf{y}||^2 + \lambda ||\beta||^2, \ \lambda \geq 0. +$$ +

 
+ +

+In order to minimize \( C_{\text{ridge}}(\beta) \) using GD we only have adjust the gradient as follows +

 
+$$ +\nabla_\beta C_{\text{ridge}}(\beta) = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \beta_0 \\ \beta_1\end{bmatrix} = 2 (X^T(X\beta - \mathbf{y})+\lambda \beta). +$$ +

 
+ +

+We can easily extend our program to minimize \( C_{\text{ridge}}(\beta) \) using gradient descent and compare with the analytical solution given by +

 
+$$ +\beta_{\text{ridge}} = \left(X^T X + \lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +$$ +

 
+

+ + +
+

Program example for gradient descent with Ridge Regression

+

+ + +

from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+XT_X = xb.T @ xb
+
+#Ridge parameter lambda
+lmbda  = 0.001
+Id = lmbda* np.eye(XT_X.shape[0])
+
+beta_linreg = np.linalg.inv(XT_X+Id) @ xb.T @ y
+print(beta_linreg)
+# Start plain gradient descent
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 100
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ (xb @ (beta)-y)+2*lmbda*beta
+    beta -= eta*gradients
+
+print(beta)
+ypredict = xb @ beta
+ypredict2 = xb @ beta_linreg
+plt.plot(x, ypredict, "r-")
+plt.plot(x, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example for Ridge')
+plt.show()
+
+
+ + +
+

Using gradient descent methods, limitations

+ +
    +

  • Gradient descent (GD) finds local minima of our function. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our energy function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.
  • +

  • GD is sensitive to initial conditions. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.
  • +

  • Gradients are computationally expensive to calculate for large datasets. In many cases in statistics and ML, the energy function is a sum of terms, with one term for each data point. For example, in linear regression, \( E \propto \sum_{i=1}^n (y_i - \mathbf{w}^T\cdot\mathbf{x}_i)^2 \); for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over all \( n \) data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called "mini batches". This has the added benefit of introducing stochasticity into our algorithm.
  • +

  • GD is very sensitive to choices of learning rates. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would adaptively choose the learning rates to match the landscape.
  • +

  • GD treats all directions in parameter space uniformly. Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive.
  • +

  • GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.
  • +
+
+ + +
+

Friday September 25

+
+ + +
+

Stochastic Gradient Descent

+ +

+Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. + +

+The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +

 
+$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ +

 
+

+ + +
+

Computation of gradients

+ +

+This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +

 
+$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ +

 
+ +

+Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). +

+ + +
+

SGD example

+As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). + +

+The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +

 
+$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ +

 
+

+ + +
+

The gradient step

+ +

+Thus a gradient descent step now looks like +

 
+$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ +

 
+ +

+where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. +

+ + +
+

Simple example code

+ +

+ + +

import numpy as np 
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 10 #number of epochs
+
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for 
+        j += 1
+
+

+Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. +

+ + +
+

When do we stop?

+ +

+A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. +

+ + +
+

Slightly different approach

+ +

+Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. + +

+As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function

 
+$$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ +

 
goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \). + +

+In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. + +

+ + +

import numpy as np 
+
+def step_length(t,t0,t1):
+    return t0/(t+t1)
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 500 #number of epochs
+t0 = 1.0
+t1 = 10
+
+gamma_j = t0/t1
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for beta
+        t = epoch*m+i
+        gamma_j = step_length(t,t0,t1)
+        j += 1
+
+print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
+
+
+ + +
+

Program for stochastic gradient

+ +

+ + +

# Importing various packages
+from math import exp, sqrt
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print("Own inversion")
+print(theta_linreg)
+sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print("sgdreg from scikit")
+print(sgdreg.intercept_, sgdreg.coef_)
+
+
+theta = np.random.randn(2,1)
+eta = 0.1
+Niterations = 1000
+
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ ((xb @ theta)-y)
+    theta -= eta*gradients
+print("theta frm own gd")
+print(theta)
+
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(theta)
+ypredict2 = xbnew.dot(theta_linreg)
+
+
+n_epochs = 50
+t0, t1 = 5, 50
+def learning_schedule(t):
+    return t0/(t+t1)
+
+theta = np.random.randn(2,1)
+
+for epoch in range(n_epochs):
+    for i in range(m):
+        random_index = np.random.randint(m)
+        xi = xb[random_index:random_index+1]
+        yi = y[random_index:random_index+1]
+        gradients = 2 * xi.T @ ((xi @ theta)-yi)
+        eta = learning_schedule(epoch*m+i)
+        theta = theta - eta*gradients
+print("theta from own sdg")
+print(theta)
+
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Random numbers ')
+plt.show()
+
+

+Challenge: try to write a similar code for a Logistic Regression case. +

+ + +
+

Momentum based GD

+ +

+The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows + +

 
+$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\tag{2} +\end{align} +$$ +

 
+ +

+where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is + +

 
+$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ +

 
+ +where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \). +

+ + +
+

More on momentum based approaches

+ +

+Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by + +

 
+$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ +

 
+ +

+We can discretize this equation in the usual way to get + +

 
+$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ +

 
+ +

+Rearranging this equation, we can rewrite this as + +

 
+$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ +

 
+

+ + +
+

Momentum parameter

+ +

+Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: + +

 
+$$ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +$$ +

 
+ +

+Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). + +

+Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. + +

+These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). + +

+In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule + +

 
+$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\tag{3} +\end{align} +$$ +

 
+ +

+One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \). +

+ + +
+

Second moment of the gradient

+ +

+In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. + +

+Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and +ADAM. +

+ + +
+

RMS prop

+ +

+In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given by + +

 
+$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{4}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ +

 
+ +

+where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. +

+ + +
+

ADAM optimizer

+ +

+A related algorithm is the ADAM optimizer. In ADAM, we keep a running +average of both the first and second moment of the gradient and use +this information to adaptively change the learning rate for different +parameters. In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) + +

 
+$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\tag{5}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\hat{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\hat{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \hat{\mathbf{m}}_t \over \sqrt{\hat{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\tag{6} +\end{align} +$$ +

 
+ +

+where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. + +

+Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \hat{\mathbf{s}}_t - +(\hat{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by + +

 
+$$ +\Delta \theta_{t+1}= -\eta_t { \hat{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ +

 
+

+ + +
+

Practical tips

+ +
    +

  • Randomize the data when making mini-batches. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.
  • +

  • Transform your inputs. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the energy matrix is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.
  • +

  • Monitor the out-of-sample performance. Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This early stopping significantly improves performance in many settings.
  • +

  • Adaptive optimization methods don't always have good generalization. Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.
  • +
+

+ +Geron's text, see chapter 11, has several interesting discussions. +

+ + +
+

Automatic differentiation

+ +

+Automatic differentiation (AD), +also called algorithmic +differentiation or computational differentiation,is a set of +techniques to numerically evaluate the derivative of a function +specified by a computer program. AD exploits the fact that every +computer program, no matter how complicated, executes a sequence of +elementary arithmetic operations (addition, subtraction, +multiplication, division, etc.) and elementary functions (exp, log, +sin, cos, etc.). By applying the chain rule repeatedly to these +operations, derivatives of arbitrary order can be computed +automatically, accurately to working precision, and using at most a +small constant factor more arithmetic operations than the original +program. + +

+Automatic differentiation is neither: + +

    +

  • Symbolic differentiation, nor
  • +

  • Numerical differentiation (the method of finite differences).
  • +
+

+ +Symbolic differentiation can lead to inefficient code and faces the +difficulty of converting a computer program into a single expression, +while numerical differentiation can introduce round-off errors in the +discretization process and cancellation + +

+Python has tools for so-called automatic differentiation. +Consider the following example +

 
+$$ +f(x) = \sin\left(2\pi x + x^2\right) +$$ +

 
+ +which has the following derivative +

 
+$$ +f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) +$$ +

 
+ +Using autograd we have + +

+ + +

import autograd.numpy as np
+
+# To do elementwise differentiation:
+from autograd import elementwise_grad as egrad 
+
+# To plot:
+import matplotlib.pyplot as plt 
+
+
+def f(x):
+    return np.sin(2*np.pi*x + x**2)
+
+def f_grad_analytic(x):
+    return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
+
+# Do the comparison:
+x = np.linspace(0,1,1000)
+
+f_grad = egrad(f)
+
+computed = f_grad(x)
+analytic = f_grad_analytic(x)
+
+plt.title('Derivative computed from Autograd compared with the analytical derivative')
+plt.plot(x,computed,label='autograd')
+plt.plot(x,analytic,label='analytic')
+
+plt.xlabel('x')
+plt.ylabel('y')
+plt.legend()
+
+plt.show()
+
+print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
+
+
+ + +
+

Using autograd

+ +

+Here we +experiment with what kind of functions Autograd is capable +of finding the gradient of. The following Python functions are just +meant to illustrate what Autograd can do, but please feel free to +experiment with other, possibly more complicated, functions as well. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f1(x):
+    return x**3 + 1
+
+f1_grad = grad(f1)
+
+# Remember to send in float as argument to the computed gradient from Autograd!
+a = 1.0
+
+# See the evaluated gradient at a using autograd:
+print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a)))
+
+# Compare with the analytical derivative, that is f1'(x) = 3*x**2 
+grad_analytical = 3*a**2
+print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
+
+
+ + +
+

Autograd with more complicated functions

+ +

+To differentiate with respect to two (or more) arguments of a Python +function, Autograd need to know at which variable the function if +being differentiated with respect to. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f2(x1,x2):
+    return 3*x1**3 + x2*(x1 - 5) + 1
+
+# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1
+f2_grad_x1 = grad(f2,0)
+
+# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad
+f2_grad_x2 = grad(f2,1)
+
+x1 = 1.0
+x2 = 3.0 
+
+print("Evaluating at x1 = %g, x2 = %g"%(x1,x2))
+print("-"*30)
+
+# Compare with the analytical derivatives:
+
+# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:
+f2_grad_x1_analytical = 9*x1**2 + x2
+
+# Derivative of f2 w.r.t x2 is: x1 - 5:
+f2_grad_x2_analytical = x1 - 5
+
+# See the evaluated derivations:
+print("The derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+
+print()
+
+print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+
+

+Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. +

+ + +
+

More complicated functions using the elements of their arguments directly

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f3(x): # Assumes x is an array of length 5 or higher
+    return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
+
+f3_grad = grad(f3)
+
+x = np.linspace(0,4,5)
+
+# Print the computed gradient:
+print("The computed gradient of f3 is: ", f3_grad(x))
+
+# The analytical gradient is: (2, 3, 5, 7, 22*x[4])
+f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])
+
+# Print the analytical gradient:
+print("The analytical gradient of f3 is: ", f3_grad_analytical)
+
+

+Note that in this case, when sending an array as input argument, the +output from Autograd is another array. This is the true gradient of +the function, as opposed to the function in the previous example. By +using arrays to represent the variables, the output from Autograd +might be easier to work with, as the output is closer to what one +could expect form a gradient-evaluting function. +

+ + +
+

Functions using mathematical functions from Numpy

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f4(x):
+    return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
+
+f4_grad = grad(f4)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x)))
+
+# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi
+f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi
+
+# Print the analytical gradient:
+print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
+
+
+ + +
+

More autograd

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f5(x):
+    if x >= 0:
+        return x**2
+    else:
+        return -3*x + 1
+
+f5_grad = grad(f5)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
+
+
+ + +
+

And with loops

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f6_for(x):
+    val = 0
+    for i in range(10):
+        val = val + x**i
+    return val
+
+def f6_while(x):
+    val = 0
+    i = 0
+    while i < 10:
+        val = val + x**i
+        i = i + 1
+    return val
+
+f6_for_grad = grad(f6_for)
+f6_while_grad = grad(f6_while)
+
+x = 0.5
+
+# Print the computed derivaties of f6_for and f6_while
+print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
+print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
+
+

+ + +

import autograd.numpy as np
+from autograd import grad
+# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
+# The analytical derivative is: sum(i*x**(i-1)) 
+f6_grad_analytical = 0
+for i in range(10):
+    f6_grad_analytical += i*x**(i-1)
+
+print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
+
+
+ + +
+

Using recursion

+

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f7(n): # Assume that n is an integer
+    if n == 1 or n == 0:
+        return 1
+    else:
+        return n*f7(n-1)
+
+f7_grad = grad(f7)
+
+n = 2.0
+
+print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n)))
+
+# The function f7 is an implementation of the factorial of n.
+# By using the product rule, one can find that the derivative is:
+
+f7_grad_analytical = 0
+for i in range(int(n)-1):
+    tmp = 1
+    for k in range(int(n)-1):
+        if k != i:
+            tmp *= (n - k)
+    f7_grad_analytical += tmp
+
+print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
+
+

+Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. +

+ + +
+

Unsupported functions

+Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. + +

+Assigning a value to the variable being differentiated with respect to +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f8(x): # Assume x is an array
+    x[2] = 3
+    return x*2
+
+f8_grad = grad(f8)
+
+x = 8.4
+
+print("The derivative of f8 is:",f8_grad(x))
+
+

+Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. +

+ + +
+

The syntax a.dot(b) when finding the dot product

+

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9(a): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return a.dot(b)
+
+f9_grad = grad(f9)
+
+x = np.array([1.0,0.0])
+
+print("The derivative of f9 is:",f9_grad(x))
+
+

+Here we are told that the 'dot' function does not belong to Autograd's +version of a Numpy array. To overcome this, an alternative syntax +which also computed the dot product can be used: + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9_alternative(x): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2
+
+f9_alternative_grad = grad(f9_alternative)
+
+x = np.array([3.0,0.0])
+
+print("The gradient of f9 is:",f9_alternative_grad(x))
+
+# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
+# w.r.t x is (b_1, b_2).
+
+
+ + +
+

Recommended to avoid

+The documentation recommends to avoid inplace operations such as +

+ + +

a += b
+a -= b
+a*= b
+a /=b
+
+
+ + +
+

Standard steepest descent

+ +

+Before we proceed, we would like to discuss the approach called the +standard Steepest descent, which again leads to us having to be able +to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG). + +

+The success of the CG method +for finding solutions of non-linear problems is based on the theory +of conjugate gradients for linear systems of equations. It belongs to +the class of iterative methods for solving problems from linear +algebra of the type +

 
+$$ +\begin{equation*} +\hat{A}\hat{x} = \hat{b}. +\end{equation*} +$$ +

 
+ +

+In the iterative process we end up with a problem like + +

 
+$$ +\begin{equation*} + \hat{r}= \hat{b}-\hat{A}\hat{x}, +\end{equation*} +$$ +

 
+ +where \( \hat{r} \) is the so-called residual or error in the iterative process. + +

+When we have found the exact solution, \( \hat{r}=0 \). +

+ + +
+

Gradient method

+ +

+The residual is zero when we reach the minimum of the quadratic equation +

 
+$$ +\begin{equation*} + P(\hat{x})=\frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T\hat{b}, +\end{equation*} +$$ +

 
+ +

+with the constraint that the matrix \( \hat{A} \) is positive definite and +symmetric. This defines also the Hessian and we want it to be positive definite. +

+ + +
+

Steepest descent method

+ +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +

 
+$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ +

 
+ +or consider the system +

 
+$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ +

 
+ +instead. +

+ + +
+

Steepest descent method

+
+ +

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +

 
+$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ +

 
+ +This suggests taking the first basis vector \( \hat{r}_1 \) (see below for definition) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +

 
+$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ +

 
+ +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). + + +

+
+ + +
+

Final expressions

+
+ +

+We can compute the residual iteratively as +

 
+$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ +

 
+ +which equals +

 
+$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{r}_k), + \end{equation*} +$$ +

 
+ +or +

 
+$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{r}_k, + \end{equation*} +$$ +

 
+ +which gives + +

 
+$$ +\alpha_k = \frac{\hat{r}_k^T\hat{r}_k}{\hat{r}_k^T\hat{A}\hat{r}_k} +$$ +

 
+ +leading to the iterative scheme +

 
+$$ +\begin{equation*} +\hat{x}_{k+1}=\hat{x}_k-\alpha_k\hat{r}_{k}, + \end{equation*} +$$ +

 
+

+
+ + +
+

Code examples for steepest descent

+
+ + +
+

Simple codes for steepest descent and conjugate gradient using a \( 2\times 2 \) matrix, in c++, Python code to come

+
+ +

+ + +

#include <cmath>
+#include <iostream>
+#include <fstream>
+#include <iomanip>
+#include "vectormatrixclass.h"
+using namespace  std;
+//   Main function begins here
+int main(int  argc, char * argv[]){
+  int dim = 2;
+  Vector x(dim),xsd(dim), b(dim),x0(dim);
+  Matrix A(dim,dim);
+
+  // Set our initial guess
+  x0(0) = x0(1) = 0;
+  // Set the matrix
+  A(0,0) =  3;    A(1,0) =  2;   A(0,1) =  2;   A(1,1) =  6;
+  b(0) = 2; b(1) = -8;
+  cout << "The Matrix A that we are using: " << endl;
+  A.Print();
+  cout << endl;
+  xsd = SteepestDescent(A,b,x0);
+  cout << "The approximate solution using Steepest Descent is: " << endl;
+  xsd.Print();
+  cout << endl;
+}
+
+ +
+
+ + +
+

The routine for the steepest descent method

+
+ +

+ + +

Vector SteepestDescent(Matrix A, Vector b, Vector x0){
+  int IterMax, i;
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),f(dim),z(dim);
+  double c,alpha,d;
+  IterMax = 30;
+  x = x0;
+  r = A*x-b;
+  i = 0;
+  while (i <= IterMax){
+    z = A*r;
+    c = dot(r,r);
+    alpha = c/dot(r,z);
+    x = x - alpha*r;
+    r =  A*x-b;
+    if(sqrt(dot(r,r)) < tolerance) break;
+    i++;
+  }
+  return x;
+}
+
+ +
+
+ + +
+

Steepest descent example

+ +

+ + +

import numpy as np
+import numpy.linalg as la
+
+import scipy.optimize as sopt
+
+import matplotlib.pyplot as pt
+from mpl_toolkits.mplot3d import axes3d
+
+def f(x):
+    return 0.5*x[0]**2 + 2.5*x[1]**2
+
+def df(x):
+    return np.array([x[0], 5*x[1]])
+
+fig = pt.figure()
+ax = fig.gca(projection="3d")
+
+xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
+fmesh = f(np.array([xmesh, ymesh]))
+ax.plot_surface(xmesh, ymesh, fmesh)
+
+

+And then as countor plot +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh)
+guesses = [np.array([2, 2./5])]
+
+

+Find guesses +

+ + +

x = guesses[-1]
+s = -df(x)
+
+

+Run it! +

+ + +

def f1d(alpha):
+    return f(x + alpha*s)
+
+alpha_opt = sopt.golden(f1d)
+next_guess = x + alpha_opt * s
+guesses.append(next_guess)
+print(next_guess)
+
+

+What happened? +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh, 50)
+it_array = np.array(guesses)
+pt.plot(it_array.T[0], it_array.T[1], "x-")
+
+
+ + +
+

Conjugate gradient method

+
+ +

+In the CG method we define so-called conjugate directions and two vectors +\( \hat{s} \) and \( \hat{t} \) +are said to be +conjugate if +

 
+$$ +\begin{equation*} +\hat{s}^T\hat{A}\hat{t}= 0. +\end{equation*} +$$ +

 
+ +The philosophy of the CG method is to perform searches in various conjugate directions +of our vectors \( \hat{x}_i \) obeying the above criterion, namely +

 
+$$ +\begin{equation*} +\hat{x}_i^T\hat{A}\hat{x}_j= 0. +\end{equation*} +$$ +

 
+ +Two vectors are conjugate if they are orthogonal with respect to +this inner product. Being conjugate is a symmetric relation: if \( \hat{s} \) is conjugate to \( \hat{t} \), then \( \hat{t} \) is conjugate to \( \hat{s} \). +

+
+ + +
+

Conjugate gradient method

+
+ +

+An example is given by the eigenvectors of the matrix +

 
+$$ +\begin{equation*} +\hat{v}_i^T\hat{A}\hat{v}_j= \lambda\hat{v}_i^T\hat{v}_j, +\end{equation*} +$$ +

 
+ +which is zero unless \( i=j \). +

+
+ + +
+

Conjugate gradient method

+
+ +

+Assume now that we have a symmetric positive-definite matrix \( \hat{A} \) of size +\( n\times n \). At each iteration \( i+1 \) we obtain the conjugate direction of a vector +

 
+$$ +\begin{equation*} +\hat{x}_{i+1}=\hat{x}_{i}+\alpha_i\hat{p}_{i}. +\end{equation*} +$$ +

 
+ +We assume that \( \hat{p}_{i} \) is a sequence of \( n \) mutually conjugate directions. +Then the \( \hat{p}_{i} \) form a basis of \( R^n \) and we can expand the solution +$ \hat{A}\hat{x} = \hat{b}$ in this basis, namely + +

 
+$$ +\begin{equation*} + \hat{x} = \sum^{n}_{i=1} \alpha_i \hat{p}_i. +\end{equation*} +$$ +

 
+

+
+ + +
+

Conjugate gradient method

+
+ +

+The coefficients are given by +

 
+$$ +\begin{equation*} + \mathbf{A}\mathbf{x} = \sum^{n}_{i=1} \alpha_i \mathbf{A} \mathbf{p}_i = \mathbf{b}. +\end{equation*} +$$ +

 
+ +Multiplying with \( \hat{p}_k^T \) from the left gives + +

 
+$$ +\begin{equation*} + \hat{p}_k^T \hat{A}\hat{x} = \sum^{n}_{i=1} \alpha_i\hat{p}_k^T \hat{A}\hat{p}_i= \hat{p}_k^T \hat{b}, +\end{equation*} +$$ +

 
+ +and we can define the coefficients \( \alpha_k \) as + +

 
+$$ +\begin{equation*} + \alpha_k = \frac{\hat{p}_k^T \hat{b}}{\hat{p}_k^T \hat{A} \hat{p}_k} +\end{equation*} +$$ +

 
+

+
+ + +
+

Conjugate gradient method and iterations

+
+ +

+If we choose the conjugate vectors \( \hat{p}_k \) carefully, +then we may not need all of them to obtain a good approximation to the solution +\( \hat{x} \). +We want to regard the conjugate gradient method as an iterative method. +This will us to solve systems where \( n \) is so large that the direct +method would take too much time. + +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +

 
+$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ +

 
+ +or consider the system +

 
+$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ +

 
+ +instead. +

+
+ + +
+

Conjugate gradient method

+
+ +

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +

 
+$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ +

 
+ +This suggests taking the first basis vector \( \hat{p}_1 \) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +

 
+$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ +

 
+ +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). +The other vectors in the basis will be conjugate to the gradient, +hence the name conjugate gradient method. +

+
+ + +
+

Conjugate gradient method

+
+ +

+Let \( \hat{r}_k \) be the residual at the \( k \)-th step: +

 
+$$ +\begin{equation*} +\hat{r}_k=\hat{b}-\hat{A}\hat{x}_k. +\end{equation*} +$$ +

 
+ +Note that \( \hat{r}_k \) is the negative gradient of \( f \) at +\( \hat{x}=\hat{x}_k \), +so the gradient descent method would be to move in the direction \( \hat{r}_k \). +Here, we insist that the directions \( \hat{p}_k \) are conjugate to each other, +so we take the direction closest to the gradient \( \hat{r}_k \) +under the conjugacy constraint. +This gives the following expression +

 
+$$ +\begin{equation*} +\hat{p}_{k+1}=\hat{r}_k-\frac{\hat{p}_k^T \hat{A}\hat{r}_k}{\hat{p}_k^T\hat{A}\hat{p}_k} \hat{p}_k. +\end{equation*} +$$ +

 
+

+
+ + +
+

Conjugate gradient method

+
+ +

+We can also compute the residual iteratively as +

 
+$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ +

 
+ +which equals +

 
+$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{p}_k), + \end{equation*} +$$ +

 
+ +or +

 
+$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{p}_k, + \end{equation*} +$$ +

 
+ +which gives + +

 
+$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{r}_k-\hat{A}\hat{p}_{k}, + \end{equation*} +$$ +

 
+

+
+ + +
+

Simple implementation of the Conjugate gradient algorithm

+
+ +

+ + +

  Vector ConjugateGradient(Matrix A, Vector b, Vector x0){
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),r(dim),v(dim),z(dim);
+  double c,t,d;
+
+  x = x0;
+  r = b - A*x;
+  v = r;
+  c = dot(r,r);
+  int i = 0; IterMax = dim;
+  while(i <= IterMax){
+    z = A*v;
+    t = c/dot(v,z);
+    x = x + t*v;
+    r = r - t*z;
+    d = dot(r,r);
+    if(sqrt(d) < tolerance)
+      break;
+    v = r + (d/c)*v;
+    c = d;  i++;
+  }
+  return x;
+} 
+
+ +
+
+ + +
+

Broyden–Fletcher–Goldfarb–Shanno algorithm

+
+ +

+The optimization problem is to minimize \( f(\mathbf {x} ) \) where \( \mathbf {x} \) is a vector in \( R^{n} \), and \( f \) is a differentiable scalar function. There are no constraints on the values that \( \mathbf {x} \) can take. + +

+The algorithm begins at an initial estimate for the optimal value \( \mathbf {x}_{0} \) and proceeds iteratively to get a better estimate at each stage. + +

+The search direction \( p_k \) at stage \( k \) is given by the solution of the analogue of the Newton equation +

 
+$$ +B_{k}\mathbf {p} _{k}=-\nabla f(\mathbf {x}_{k}), +$$ +

 
+ +

+where \( B_{k} \) is an approximation to the Hessian matrix, which is +updated iteratively at each stage, and \( \nabla f(\mathbf {x} _{k}) \) +is the gradient of the function +evaluated at \( x_k \). +A line search in the direction \( p_k \) is then used to +find the next point \( x_{k+1} \) by minimising +

 
+$$ +f(\mathbf {x}_{k}+\alpha \mathbf {p}_{k}), +$$ +

 
+ +over the scalar \( \alpha > 0 \). + + +

+
+ + + +
+
+ + + + + + + + + + + + diff --git a/doc/pub/week39/html/week39-solarized.html b/doc/pub/week39/html/week39-solarized.html new file mode 100644 index 000000000..164656896 --- /dev/null +++ b/doc/pub/week39/html/week39-solarized.html @@ -0,0 +1,2481 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Week 39: Optimization and Gradient Methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Plan for week 39

+ + + +









+ +

Thursday September 24

+ +

+









+ +

Optimization, the central part of any Machine Learning algortithm

+ +

+Almost every problem in machine learning and data science starts with +a dataset \( X \), a model \( g(\beta) \), which is a function of the +parameters \( \beta \) and a cost function \( C(X, g(\beta)) \) that allows +us to judge how well the model \( g(\beta) \) explains the observations +\( X \). The model is fit by finding the values of \( \beta \) that minimize +the cost function. Ideally we would be able to solve for \( \beta \) +analytically, however this is not possible in general and we must use +some approximative/numerical method to compute the minimum. + +

+









+ +

Revisiting our Logistic Regression case

+ +

+In our discussion on Logistic Regression we studied the +case of +two classes, with \( y_i \) either +\( 0 \) or \( 1 \). Furthermore we assumed also that we have only two +parameters \( \beta \) in our fitting, that is we +defined probabilities + +$$ +\begin{align*} +p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ +p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), +\end{align*} +$$ + +where \( \hat{\beta} \) are the weights we wish to extract from data, in our case \( \beta_0 \) and \( \beta_1 \). + +

+









+ +

The equations to solve

+ +

+Our compact equations used a definition of a vector \( \hat{y} \) with \( n \) +elements \( y_i \), an \( n\times p \) matrix \( \hat{X} \) which contains the +\( x_i \) values and a vector \( \hat{p} \) of fitted probabilities +\( p(y_i\vert x_i,\hat{\beta}) \). We rewrote in a more compact form +the first derivative of the cost function as + +$$ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). +$$ + +

+If we in addition define a diagonal matrix \( \hat{W} \) with elements +\( p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta}) \), we can obtain a compact expression of the second derivative as + +$$ +\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. +$$ + +This defines what is called the Hessian matrix. + +

+









+ +

Solving using Newton-Raphson's method

+ +

+If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. + +

+Our iterative scheme is then given by + +$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T}\right)^{-1}_{\hat{\beta}^{\mathrm{old}}}\times \left(\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}}\right)_{\hat{\beta}^{\mathrm{old}}}, +$$ + +or in matrix form as + +$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\hat{X}^T\hat{W}\hat{X} \right)^{-1}\times \left(-\hat{X}^T(\hat{y}-\hat{p}) \right)_{\hat{\beta}^{\mathrm{old}}}. +$$ + +The right-hand side is computed with the old values of \( \beta \). + +

+If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement. + +

+









+ +

Brief reminder on Newton-Raphson's method

+ +

+Let us quickly remind ourselves how we derive the above method. + +

+Perhaps the most celebrated of all one-dimensional root-finding +routines is Newton's method, also called the Newton-Raphson +method. This method requires the evaluation of both the +function \( f \) and its derivative \( f' \) at arbitrary points. +If you can only calculate the derivative +numerically and/or your function is not of the smooth type, we +normally discourage the use of this method. + +

+









+ +

The equations

+ +

+The Newton-Raphson formula consists geometrically of extending the +tangent line at a current point until it crosses zero, then setting +the next guess to the abscissa of that zero-crossing. The mathematics +behind this method is rather simple. Employing a Taylor expansion for +\( x \) sufficiently close to the solution \( s \), we have + +$$ + f(s)=0=f(x)+(s-x)f'(x)+\frac{(s-x)^2}{2}f''(x) +\dots. + \label{eq:taylornr} +$$ + +

+For small enough values of the function and for well-behaved +functions, the terms beyond linear are unimportant, hence we obtain + +$$ + f(x)+(s-x)f'(x)\approx 0, +$$ + +yielding +$$ + s\approx x-\frac{f(x)}{f'(x)}. +$$ + +

+Having in mind an iterative procedure, it is natural to start iterating with +$$ + x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}. +$$ + +

+









+ +

Simple geometric interpretation

+ +

+The above is Newton-Raphson's method. It has a simple geometric +interpretation, namely \( x_{n+1} \) is the point where the tangent from +\( (x_n,f(x_n)) \) crosses the \( x \)-axis. Close to the solution, +Newton-Raphson converges fast to the desired result. However, if we +are far from a root, where the higher-order terms in the series are +important, the Newton-Raphson formula can give grossly inaccurate +results. For instance, the initial guess for the root might be so far +from the true root as to let the search interval include a local +maximum or minimum of the function. If an iteration places a trial +guess near such a local extremum, so that the first derivative nearly +vanishes, then Newton-Raphson may fail totally + +

+









+ +

Extending to more than one variable

+ +

+Newton's method can be generalized to systems of several non-linear equations +and variables. Consider the case with two equations +$$ + \begin{array}{cc} f_1(x_1,x_2) &=0\\ + f_2(x_1,x_2) &=0,\end{array} +$$ + +which we Taylor expand to obtain + +$$ + \begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1 + \partial f_1/\partial x_1+h_2 + \partial f_1/\partial x_2+\dots\\ + 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1 + \partial f_2/\partial x_1+h_2 + \partial f_2/\partial x_2+\dots + \end{array}. +$$ + +Defining the Jacobian matrix \( {\bf \hat{J}} \) we have +$$ + {\bf \hat{J}}=\left( \begin{array}{cc} + \partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\ + \partial f_2/\partial x_1 &\partial f_2/\partial x_2 + \end{array} \right), +$$ + +we can rephrase Newton's method as +$$ +\left(\begin{array}{c} x_1^{n+1} \\ x_2^{n+1} \end{array} \right)= +\left(\begin{array}{c} x_1^{n} \\ x_2^{n} \end{array} \right)+ +\left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right), +$$ + +where we have defined +$$ + \left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)= + -{\bf \hat{J}}^{-1} + \left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right). +$$ + +We need thus to compute the inverse of the Jacobian matrix and it +is to understand that difficulties may +arise in case \( {\bf \hat{J}} \) is nearly singular. + +

+It is rather straightforward to extend the above scheme to systems of +more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. + +

+









+ +

Steepest descent

+ +

+The basic idea of gradient descent is +that a function \( F(\mathbf{x}) \), +\( \mathbf{x} \equiv (x_1,\cdots,x_n) \), decreases fastest if one goes from \( \bf {x} \) in the +direction of the negative gradient \( -\nabla F(\mathbf{x}) \). + +

+It can be shown that if +$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), +$$ + +with \( \gamma_k > 0 \). + +

+For \( \gamma_k \) small enough, then \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \). This means that for a sufficiently small \( \gamma_k \) +we are always moving towards smaller function values, i.e a minimum. + +

+ + +

More on Steepest descent

+ +

+The previous observation is the basis of the method of steepest +descent, which is also referred to as just gradient descent (GD). One +starts with an initial guess \( \mathbf{x}_0 \) for a minimum of \( F \) and +computes new approximations according to + +$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), \ \ k \geq 0. +$$ + +

+The parameter \( \gamma_k \) is often referred to as the step length or +the learning rate within the context of Machine Learning. + +

+ + +

The ideal

+ +

+Ideally the sequence \( \{\mathbf{x}_k \}_{k=0} \) converges to a global +minimum of the function \( F \). In general we do not know if we are in a +global or local minimum. In the special case when \( F \) is a convex +function, all local minima are also global minima, so in this case +gradient descent can converge to the global solution. The advantage of +this scheme is that it is conceptually simple and straightforward to +implement. However the method in this form has some severe +limitations: + +

+In machine learing we are often faced with non-convex high dimensional +cost functions with many local minima. Since GD is deterministic we +will get stuck in a local minimum, if the method converges, unless we +have a very good intial guess. This also implies that the scheme is +sensitive to the chosen initial condition. + +

+Note that the gradient is a function of \( \mathbf{x} = +(x_1,\cdots,x_n) \) which makes it expensive to compute numerically. + +

+ + +

The sensitiveness of the gradient descent

+ +

+The gradient descent method +is sensitive to the choice of learning rate \( \gamma_k \). This is due +to the fact that we are only guaranteed that \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \) for sufficiently small \( \gamma_k \). The problem is to +determine an optimal learning rate. If the learning rate is chosen too +small the method will take a long time to converge and if it is too +large we can experience erratic behavior. + +

+Many of these shortcomings can be alleviated by introducing +randomness. One such method is that of Stochastic Gradient Descent +(SGD), see below. + +

+ + +

Convex functions

+ +

+Ideally we want our cost/loss function to be convex(concave). + +

+First we give the definition of a convex set: A set \( C \) in +\( \mathbb{R}^n \) is said to be convex if, for all \( x \) and \( y \) in \( C \) and +all \( t \in (0,1) \) , the point \( (1 − t)x + ty \) also belongs to +C. Geometrically this means that every point on the line segment +connecting \( x \) and \( y \) is in \( C \) as discussed below. + +

+The convex subsets of \( \mathbb{R} \) are the intervals of +\( \mathbb{R} \). Examples of convex sets of \( \mathbb{R}^2 \) are the +regular polygons (triangles, rectangles, pentagons, etc...). + +

+









+ +

Convex function

+ +

+Convex function: Let \( X \subset \mathbb{R}^n \) be a convex set. Assume that the function \( f: X \rightarrow \mathbb{R} \) is continuous, then \( f \) is said to be convex if $$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ for all \( x_1, x_2 \in X \) and for all \( t \in [0,1] \). If \( \leq \) is replaced with a strict inequaltiy in the definition, we demand \( x_1 \neq x_2 \) and \( t\in(0,1) \) then \( f \) is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting \( f(x_1) \) and \( f(x_2) \), the value of the function on the interval \( [x_1,x_2] \) is always below the line as illustrated below. + +

+









+ +

Conditions on convex functions

+ +

+In the following we state first and second-order conditions which +ensures convexity of a function \( f \). We write \( D_f \) to denote the +domain of \( f \), i.e the subset of \( R^n \) where \( f \) is defined. For more +details and proofs we refer to: S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press. + +

+

+First order condition. +

+Suppose \( f \) is differentiable (i.e \( \nabla f(x) \) is well defined for +all \( x \) in the domain of \( f \)). Then \( f \) is convex if and only if \( D_f \) +is a convex set and $$f(y) \geq f(x) + \nabla f(x)^T (y-x) $$ holds +for all \( x,y \in D_f \). This condition means that for a convex function +the first order Taylor expansion (right hand side above) at any point +a global under estimator of the function. To convince yourself you can +make a drawing of \( f(x) = x^2+1 \) and draw the tangent line to \( f(x) \) and +note that it is always below the graph. +

+ + +

+

+Second order condition. +

+Assume that \( f \) is twice +differentiable, i.e the Hessian matrix exists at each point in +\( D_f \). Then \( f \) is convex if and only if \( D_f \) is a convex set and its +Hessian is positive semi-definite for all \( x\in D_f \). For a +single-variable function this reduces to \( f''(x) \geq 0 \). Geometrically this means that \( f \) has nonnegative curvature +everywhere. +

+ + +

+This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition. + +

+









+ +

More on convex functions

+ +

+The next result is of great importance to us and the reason why we are +going on about convex functions. In machine learning we frequently +have to minimize a loss/cost function in order to find the best +parameters for the model we are considering. + +

+Ideally we want the +global minimum (for high-dimensional models it is hard to know +if we have local or global minimum). However, if the cost/loss function +is convex the following result provides invaluable information: + +

+

+Any minimum is global for convex functions. +

+Consider the problem of finding \( x \in \mathbb{R}^n \) such that \( f(x) \) +is minimal, where \( f \) is convex and differentiable. Then, any point +\( x^* \) that satisfies \( \nabla f(x^*) = 0 \) is a global minimum. +

+ + +

+This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum. + +

+









+ +

Some simple problems

+ +
    +
  1. Show that \( f(x)=x^2 \) is convex for \( x \in \mathbb{R} \) using the definition of convexity. Hint: If you re-write the definition, \( f \) is convex if the following holds for all \( x,y \in D_f \) and any \( \lambda \in [0,1] \) $\lambda f(x)+(1-\lambda)f(y)-f(\lambda x + (1-\lambda) y ) \geq 0$.
  2. +
  3. Using the second order condition show that the following functions are convex on the specified domain.
  4. + +
      +
    • \( f(x) = e^x \) is convex for \( x \in \mathbb{R} \).
    • +
    • \( g(x) = -\ln(x) \) is convex for \( x \in (0,\infty) \).
    • +
    + +
  5. Let \( f(x) = x^2 \) and \( g(x) = e^x \). Show that \( f(g(x)) \) and \( g(f(x)) \) is convex for \( x \in \mathbb{R} \). Also show that if \( f(x) \) is any convex function than \( h(x) = e^{f(x)} \) is convex.
  6. +
  7. A norm is any function that satisfy the following properties
  8. + +
      +
    • \( f(\alpha x) = |\alpha| f(x) \) for all \( \alpha \in \mathbb{R} \).
    • +
    • \( f(x+y) \leq f(x) + f(y) \)
    • +
    • \( f(x) \leq 0 \) for all \( x \in \mathbb{R}^n \) with equality if and only if \( x = 0 \)
    • +
    + +
+ +Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this). + +

+ + +

Revisiting our first homework

+ +

+We will use linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: + +

    +
  1. An analytical solution (recall homework set 1).
  2. +
  3. The gradient can be computed analytically.
  4. +
  5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
  6. +
+ +We revisit the example from homework set 1 where we had +$$ +y_i = 5x_i^2 + 0.1\xi_i, \ i=1,\cdots,100 +$$ + +with \( x_i \in [0,1] \) chosen randomly with a uniform distribution. Additionally \( \xi_i \) represents stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +$$ +h_\beta(x) = \hat{y} = \beta_0 + \beta_1 x, +$$ + +such that +$$ +\hat{y}_i = \beta_0 + \beta_1 x_i. +$$ + +

+ + +

Gradient descent example

+ +

+Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\hat{y}} = (\hat{y}_1,\cdots,\hat{y}_n)^T \) and \( \beta = (\beta_0, \beta_1)^T \) + +

+It is convenient to write \( \mathbf{\hat{y}} = X\beta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by +$$ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +$$ + +The loss function is given by +$$ +C(\beta) = ||X\beta-\mathbf{y}||^2 = ||X\beta||^2 - 2 \mathbf{y}^T X\beta + ||\mathbf{y}||^2 = \sum_{i=1}^{100} (\beta_0 + \beta_1 x_i)^2 - 2 y_i (\beta_0 + \beta_1 x_i) + y_i^2 +$$ + +and we want to find \( \beta \) such that \( C(\beta) \) is minimized. + +

+









+ +

The derivative of the cost/loss function

+ +

+Computing \( \partial C(\beta) / \partial \beta_0 \) and \( \partial C(\beta) / \partial \beta_1 \) we can show that the gradient can be written as +$$ +\nabla_{\beta} C(\beta) = (\partial C(\beta) / \partial \beta_0, \partial C(\beta) / \partial \beta_1)^T = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = 2X^T(X\beta - \mathbf{y}), +$$ + +where \( X \) is the design matrix defined above. + +

+









+ +

The Hessian matrix

+The Hessian matrix of \( C(\beta) \) is given by +$$ +\hat{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\beta)}{\partial \beta_0^2} & \frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} \\ +\frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} & \frac{\partial^2 C(\beta)}{\partial \beta_1^2} & \\ +\end{bmatrix} = 2X^T X. +$$ + +This result implies that \( C(\beta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite. + +

+









+ +

Simple program

+ +

+We can now write a program that minimizes \( C(\beta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to +$$ +\beta_{k+1} = \beta_k - \gamma \nabla_\beta C(\beta_k), \ k=0,1,\cdots +$$ + +

+We can use the expression we computed for the gradient and let use a +\( \beta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\beta C(\beta_k) || \leq \epsilon = 10^{-8} \). + +

+And finally we can compare our solution for \( \beta \) with the analytic result given by +\( \beta= (X^TX)^{-1} X^T \mathbf{y} \). + +

+









+ +

Gradient Descent Example

+ +

+Here our simple example +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 1000
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T.dot(xb.dot(beta)-y)
+    beta -= eta*gradients
+
+print(beta)
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(beta)
+ypredict2 = xbnew.dot(beta_linreg)
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example')
+plt.show()
+
+

+









+ +

And a corresponding example using scikit-learn

+ +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+x = 2*np.random.rand(100,1)
+y = 4+3*x+np.random.randn(100,1)
+
+xb = np.c_[np.ones((100,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print(sgdreg.intercept_, sgdreg.coef_)
+
+

+ + +

Gradient descent and Ridge

+ +

+We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \beta \), +$$ +C_{\text{ridge}}(\beta) = ||X\beta -\mathbf{y}||^2 + \lambda ||\beta||^2, \ \lambda \geq 0. +$$ + +

+In order to minimize \( C_{\text{ridge}}(\beta) \) using GD we only have adjust the gradient as follows +$$ +\nabla_\beta C_{\text{ridge}}(\beta) = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \beta_0 \\ \beta_1\end{bmatrix} = 2 (X^T(X\beta - \mathbf{y})+\lambda \beta). +$$ + +

+We can easily extend our program to minimize \( C_{\text{ridge}}(\beta) \) using gradient descent and compare with the analytical solution given by +$$ +\beta_{\text{ridge}} = \left(X^T X + \lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +$$ + +

+









+ +

Program example for gradient descent with Ridge Regression

+

+ + +

from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+XT_X = xb.T @ xb
+
+#Ridge parameter lambda
+lmbda  = 0.001
+Id = lmbda* np.eye(XT_X.shape[0])
+
+beta_linreg = np.linalg.inv(XT_X+Id) @ xb.T @ y
+print(beta_linreg)
+# Start plain gradient descent
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 100
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ (xb @ (beta)-y)+2*lmbda*beta
+    beta -= eta*gradients
+
+print(beta)
+ypredict = xb @ beta
+ypredict2 = xb @ beta_linreg
+plt.plot(x, ypredict, "r-")
+plt.plot(x, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example for Ridge')
+plt.show()
+
+

+









+ +

Using gradient descent methods, limitations

+ + + +









+ +

Friday September 25

+ +

+









+ +

Stochastic Gradient Descent

+ +

+Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. + +

+The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

+









+ +

Computation of gradients

+ +

+This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

+Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). + +

+









+ +

SGD example

+As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). + +

+The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ + +

+









+ +

The gradient step

+ +

+Thus a gradient descent step now looks like +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

+where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. + +

+









+ +

Simple example code

+ +

+ + +

import numpy as np 
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 10 #number of epochs
+
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for 
+        j += 1
+
+

+Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. + +

+









+ +

When do we stop?

+ +

+A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. + +

+









+ +

Slightly different approach

+ +

+Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. + +

+As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \). + +

+In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. + +

+ + +

import numpy as np 
+
+def step_length(t,t0,t1):
+    return t0/(t+t1)
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 500 #number of epochs
+t0 = 1.0
+t1 = 10
+
+gamma_j = t0/t1
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for beta
+        t = epoch*m+i
+        gamma_j = step_length(t,t0,t1)
+        j += 1
+
+print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
+
+

+









+ +

Program for stochastic gradient

+ +

+ + +

# Importing various packages
+from math import exp, sqrt
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print("Own inversion")
+print(theta_linreg)
+sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print("sgdreg from scikit")
+print(sgdreg.intercept_, sgdreg.coef_)
+
+
+theta = np.random.randn(2,1)
+eta = 0.1
+Niterations = 1000
+
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ ((xb @ theta)-y)
+    theta -= eta*gradients
+print("theta frm own gd")
+print(theta)
+
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(theta)
+ypredict2 = xbnew.dot(theta_linreg)
+
+
+n_epochs = 50
+t0, t1 = 5, 50
+def learning_schedule(t):
+    return t0/(t+t1)
+
+theta = np.random.randn(2,1)
+
+for epoch in range(n_epochs):
+    for i in range(m):
+        random_index = np.random.randint(m)
+        xi = xb[random_index:random_index+1]
+        yi = y[random_index:random_index+1]
+        gradients = 2 * xi.T @ ((xi @ theta)-yi)
+        eta = learning_schedule(epoch*m+i)
+        theta = theta - eta*gradients
+print("theta from own sdg")
+print(theta)
+
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Random numbers ')
+plt.show()
+
+

+Challenge: try to write a similar code for a Logistic Regression case. + +

+









+ +

Momentum based GD

+ +

+The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\label{_auto1} +\end{align} +$$ + +

+where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is + +$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ + +where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \). + +

+









+ +

More on momentum based approaches

+ +

+Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by + +$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ + +

+We can discretize this equation in the usual way to get + +$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ + +

+Rearranging this equation, we can rewrite this as + +$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ + +

+









+ +

Momentum parameter

+ +

+Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: + +$$ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +$$ + +

+Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). + +

+Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. + +

+These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). + +

+In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\label{_auto2} +\end{align} +$$ + +

+One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \). + +

+









+ +

Second moment of the gradient

+ +

+In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. + +

+Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and +ADAM. + +

+









+ +

RMS prop

+ +

+In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given by + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto3}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ + +

+where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. + +

+









+ +

ADAM optimizer

+ +

+A related algorithm is the ADAM optimizer. In ADAM, we keep a running +average of both the first and second moment of the gradient and use +this information to adaptively change the learning rate for different +parameters. In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto4}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\hat{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\hat{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \hat{\mathbf{m}}_t \over \sqrt{\hat{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\label{_auto5} +\end{align} +$$ + +

+where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. + +

+Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \hat{\mathbf{s}}_t - +(\hat{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by + +$$ +\Delta \theta_{t+1}= -\eta_t { \hat{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ + +

+









+ +

Practical tips

+ + + +Geron's text, see chapter 11, has several interesting discussions. + +

+









+ +

Automatic differentiation

+ +

+Automatic differentiation (AD), +also called algorithmic +differentiation or computational differentiation,is a set of +techniques to numerically evaluate the derivative of a function +specified by a computer program. AD exploits the fact that every +computer program, no matter how complicated, executes a sequence of +elementary arithmetic operations (addition, subtraction, +multiplication, division, etc.) and elementary functions (exp, log, +sin, cos, etc.). By applying the chain rule repeatedly to these +operations, derivatives of arbitrary order can be computed +automatically, accurately to working precision, and using at most a +small constant factor more arithmetic operations than the original +program. + +

+Automatic differentiation is neither: + +

+ +Symbolic differentiation can lead to inefficient code and faces the +difficulty of converting a computer program into a single expression, +while numerical differentiation can introduce round-off errors in the +discretization process and cancellation + +

+Python has tools for so-called automatic differentiation. +Consider the following example +$$ +f(x) = \sin\left(2\pi x + x^2\right) +$$ + +which has the following derivative +$$ +f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) +$$ + +Using autograd we have + +

+ + +

import autograd.numpy as np
+
+# To do elementwise differentiation:
+from autograd import elementwise_grad as egrad 
+
+# To plot:
+import matplotlib.pyplot as plt 
+
+
+def f(x):
+    return np.sin(2*np.pi*x + x**2)
+
+def f_grad_analytic(x):
+    return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
+
+# Do the comparison:
+x = np.linspace(0,1,1000)
+
+f_grad = egrad(f)
+
+computed = f_grad(x)
+analytic = f_grad_analytic(x)
+
+plt.title('Derivative computed from Autograd compared with the analytical derivative')
+plt.plot(x,computed,label='autograd')
+plt.plot(x,analytic,label='analytic')
+
+plt.xlabel('x')
+plt.ylabel('y')
+plt.legend()
+
+plt.show()
+
+print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
+
+

+ + +

Using autograd

+ +

+Here we +experiment with what kind of functions Autograd is capable +of finding the gradient of. The following Python functions are just +meant to illustrate what Autograd can do, but please feel free to +experiment with other, possibly more complicated, functions as well. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f1(x):
+    return x**3 + 1
+
+f1_grad = grad(f1)
+
+# Remember to send in float as argument to the computed gradient from Autograd!
+a = 1.0
+
+# See the evaluated gradient at a using autograd:
+print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a)))
+
+# Compare with the analytical derivative, that is f1'(x) = 3*x**2 
+grad_analytical = 3*a**2
+print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
+
+

+









+ +

Autograd with more complicated functions

+ +

+To differentiate with respect to two (or more) arguments of a Python +function, Autograd need to know at which variable the function if +being differentiated with respect to. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f2(x1,x2):
+    return 3*x1**3 + x2*(x1 - 5) + 1
+
+# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1
+f2_grad_x1 = grad(f2,0)
+
+# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad
+f2_grad_x2 = grad(f2,1)
+
+x1 = 1.0
+x2 = 3.0 
+
+print("Evaluating at x1 = %g, x2 = %g"%(x1,x2))
+print("-"*30)
+
+# Compare with the analytical derivatives:
+
+# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:
+f2_grad_x1_analytical = 9*x1**2 + x2
+
+# Derivative of f2 w.r.t x2 is: x1 - 5:
+f2_grad_x2_analytical = x1 - 5
+
+# See the evaluated derivations:
+print("The derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+
+print()
+
+print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+
+

+Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. + +

+









+ +

More complicated functions using the elements of their arguments directly

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f3(x): # Assumes x is an array of length 5 or higher
+    return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
+
+f3_grad = grad(f3)
+
+x = np.linspace(0,4,5)
+
+# Print the computed gradient:
+print("The computed gradient of f3 is: ", f3_grad(x))
+
+# The analytical gradient is: (2, 3, 5, 7, 22*x[4])
+f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])
+
+# Print the analytical gradient:
+print("The analytical gradient of f3 is: ", f3_grad_analytical)
+
+

+Note that in this case, when sending an array as input argument, the +output from Autograd is another array. This is the true gradient of +the function, as opposed to the function in the previous example. By +using arrays to represent the variables, the output from Autograd +might be easier to work with, as the output is closer to what one +could expect form a gradient-evaluting function. + +

+ + +

Functions using mathematical functions from Numpy

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f4(x):
+    return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
+
+f4_grad = grad(f4)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x)))
+
+# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi
+f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi
+
+# Print the analytical gradient:
+print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
+
+

+









+ +

More autograd

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f5(x):
+    if x >= 0:
+        return x**2
+    else:
+        return -3*x + 1
+
+f5_grad = grad(f5)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
+
+

+









+ +

And with loops

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f6_for(x):
+    val = 0
+    for i in range(10):
+        val = val + x**i
+    return val
+
+def f6_while(x):
+    val = 0
+    i = 0
+    while i < 10:
+        val = val + x**i
+        i = i + 1
+    return val
+
+f6_for_grad = grad(f6_for)
+f6_while_grad = grad(f6_while)
+
+x = 0.5
+
+# Print the computed derivaties of f6_for and f6_while
+print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
+print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
+
+

+ + +

import autograd.numpy as np
+from autograd import grad
+# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
+# The analytical derivative is: sum(i*x**(i-1)) 
+f6_grad_analytical = 0
+for i in range(10):
+    f6_grad_analytical += i*x**(i-1)
+
+print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
+
+

+









+ +

Using recursion

+

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f7(n): # Assume that n is an integer
+    if n == 1 or n == 0:
+        return 1
+    else:
+        return n*f7(n-1)
+
+f7_grad = grad(f7)
+
+n = 2.0
+
+print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n)))
+
+# The function f7 is an implementation of the factorial of n.
+# By using the product rule, one can find that the derivative is:
+
+f7_grad_analytical = 0
+for i in range(int(n)-1):
+    tmp = 1
+    for k in range(int(n)-1):
+        if k != i:
+            tmp *= (n - k)
+    f7_grad_analytical += tmp
+
+print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
+
+

+Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. + +

+









+ +

Unsupported functions

+Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. + +

+Assigning a value to the variable being differentiated with respect to +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f8(x): # Assume x is an array
+    x[2] = 3
+    return x*2
+
+f8_grad = grad(f8)
+
+x = 8.4
+
+print("The derivative of f8 is:",f8_grad(x))
+
+

+Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. + +

+









+ +

The syntax a.dot(b) when finding the dot product

+

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9(a): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return a.dot(b)
+
+f9_grad = grad(f9)
+
+x = np.array([1.0,0.0])
+
+print("The derivative of f9 is:",f9_grad(x))
+
+

+Here we are told that the 'dot' function does not belong to Autograd's +version of a Numpy array. To overcome this, an alternative syntax +which also computed the dot product can be used: + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9_alternative(x): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2
+
+f9_alternative_grad = grad(f9_alternative)
+
+x = np.array([3.0,0.0])
+
+print("The gradient of f9 is:",f9_alternative_grad(x))
+
+# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
+# w.r.t x is (b_1, b_2).
+
+

+









+ +

Recommended to avoid

+The documentation recommends to avoid inplace operations such as +

+ + +

a += b
+a -= b
+a*= b
+a /=b
+
+

+









+ +

Standard steepest descent

+ +

+Before we proceed, we would like to discuss the approach called the +standard Steepest descent, which again leads to us having to be able +to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG). + +

+The success of the CG method +for finding solutions of non-linear problems is based on the theory +of conjugate gradients for linear systems of equations. It belongs to +the class of iterative methods for solving problems from linear +algebra of the type +$$ +\begin{equation*} +\hat{A}\hat{x} = \hat{b}. +\end{equation*} +$$ + +

+In the iterative process we end up with a problem like + +$$ +\begin{equation*} + \hat{r}= \hat{b}-\hat{A}\hat{x}, +\end{equation*} +$$ + +where \( \hat{r} \) is the so-called residual or error in the iterative process. + +

+When we have found the exact solution, \( \hat{r}=0 \). + +

+









+ +

Gradient method

+ +

+The residual is zero when we reach the minimum of the quadratic equation +$$ +\begin{equation*} + P(\hat{x})=\frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T\hat{b}, +\end{equation*} +$$ + +

+with the constraint that the matrix \( \hat{A} \) is positive definite and +symmetric. This defines also the Hessian and we want it to be positive definite. + +

+









+ +

Steepest descent method

+ +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ + +or consider the system +$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ + +instead. + +

+









+ +

Steepest descent method

+
+ +

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ + +This suggests taking the first basis vector \( \hat{r}_1 \) (see below for definition) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ + +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). + + +

+ + +

+









+ +

Final expressions

+
+ +

+We can compute the residual iteratively as +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ + +which equals +$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{r}_k), + \end{equation*} +$$ + +or +$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{r}_k, + \end{equation*} +$$ + +which gives + +$$ +\alpha_k = \frac{\hat{r}_k^T\hat{r}_k}{\hat{r}_k^T\hat{A}\hat{r}_k} +$$ + +leading to the iterative scheme +$$ +\begin{equation*} +\hat{x}_{k+1}=\hat{x}_k-\alpha_k\hat{r}_{k}, + \end{equation*} +$$ +

+ + +

+









+ +

Code examples for steepest descent

+ +

+









+ +

Simple codes for steepest descent and conjugate gradient using a \( 2\times 2 \) matrix, in c++, Python code to come

+
+ +

+

+ + +

#include <cmath>
+#include <iostream>
+#include <fstream>
+#include <iomanip>
+#include "vectormatrixclass.h"
+using namespace  std;
+//   Main function begins here
+int main(int  argc, char * argv[]){
+  int dim = 2;
+  Vector x(dim),xsd(dim), b(dim),x0(dim);
+  Matrix A(dim,dim);
+
+  // Set our initial guess
+  x0(0) = x0(1) = 0;
+  // Set the matrix
+  A(0,0) =  3;    A(1,0) =  2;   A(0,1) =  2;   A(1,1) =  6;
+  b(0) = 2; b(1) = -8;
+  cout << "The Matrix A that we are using: " << endl;
+  A.Print();
+  cout << endl;
+  xsd = SteepestDescent(A,b,x0);
+  cout << "The approximate solution using Steepest Descent is: " << endl;
+  xsd.Print();
+  cout << endl;
+}
+
+ +
+ + +

+









+ +

The routine for the steepest descent method

+
+ +

+

+ + +

Vector SteepestDescent(Matrix A, Vector b, Vector x0){
+  int IterMax, i;
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),f(dim),z(dim);
+  double c,alpha,d;
+  IterMax = 30;
+  x = x0;
+  r = A*x-b;
+  i = 0;
+  while (i <= IterMax){
+    z = A*r;
+    c = dot(r,r);
+    alpha = c/dot(r,z);
+    x = x - alpha*r;
+    r =  A*x-b;
+    if(sqrt(dot(r,r)) < tolerance) break;
+    i++;
+  }
+  return x;
+}
+
+ +
+ + +

+









+ +

Steepest descent example

+ +

+ + +

import numpy as np
+import numpy.linalg as la
+
+import scipy.optimize as sopt
+
+import matplotlib.pyplot as pt
+from mpl_toolkits.mplot3d import axes3d
+
+def f(x):
+    return 0.5*x[0]**2 + 2.5*x[1]**2
+
+def df(x):
+    return np.array([x[0], 5*x[1]])
+
+fig = pt.figure()
+ax = fig.gca(projection="3d")
+
+xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
+fmesh = f(np.array([xmesh, ymesh]))
+ax.plot_surface(xmesh, ymesh, fmesh)
+
+

+And then as countor plot +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh)
+guesses = [np.array([2, 2./5])]
+
+

+Find guesses +

+ + +

x = guesses[-1]
+s = -df(x)
+
+

+Run it! +

+ + +

def f1d(alpha):
+    return f(x + alpha*s)
+
+alpha_opt = sopt.golden(f1d)
+next_guess = x + alpha_opt * s
+guesses.append(next_guess)
+print(next_guess)
+
+

+What happened? +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh, 50)
+it_array = np.array(guesses)
+pt.plot(it_array.T[0], it_array.T[1], "x-")
+
+

+









+ +

Conjugate gradient method

+
+ +

+In the CG method we define so-called conjugate directions and two vectors +\( \hat{s} \) and \( \hat{t} \) +are said to be +conjugate if +$$ +\begin{equation*} +\hat{s}^T\hat{A}\hat{t}= 0. +\end{equation*} +$$ + +The philosophy of the CG method is to perform searches in various conjugate directions +of our vectors \( \hat{x}_i \) obeying the above criterion, namely +$$ +\begin{equation*} +\hat{x}_i^T\hat{A}\hat{x}_j= 0. +\end{equation*} +$$ + +Two vectors are conjugate if they are orthogonal with respect to +this inner product. Being conjugate is a symmetric relation: if \( \hat{s} \) is conjugate to \( \hat{t} \), then \( \hat{t} \) is conjugate to \( \hat{s} \). +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+An example is given by the eigenvectors of the matrix +$$ +\begin{equation*} +\hat{v}_i^T\hat{A}\hat{v}_j= \lambda\hat{v}_i^T\hat{v}_j, +\end{equation*} +$$ + +which is zero unless \( i=j \). +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+Assume now that we have a symmetric positive-definite matrix \( \hat{A} \) of size +\( n\times n \). At each iteration \( i+1 \) we obtain the conjugate direction of a vector +$$ +\begin{equation*} +\hat{x}_{i+1}=\hat{x}_{i}+\alpha_i\hat{p}_{i}. +\end{equation*} +$$ + +We assume that \( \hat{p}_{i} \) is a sequence of \( n \) mutually conjugate directions. +Then the \( \hat{p}_{i} \) form a basis of \( R^n \) and we can expand the solution +$ \hat{A}\hat{x} = \hat{b}$ in this basis, namely + +$$ +\begin{equation*} + \hat{x} = \sum^{n}_{i=1} \alpha_i \hat{p}_i. +\end{equation*} +$$ +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+The coefficients are given by +$$ +\begin{equation*} + \mathbf{A}\mathbf{x} = \sum^{n}_{i=1} \alpha_i \mathbf{A} \mathbf{p}_i = \mathbf{b}. +\end{equation*} +$$ + +Multiplying with \( \hat{p}_k^T \) from the left gives + +$$ +\begin{equation*} + \hat{p}_k^T \hat{A}\hat{x} = \sum^{n}_{i=1} \alpha_i\hat{p}_k^T \hat{A}\hat{p}_i= \hat{p}_k^T \hat{b}, +\end{equation*} +$$ + +and we can define the coefficients \( \alpha_k \) as + +$$ +\begin{equation*} + \alpha_k = \frac{\hat{p}_k^T \hat{b}}{\hat{p}_k^T \hat{A} \hat{p}_k} +\end{equation*} +$$ +

+ + +

+









+ +

Conjugate gradient method and iterations

+
+ +

+ +

+If we choose the conjugate vectors \( \hat{p}_k \) carefully, +then we may not need all of them to obtain a good approximation to the solution +\( \hat{x} \). +We want to regard the conjugate gradient method as an iterative method. +This will us to solve systems where \( n \) is so large that the direct +method would take too much time. + +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ + +or consider the system +$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ + +instead. +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ + +This suggests taking the first basis vector \( \hat{p}_1 \) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ + +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). +The other vectors in the basis will be conjugate to the gradient, +hence the name conjugate gradient method. +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+Let \( \hat{r}_k \) be the residual at the \( k \)-th step: +$$ +\begin{equation*} +\hat{r}_k=\hat{b}-\hat{A}\hat{x}_k. +\end{equation*} +$$ + +Note that \( \hat{r}_k \) is the negative gradient of \( f \) at +\( \hat{x}=\hat{x}_k \), +so the gradient descent method would be to move in the direction \( \hat{r}_k \). +Here, we insist that the directions \( \hat{p}_k \) are conjugate to each other, +so we take the direction closest to the gradient \( \hat{r}_k \) +under the conjugacy constraint. +This gives the following expression +$$ +\begin{equation*} +\hat{p}_{k+1}=\hat{r}_k-\frac{\hat{p}_k^T \hat{A}\hat{r}_k}{\hat{p}_k^T\hat{A}\hat{p}_k} \hat{p}_k. +\end{equation*} +$$ +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+We can also compute the residual iteratively as +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ + +which equals +$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{p}_k), + \end{equation*} +$$ + +or +$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{p}_k, + \end{equation*} +$$ + +which gives + +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{r}_k-\hat{A}\hat{p}_{k}, + \end{equation*} +$$ +

+ + +

+









+ +

Simple implementation of the Conjugate gradient algorithm

+
+ +

+

+ + +

  Vector ConjugateGradient(Matrix A, Vector b, Vector x0){
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),r(dim),v(dim),z(dim);
+  double c,t,d;
+
+  x = x0;
+  r = b - A*x;
+  v = r;
+  c = dot(r,r);
+  int i = 0; IterMax = dim;
+  while(i <= IterMax){
+    z = A*v;
+    t = c/dot(v,z);
+    x = x + t*v;
+    r = r - t*z;
+    d = dot(r,r);
+    if(sqrt(d) < tolerance)
+      break;
+    v = r + (d/c)*v;
+    c = d;  i++;
+  }
+  return x;
+} 
+
+ +
+ + +

+









+ +

Broyden–Fletcher–Goldfarb–Shanno algorithm

+
+ +

+The optimization problem is to minimize \( f(\mathbf {x} ) \) where \( \mathbf {x} \) is a vector in \( R^{n} \), and \( f \) is a differentiable scalar function. There are no constraints on the values that \( \mathbf {x} \) can take. + +

+The algorithm begins at an initial estimate for the optimal value \( \mathbf {x}_{0} \) and proceeds iteratively to get a better estimate at each stage. + +

+The search direction \( p_k \) at stage \( k \) is given by the solution of the analogue of the Newton equation +$$ +B_{k}\mathbf {p} _{k}=-\nabla f(\mathbf {x}_{k}), +$$ + +

+where \( B_{k} \) is an approximation to the Hessian matrix, which is +updated iteratively at each stage, and \( \nabla f(\mathbf {x} _{k}) \) +is the gradient of the function +evaluated at \( x_k \). +A line search in the direction \( p_k \) is then used to +find the next point \( x_{k+1} \) by minimising +$$ +f(\mathbf {x}_{k}+\alpha \mathbf {p}_{k}), +$$ + +over the scalar \( \alpha > 0 \). + + +

+ + +

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week39/html/week39.html b/doc/pub/week39/html/week39.html new file mode 100644 index 000000000..06a81fc70 --- /dev/null +++ b/doc/pub/week39/html/week39.html @@ -0,0 +1,2486 @@ + + + + + + + + +Week 39: Optimization and Gradient Methods + + + + + + + + + + + + + + + + + + + + + + + +

Week 39: Optimization and Gradient Methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Plan for week 39

+ + + +









+ +

Thursday September 24

+ +

+









+ +

Optimization, the central part of any Machine Learning algortithm

+ +

+Almost every problem in machine learning and data science starts with +a dataset \( X \), a model \( g(\beta) \), which is a function of the +parameters \( \beta \) and a cost function \( C(X, g(\beta)) \) that allows +us to judge how well the model \( g(\beta) \) explains the observations +\( X \). The model is fit by finding the values of \( \beta \) that minimize +the cost function. Ideally we would be able to solve for \( \beta \) +analytically, however this is not possible in general and we must use +some approximative/numerical method to compute the minimum. + +

+









+ +

Revisiting our Logistic Regression case

+ +

+In our discussion on Logistic Regression we studied the +case of +two classes, with \( y_i \) either +\( 0 \) or \( 1 \). Furthermore we assumed also that we have only two +parameters \( \beta \) in our fitting, that is we +defined probabilities + +$$ +\begin{align*} +p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ +p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), +\end{align*} +$$ + +where \( \hat{\beta} \) are the weights we wish to extract from data, in our case \( \beta_0 \) and \( \beta_1 \). + +

+









+ +

The equations to solve

+ +

+Our compact equations used a definition of a vector \( \hat{y} \) with \( n \) +elements \( y_i \), an \( n\times p \) matrix \( \hat{X} \) which contains the +\( x_i \) values and a vector \( \hat{p} \) of fitted probabilities +\( p(y_i\vert x_i,\hat{\beta}) \). We rewrote in a more compact form +the first derivative of the cost function as + +$$ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). +$$ + +

+If we in addition define a diagonal matrix \( \hat{W} \) with elements +\( p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta}) \), we can obtain a compact expression of the second derivative as + +$$ +\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. +$$ + +This defines what is called the Hessian matrix. + +

+









+ +

Solving using Newton-Raphson's method

+ +

+If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. + +

+Our iterative scheme is then given by + +$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T}\right)^{-1}_{\hat{\beta}^{\mathrm{old}}}\times \left(\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}}\right)_{\hat{\beta}^{\mathrm{old}}}, +$$ + +or in matrix form as + +$$ +\hat{\beta}^{\mathrm{new}} = \hat{\beta}^{\mathrm{old}}-\left(\hat{X}^T\hat{W}\hat{X} \right)^{-1}\times \left(-\hat{X}^T(\hat{y}-\hat{p}) \right)_{\hat{\beta}^{\mathrm{old}}}. +$$ + +The right-hand side is computed with the old values of \( \beta \). + +

+If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement. + +

+









+ +

Brief reminder on Newton-Raphson's method

+ +

+Let us quickly remind ourselves how we derive the above method. + +

+Perhaps the most celebrated of all one-dimensional root-finding +routines is Newton's method, also called the Newton-Raphson +method. This method requires the evaluation of both the +function \( f \) and its derivative \( f' \) at arbitrary points. +If you can only calculate the derivative +numerically and/or your function is not of the smooth type, we +normally discourage the use of this method. + +

+









+ +

The equations

+ +

+The Newton-Raphson formula consists geometrically of extending the +tangent line at a current point until it crosses zero, then setting +the next guess to the abscissa of that zero-crossing. The mathematics +behind this method is rather simple. Employing a Taylor expansion for +\( x \) sufficiently close to the solution \( s \), we have + +$$ + f(s)=0=f(x)+(s-x)f'(x)+\frac{(s-x)^2}{2}f''(x) +\dots. + \label{eq:taylornr} +$$ + +

+For small enough values of the function and for well-behaved +functions, the terms beyond linear are unimportant, hence we obtain + +$$ + f(x)+(s-x)f'(x)\approx 0, +$$ + +yielding +$$ + s\approx x-\frac{f(x)}{f'(x)}. +$$ + +

+Having in mind an iterative procedure, it is natural to start iterating with +$$ + x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}. +$$ + +

+









+ +

Simple geometric interpretation

+ +

+The above is Newton-Raphson's method. It has a simple geometric +interpretation, namely \( x_{n+1} \) is the point where the tangent from +\( (x_n,f(x_n)) \) crosses the \( x \)-axis. Close to the solution, +Newton-Raphson converges fast to the desired result. However, if we +are far from a root, where the higher-order terms in the series are +important, the Newton-Raphson formula can give grossly inaccurate +results. For instance, the initial guess for the root might be so far +from the true root as to let the search interval include a local +maximum or minimum of the function. If an iteration places a trial +guess near such a local extremum, so that the first derivative nearly +vanishes, then Newton-Raphson may fail totally + +

+









+ +

Extending to more than one variable

+ +

+Newton's method can be generalized to systems of several non-linear equations +and variables. Consider the case with two equations +$$ + \begin{array}{cc} f_1(x_1,x_2) &=0\\ + f_2(x_1,x_2) &=0,\end{array} +$$ + +which we Taylor expand to obtain + +$$ + \begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1 + \partial f_1/\partial x_1+h_2 + \partial f_1/\partial x_2+\dots\\ + 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1 + \partial f_2/\partial x_1+h_2 + \partial f_2/\partial x_2+\dots + \end{array}. +$$ + +Defining the Jacobian matrix \( {\bf \hat{J}} \) we have +$$ + {\bf \hat{J}}=\left( \begin{array}{cc} + \partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\ + \partial f_2/\partial x_1 &\partial f_2/\partial x_2 + \end{array} \right), +$$ + +we can rephrase Newton's method as +$$ +\left(\begin{array}{c} x_1^{n+1} \\ x_2^{n+1} \end{array} \right)= +\left(\begin{array}{c} x_1^{n} \\ x_2^{n} \end{array} \right)+ +\left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right), +$$ + +where we have defined +$$ + \left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)= + -{\bf \hat{J}}^{-1} + \left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right). +$$ + +We need thus to compute the inverse of the Jacobian matrix and it +is to understand that difficulties may +arise in case \( {\bf \hat{J}} \) is nearly singular. + +

+It is rather straightforward to extend the above scheme to systems of +more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. + +

+









+ +

Steepest descent

+ +

+The basic idea of gradient descent is +that a function \( F(\mathbf{x}) \), +\( \mathbf{x} \equiv (x_1,\cdots,x_n) \), decreases fastest if one goes from \( \bf {x} \) in the +direction of the negative gradient \( -\nabla F(\mathbf{x}) \). + +

+It can be shown that if +$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), +$$ + +with \( \gamma_k > 0 \). + +

+For \( \gamma_k \) small enough, then \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \). This means that for a sufficiently small \( \gamma_k \) +we are always moving towards smaller function values, i.e a minimum. + +

+ + +

More on Steepest descent

+ +

+The previous observation is the basis of the method of steepest +descent, which is also referred to as just gradient descent (GD). One +starts with an initial guess \( \mathbf{x}_0 \) for a minimum of \( F \) and +computes new approximations according to + +$$ +\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), \ \ k \geq 0. +$$ + +

+The parameter \( \gamma_k \) is often referred to as the step length or +the learning rate within the context of Machine Learning. + +

+ + +

The ideal

+ +

+Ideally the sequence \( \{\mathbf{x}_k \}_{k=0} \) converges to a global +minimum of the function \( F \). In general we do not know if we are in a +global or local minimum. In the special case when \( F \) is a convex +function, all local minima are also global minima, so in this case +gradient descent can converge to the global solution. The advantage of +this scheme is that it is conceptually simple and straightforward to +implement. However the method in this form has some severe +limitations: + +

+In machine learing we are often faced with non-convex high dimensional +cost functions with many local minima. Since GD is deterministic we +will get stuck in a local minimum, if the method converges, unless we +have a very good intial guess. This also implies that the scheme is +sensitive to the chosen initial condition. + +

+Note that the gradient is a function of \( \mathbf{x} = +(x_1,\cdots,x_n) \) which makes it expensive to compute numerically. + +

+ + +

The sensitiveness of the gradient descent

+ +

+The gradient descent method +is sensitive to the choice of learning rate \( \gamma_k \). This is due +to the fact that we are only guaranteed that \( F(\mathbf{x}_{k+1}) \leq +F(\mathbf{x}_k) \) for sufficiently small \( \gamma_k \). The problem is to +determine an optimal learning rate. If the learning rate is chosen too +small the method will take a long time to converge and if it is too +large we can experience erratic behavior. + +

+Many of these shortcomings can be alleviated by introducing +randomness. One such method is that of Stochastic Gradient Descent +(SGD), see below. + +

+ + +

Convex functions

+ +

+Ideally we want our cost/loss function to be convex(concave). + +

+First we give the definition of a convex set: A set \( C \) in +\( \mathbb{R}^n \) is said to be convex if, for all \( x \) and \( y \) in \( C \) and +all \( t \in (0,1) \) , the point \( (1 − t)x + ty \) also belongs to +C. Geometrically this means that every point on the line segment +connecting \( x \) and \( y \) is in \( C \) as discussed below. + +

+The convex subsets of \( \mathbb{R} \) are the intervals of +\( \mathbb{R} \). Examples of convex sets of \( \mathbb{R}^2 \) are the +regular polygons (triangles, rectangles, pentagons, etc...). + +

+









+ +

Convex function

+ +

+Convex function: Let \( X \subset \mathbb{R}^n \) be a convex set. Assume that the function \( f: X \rightarrow \mathbb{R} \) is continuous, then \( f \) is said to be convex if $$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ for all \( x_1, x_2 \in X \) and for all \( t \in [0,1] \). If \( \leq \) is replaced with a strict inequaltiy in the definition, we demand \( x_1 \neq x_2 \) and \( t\in(0,1) \) then \( f \) is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting \( f(x_1) \) and \( f(x_2) \), the value of the function on the interval \( [x_1,x_2] \) is always below the line as illustrated below. + +

+









+ +

Conditions on convex functions

+ +

+In the following we state first and second-order conditions which +ensures convexity of a function \( f \). We write \( D_f \) to denote the +domain of \( f \), i.e the subset of \( R^n \) where \( f \) is defined. For more +details and proofs we refer to: S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press. + +

+

+First order condition. +

+Suppose \( f \) is differentiable (i.e \( \nabla f(x) \) is well defined for +all \( x \) in the domain of \( f \)). Then \( f \) is convex if and only if \( D_f \) +is a convex set and $$f(y) \geq f(x) + \nabla f(x)^T (y-x) $$ holds +for all \( x,y \in D_f \). This condition means that for a convex function +the first order Taylor expansion (right hand side above) at any point +a global under estimator of the function. To convince yourself you can +make a drawing of \( f(x) = x^2+1 \) and draw the tangent line to \( f(x) \) and +note that it is always below the graph. +

+ + +

+

+Second order condition. +

+Assume that \( f \) is twice +differentiable, i.e the Hessian matrix exists at each point in +\( D_f \). Then \( f \) is convex if and only if \( D_f \) is a convex set and its +Hessian is positive semi-definite for all \( x\in D_f \). For a +single-variable function this reduces to \( f''(x) \geq 0 \). Geometrically this means that \( f \) has nonnegative curvature +everywhere. +

+ + +

+This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition. + +

+









+ +

More on convex functions

+ +

+The next result is of great importance to us and the reason why we are +going on about convex functions. In machine learning we frequently +have to minimize a loss/cost function in order to find the best +parameters for the model we are considering. + +

+Ideally we want the +global minimum (for high-dimensional models it is hard to know +if we have local or global minimum). However, if the cost/loss function +is convex the following result provides invaluable information: + +

+

+Any minimum is global for convex functions. +

+Consider the problem of finding \( x \in \mathbb{R}^n \) such that \( f(x) \) +is minimal, where \( f \) is convex and differentiable. Then, any point +\( x^* \) that satisfies \( \nabla f(x^*) = 0 \) is a global minimum. +

+ + +

+This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum. + +

+









+ +

Some simple problems

+ +
    +
  1. Show that \( f(x)=x^2 \) is convex for \( x \in \mathbb{R} \) using the definition of convexity. Hint: If you re-write the definition, \( f \) is convex if the following holds for all \( x,y \in D_f \) and any \( \lambda \in [0,1] \) $\lambda f(x)+(1-\lambda)f(y)-f(\lambda x + (1-\lambda) y ) \geq 0$.
  2. +
  3. Using the second order condition show that the following functions are convex on the specified domain.
  4. + +
      +
    • \( f(x) = e^x \) is convex for \( x \in \mathbb{R} \).
    • +
    • \( g(x) = -\ln(x) \) is convex for \( x \in (0,\infty) \).
    • +
    + +
  5. Let \( f(x) = x^2 \) and \( g(x) = e^x \). Show that \( f(g(x)) \) and \( g(f(x)) \) is convex for \( x \in \mathbb{R} \). Also show that if \( f(x) \) is any convex function than \( h(x) = e^{f(x)} \) is convex.
  6. +
  7. A norm is any function that satisfy the following properties
  8. + +
      +
    • \( f(\alpha x) = |\alpha| f(x) \) for all \( \alpha \in \mathbb{R} \).
    • +
    • \( f(x+y) \leq f(x) + f(y) \)
    • +
    • \( f(x) \leq 0 \) for all \( x \in \mathbb{R}^n \) with equality if and only if \( x = 0 \)
    • +
    + +
+ +Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this). + +

+ + +

Revisiting our first homework

+ +

+We will use linear regression as a case study for the gradient descent +methods. Linear regression is a great test case for the gradient +descent methods discussed in the lectures since it has several +desirable properties such as: + +

    +
  1. An analytical solution (recall homework set 1).
  2. +
  3. The gradient can be computed analytically.
  4. +
  5. The cost function is convex which guarantees that gradient descent converges for small enough learning rates
  6. +
+ +We revisit the example from homework set 1 where we had +$$ +y_i = 5x_i^2 + 0.1\xi_i, \ i=1,\cdots,100 +$$ + +with \( x_i \in [0,1] \) chosen randomly with a uniform distribution. Additionally \( \xi_i \) represents stochastic noise chosen according to a normal distribution \( \cal {N}(0,1) \). +The linear regression model is given by +$$ +h_\beta(x) = \hat{y} = \beta_0 + \beta_1 x, +$$ + +such that +$$ +\hat{y}_i = \beta_0 + \beta_1 x_i. +$$ + +

+ + +

Gradient descent example

+ +

+Let \( \mathbf{y} = (y_1,\cdots,y_n)^T \), \( \mathbf{\hat{y}} = (\hat{y}_1,\cdots,\hat{y}_n)^T \) and \( \beta = (\beta_0, \beta_1)^T \) + +

+It is convenient to write \( \mathbf{\hat{y}} = X\beta \) where \( X \in \mathbb{R}^{100 \times 2} \) is the design matrix given by +$$ +X \equiv \begin{bmatrix} +1 & x_1 \\ +\vdots & \vdots \\ +1 & x_{100} & \\ +\end{bmatrix}. +$$ + +The loss function is given by +$$ +C(\beta) = ||X\beta-\mathbf{y}||^2 = ||X\beta||^2 - 2 \mathbf{y}^T X\beta + ||\mathbf{y}||^2 = \sum_{i=1}^{100} (\beta_0 + \beta_1 x_i)^2 - 2 y_i (\beta_0 + \beta_1 x_i) + y_i^2 +$$ + +and we want to find \( \beta \) such that \( C(\beta) \) is minimized. + +

+









+ +

The derivative of the cost/loss function

+ +

+Computing \( \partial C(\beta) / \partial \beta_0 \) and \( \partial C(\beta) / \partial \beta_1 \) we can show that the gradient can be written as +$$ +\nabla_{\beta} C(\beta) = (\partial C(\beta) / \partial \beta_0, \partial C(\beta) / \partial \beta_1)^T = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} = 2X^T(X\beta - \mathbf{y}), +$$ + +where \( X \) is the design matrix defined above. + +

+









+ +

The Hessian matrix

+The Hessian matrix of \( C(\beta) \) is given by +$$ +\hat{H} \equiv \begin{bmatrix} +\frac{\partial^2 C(\beta)}{\partial \beta_0^2} & \frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} \\ +\frac{\partial^2 C(\beta)}{\partial \beta_0 \partial \beta_1} & \frac{\partial^2 C(\beta)}{\partial \beta_1^2} & \\ +\end{bmatrix} = 2X^T X. +$$ + +This result implies that \( C(\beta) \) is a convex function since the matrix \( X^T X \) always is positive semi-definite. + +

+









+ +

Simple program

+ +

+We can now write a program that minimizes \( C(\beta) \) using the gradient descent method with a constant learning rate \( \gamma \) according to +$$ +\beta_{k+1} = \beta_k - \gamma \nabla_\beta C(\beta_k), \ k=0,1,\cdots +$$ + +

+We can use the expression we computed for the gradient and let use a +\( \beta_0 \) be chosen randomly and let \( \gamma = 0.001 \). Stop iterating +when \( ||\nabla_\beta C(\beta_k) || \leq \epsilon = 10^{-8} \). + +

+And finally we can compare our solution for \( \beta \) with the analytic result given by +\( \beta= (X^TX)^{-1} X^T \mathbf{y} \). + +

+









+ +

Gradient Descent Example

+ +

+Here our simple example +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 1000
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T.dot(xb.dot(beta)-y)
+    beta -= eta*gradients
+
+print(beta)
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(beta)
+ypredict2 = xbnew.dot(beta_linreg)
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example')
+plt.show()
+
+

+









+ +

And a corresponding example using scikit-learn

+ +

+ + +

# Importing various packages
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+x = 2*np.random.rand(100,1)
+y = 4+3*x+np.random.randn(100,1)
+
+xb = np.c_[np.ones((100,1)), x]
+beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print(beta_linreg)
+sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print(sgdreg.intercept_, sgdreg.coef_)
+
+

+ + +

Gradient descent and Ridge

+ +

+We have also discussed Ridge regression where the loss function contains a regularized term given by the \( L_2 \) norm of \( \beta \), +$$ +C_{\text{ridge}}(\beta) = ||X\beta -\mathbf{y}||^2 + \lambda ||\beta||^2, \ \lambda \geq 0. +$$ + +

+In order to minimize \( C_{\text{ridge}}(\beta) \) using GD we only have adjust the gradient as follows +$$ +\nabla_\beta C_{\text{ridge}}(\beta) = 2\begin{bmatrix} \sum_{i=1}^{100} \left(\beta_0+\beta_1x_i-y_i\right) \\ +\sum_{i=1}^{100}\left( x_i (\beta_0+\beta_1x_i)-y_ix_i\right) \\ +\end{bmatrix} + 2\lambda\begin{bmatrix} \beta_0 \\ \beta_1\end{bmatrix} = 2 (X^T(X\beta - \mathbf{y})+\lambda \beta). +$$ + +

+We can easily extend our program to minimize \( C_{\text{ridge}}(\beta) \) using gradient descent and compare with the analytical solution given by +$$ +\beta_{\text{ridge}} = \left(X^T X + \lambda I_{2 \times 2} \right)^{-1} X^T \mathbf{y}. +$$ + +

+









+ +

Program example for gradient descent with Ridge Regression

+

+ + +

from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+from matplotlib import cm
+from matplotlib.ticker import LinearLocator, FormatStrFormatter
+import sys
+
+# the number of datapoints
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+XT_X = xb.T @ xb
+
+#Ridge parameter lambda
+lmbda  = 0.001
+Id = lmbda* np.eye(XT_X.shape[0])
+
+beta_linreg = np.linalg.inv(XT_X+Id) @ xb.T @ y
+print(beta_linreg)
+# Start plain gradient descent
+beta = np.random.randn(2,1)
+
+eta = 0.1
+Niterations = 100
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ (xb @ (beta)-y)+2*lmbda*beta
+    beta -= eta*gradients
+
+print(beta)
+ypredict = xb @ beta
+ypredict2 = xb @ beta_linreg
+plt.plot(x, ypredict, "r-")
+plt.plot(x, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Gradient descent example for Ridge')
+plt.show()
+
+

+









+ +

Using gradient descent methods, limitations

+ + + +









+ +

Friday September 25

+ +

+









+ +

Stochastic Gradient Descent

+ +

+Stochastic gradient descent (SGD) and variants thereof address some of +the shortcomings of the Gradient descent method discussed above. + +

+The underlying idea of SGD comes from the observation that the cost +function, which we want to minimize, can almost always be written as a +sum over \( n \) data points \( \{\mathbf{x}_i\}_{i=1}^n \), +$$ +C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

+









+ +

Computation of gradients

+ +

+This in turn means that the gradient can be +computed as a sum over \( i \)-gradients +$$ +\nabla_\beta C(\mathbf{\beta}) = \sum_i^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}). +$$ + +

+Stochasticity/randomness is introduced by only taking the +gradient on a subset of the data called minibatches. If there are \( n \) +data points and the size of each minibatch is \( M \), there will be \( n/M \) +minibatches. We denote these minibatches by \( B_k \) where +\( k=1,\cdots,n/M \). + +

+









+ +

SGD example

+As an example, suppose we have \( 10 \) data points \( (\mathbf{x}_1,\cdots, \mathbf{x}_{10}) \) +and we choose to have \( M=5 \) minibathces, +then each minibatch contains two data points. In particular we have +\( B_1 = (\mathbf{x}_1,\mathbf{x}_2), \cdots, B_5 = +(\mathbf{x}_9,\mathbf{x}_{10}) \). Note that if you choose \( M=1 \) you +have only a single batch with all data points and on the other extreme, +you may choose \( M=n \) resulting in a minibatch for each datapoint, i.e +\( B_k = \mathbf{x}_k \). + +

+The idea is now to approximate the gradient by replacing the sum over +all data points with a sum over the data points in one the minibatches +picked at random in each gradient descent step +$$ +\nabla_{\beta} +C(\mathbf{\beta}) = \sum_{i=1}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) \rightarrow \sum_{i \in B_k}^n \nabla_\beta +c_i(\mathbf{x}_i, \mathbf{\beta}). +$$ + +

+









+ +

The gradient step

+ +

+Thus a gradient descent step now looks like +$$ +\beta_{j+1} = \beta_j - \gamma_j \sum_{i \in B_k}^n \nabla_\beta c_i(\mathbf{x}_i, +\mathbf{\beta}) +$$ + +

+where \( k \) is picked at random with equal +probability from \( [1,n/M] \). An iteration over the number of +minibathces (n/M) is commonly referred to as an epoch. Thus it is +typical to choose a number of epochs and for each epoch iterate over +the number of minibatches, as exemplified in the code below. + +

+









+ +

Simple example code

+ +

+ + +

import numpy as np 
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 10 #number of epochs
+
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for 
+        j += 1
+
+

+Taking the gradient only on a subset of the data has two important +benefits. First, it introduces randomness which decreases the chance +that our opmization scheme gets stuck in a local minima. Second, if +the size of the minibatches are small relative to the number of +datapoints (\( M < n \)), the computation of the gradient is much +cheaper since we sum over the datapoints in the \( k-th \) minibatch and not +all \( n \) datapoints. + +

+









+ +

When do we stop?

+ +

+A natural question is when do we stop the search for a new minimum? +One possibility is to compute the full gradient after a given number +of epochs and check if the norm of the gradient is smaller than some +threshold and stop if true. However, the condition that the gradient +is zero is valid also for local minima, so this would only tell us +that we are close to a local/global minimum. However, we could also +evaluate the cost function at this point, store the result and +continue the search. If the test kicks in at a later stage we can +compare the values of the cost function and keep the \( \beta \) that +gave the lowest value. + +

+









+ +

Slightly different approach

+ +

+Another approach is to let the step length \( \gamma_j \) depend on the +number of epochs in such a way that it becomes very small after a +reasonable time such that we do not move at all. + +

+As an example, let \( e = 0,1,2,3,\cdots \) denote the current epoch and let \( t_0, t_1 > 0 \) be two fixed numbers. Furthermore, let \( t = e \cdot m + i \) where \( m \) is the number of minibatches and \( i=0,\cdots,m-1 \). Then the function $$\gamma_j(t; t_0, t_1) = \frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length \( \gamma_j (0; t_0, t_1) = t_0/t_1 \) which decays in time \( t \). + +

+In this way we can fix the number of epochs, compute \( \beta \) and +evaluate the cost function at the end. Repeating the computation will +give a different result since the scheme is random by design. Then we +pick the final \( \beta \) that gives the lowest value of the cost +function. + +

+ + +

import numpy as np 
+
+def step_length(t,t0,t1):
+    return t0/(t+t1)
+
+n = 100 #100 datapoints 
+M = 5   #size of each minibatch
+m = int(n/M) #number of minibatches
+n_epochs = 500 #number of epochs
+t0 = 1.0
+t1 = 10
+
+gamma_j = t0/t1
+j = 0
+for epoch in range(1,n_epochs+1):
+    for i in range(m):
+        k = np.random.randint(m) #Pick the k-th minibatch at random
+        #Compute the gradient using the data in minibatch Bk
+        #Compute new suggestion for beta
+        t = epoch*m+i
+        gamma_j = step_length(t,t0,t1)
+        j += 1
+
+print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j))
+
+

+









+ +

Program for stochastic gradient

+ +

+ + +

# Importing various packages
+from math import exp, sqrt
+from random import random, seed
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.linear_model import SGDRegressor
+
+m = 100
+x = 2*np.random.rand(m,1)
+y = 4+3*x+np.random.randn(m,1)
+
+xb = np.c_[np.ones((m,1)), x]
+theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
+print("Own inversion")
+print(theta_linreg)
+sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)
+sgdreg.fit(x,y.ravel())
+print("sgdreg from scikit")
+print(sgdreg.intercept_, sgdreg.coef_)
+
+
+theta = np.random.randn(2,1)
+eta = 0.1
+Niterations = 1000
+
+
+for iter in range(Niterations):
+    gradients = 2.0/m*xb.T @ ((xb @ theta)-y)
+    theta -= eta*gradients
+print("theta frm own gd")
+print(theta)
+
+xnew = np.array([[0],[2]])
+xbnew = np.c_[np.ones((2,1)), xnew]
+ypredict = xbnew.dot(theta)
+ypredict2 = xbnew.dot(theta_linreg)
+
+
+n_epochs = 50
+t0, t1 = 5, 50
+def learning_schedule(t):
+    return t0/(t+t1)
+
+theta = np.random.randn(2,1)
+
+for epoch in range(n_epochs):
+    for i in range(m):
+        random_index = np.random.randint(m)
+        xi = xb[random_index:random_index+1]
+        yi = y[random_index:random_index+1]
+        gradients = 2 * xi.T @ ((xi @ theta)-yi)
+        eta = learning_schedule(epoch*m+i)
+        theta = theta - eta*gradients
+print("theta from own sdg")
+print(theta)
+
+plt.plot(xnew, ypredict, "r-")
+plt.plot(xnew, ypredict2, "b-")
+plt.plot(x, y ,'ro')
+plt.axis([0,2.0,0, 15.0])
+plt.xlabel(r'$x$')
+plt.ylabel(r'$y$')
+plt.title(r'Random numbers ')
+plt.show()
+
+

+Challenge: try to write a similar code for a Logistic Regression case. + +

+









+ +

Momentum based GD

+ +

+The stochastic gradient descent (SGD) is almost always used with a +momentum or inertia term that serves as a memory of the direction we +are moving in parameter space. This is typically implemented as +follows + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}, +\label{_auto1} +\end{align} +$$ + +

+where we have introduced a momentum parameter \( \gamma \), with +\( 0\le\gamma\le 1 \), and for brevity we dropped the explicit notation to +indicate the gradient is to be taken over a different mini-batch at +each step. We call this algorithm gradient descent with momentum +(GDM). From these equations, it is clear that \( \mathbf{v}_t \) is a +running average of recently encountered gradients and +\( (1-\gamma)^{-1} \) sets the characteristic time scale for the memory +used in the averaging procedure. Consistent with this, when +\( \gamma=0 \), this just reduces down to ordinary SGD as discussed +earlier. An equivalent way of writing the updates is + +$$ +\Delta \boldsymbol{\theta}_{t+1} = \gamma \Delta \boldsymbol{\theta}_t -\ \eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t), +$$ + +where we have defined \( \Delta \boldsymbol{\theta}_{t}= \boldsymbol{\theta}_t-\boldsymbol{\theta}_{t-1} \). + +

+









+ +

More on momentum based approaches

+ +

+Let us try to get more intuition from these equations. It is helpful +to consider a simple physical analogy with a particle of mass \( m \) +moving in a viscous medium with drag coefficient \( \mu \) and potential +\( E(\mathbf{w}) \). If we denote the particle's position by \( \mathbf{w} \), +then its motion is described by + +$$ +m {d^2 \mathbf{w} \over dt^2} + \mu {d \mathbf{w} \over dt }= -\nabla_w E(\mathbf{w}). +$$ + +

+We can discretize this equation in the usual way to get + +$$ +m { \mathbf{w}_{t+\Delta t}-2 \mathbf{w}_{t} +\mathbf{w}_{t-\Delta t} \over (\Delta t)^2}+\mu {\mathbf{w}_{t+\Delta t}- \mathbf{w}_{t} \over \Delta t} = -\nabla_w E(\mathbf{w}). +$$ + +

+Rearranging this equation, we can rewrite this as + +$$ +\Delta \mathbf{w}_{t +\Delta t}= - { (\Delta t)^2 \over m +\mu \Delta t} \nabla_w E(\mathbf{w})+ {m \over m +\mu \Delta t} \Delta \mathbf{w}_t. +$$ + +

+









+ +

Momentum parameter

+ +

+Notice that this equation is identical to previous one if we identify +the position of the particle, \( \mathbf{w} \), with the parameters +\( \boldsymbol{\theta} \). This allows us to identify the momentum +parameter and learning rate with the mass of the particle and the +viscous drag as: + +$$ +\gamma= {m \over m +\mu \Delta t }, \qquad \eta = {(\Delta t)^2 \over m +\mu \Delta t}. +$$ + +

+Thus, as the name suggests, the momentum parameter is proportional to +the mass of the particle and effectively provides inertia. +Furthermore, in the large viscosity/small learning rate limit, our +memory time scales as \( (1-\gamma)^{-1} \approx m/(\mu \Delta t) \). + +

+Why is momentum useful? SGD momentum helps the gradient descent +algorithm gain speed in directions with persistent but small gradients +even in the presence of stochasticity, while suppressing oscillations +in high-curvature directions. This becomes especially important in +situations where the landscape is shallow and flat in some directions +and narrow and steep in others. It has been argued that first-order +methods (with appropriate initial conditions) can perform comparable +to more expensive second order methods, especially in the context of +complex deep learning models. + +

+These beneficial properties of momentum can sometimes become even more +pronounced by using a slight modification of the classical momentum +algorithm called Nesterov Accelerated Gradient (NAG). + +

+In the NAG algorithm, rather than calculating the gradient at the +current parameters, \( \nabla_\theta E(\boldsymbol{\theta}_t) \), one +calculates the gradient at the expected value of the parameters given +our current momentum, \( \nabla_\theta E(\boldsymbol{\theta}_t +\gamma +\mathbf{v}_{t-1}) \). This yields the NAG update rule + +$$ +\begin{align} +\mathbf{v}_{t}&=\gamma \mathbf{v}_{t-1}+\eta_{t}\nabla_\theta E(\boldsymbol{\theta}_t +\gamma \mathbf{v}_{t-1}) \nonumber \\ +\boldsymbol{\theta}_{t+1}&= \boldsymbol{\theta}_t -\mathbf{v}_{t}. +\label{_auto2} +\end{align} +$$ + +

+One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of \( \gamma \). + +

+









+ +

Second moment of the gradient

+ +

+In stochastic gradient descent, with and without momentum, we still +have to specify a schedule for tuning the learning rates \( \eta_t \) +as a function of time. As discussed in the context of Newton's +method, this presents a number of dilemmas. The learning rate is +limited by the steepest direction which can change depending on the +current position in the landscape. To circumvent this problem, ideally +our algorithm would keep track of curvature and take large steps in +shallow, flat directions and small steps in steep, narrow directions. +Second-order methods accomplish this by calculating or approximating +the Hessian and normalizing the learning rate by the +curvature. However, this is very computationally expensive for +extremely large models. Ideally, we would like to be able to +adaptively change the step size to match the landscape without paying +the steep computational price of calculating or approximating +Hessians. + +

+Recently, a number of methods have been introduced that accomplish +this by tracking not only the gradient, but also the second moment of +the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and +ADAM. + +

+









+ +

RMS prop

+ +

+In RMS prop, in addition to keeping a running average of the first +moment of the gradient, we also keep track of the second moment +denoted by \( \mathbf{s}_t=\mathbb{E}[\mathbf{g}_t^2] \). The update rule +for RMS prop is given by + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto3}\\ +\mathbf{s}_t &=\beta \mathbf{s}_{t-1} +(1-\beta)\mathbf{g}_t^2 \nonumber \\ +\boldsymbol{\theta}_{t+1}&=&\boldsymbol{\theta}_t - \eta_t { \mathbf{g}_t \over \sqrt{\mathbf{s}_t +\epsilon}}, \nonumber +\end{align} +$$ + +

+where \( \beta \) controls the averaging time of the second moment and is +typically taken to be about \( \beta=0.9 \), \( \eta_t \) is a learning rate +typically chosen to be \( 10^{-3} \), and \( \epsilon\sim 10^{-8} \) is a +small regularization constant to prevent divergences. Multiplication +and division by vectors is understood as an element-wise operation. It +is clear from this formula that the learning rate is reduced in +directions where the norm of the gradient is consistently large. This +greatly speeds up the convergence by allowing us to use a larger +learning rate for flat directions. + +

+









+ +

ADAM optimizer

+ +

+A related algorithm is the ADAM optimizer. In ADAM, we keep a running +average of both the first and second moment of the gradient and use +this information to adaptively change the learning rate for different +parameters. In addition to keeping a running average of the first and +second moments of the gradient +(i.e. \( \mathbf{m}_t=\mathbb{E}[\mathbf{g}_t] \) and +\( \mathbf{s}_t=\mathbb{E}[\mathbf{g}^2_t] \), respectively), ADAM +performs an additional bias correction to account for the fact that we +are estimating the first two moments of the gradient using a running +average (denoted by the hats in the update rule below). The update +rule for ADAM is given by (where multiplication and division are once +again understood to be element-wise operations below) + +$$ +\begin{align} +\mathbf{g}_t &= \nabla_\theta E(\boldsymbol{\theta}) +\label{_auto4}\\ +\mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \mathbf{g}_t \nonumber \\ +\mathbf{s}_t &=\beta_2 \mathbf{s}_{t-1} +(1-\beta_2)\mathbf{g}_t^2 \nonumber \\ +\hat{\mathbf{m}}_t&={\mathbf{m}_t \over 1-\beta_1^t} \nonumber \\ +\hat{\mathbf{s}}_t &={\mathbf{s}_t \over1-\beta_2^t} \nonumber \\ +\boldsymbol{\theta}_{t+1}&=\boldsymbol{\theta}_t - \eta_t { \hat{\mathbf{m}}_t \over \sqrt{\hat{\mathbf{s}}_t} +\epsilon}, \nonumber \\ +\label{_auto5} +\end{align} +$$ + +

+where \( \beta_1 \) and \( \beta_2 \) set the memory lifetime of the first and +second moment and are typically taken to be \( 0.9 \) and \( 0.99 \) +respectively, and \( \eta \) and \( \epsilon \) are identical to RMSprop. + +

+Like in RMSprop, the effective step size of a parameter depends on the +magnitude of its gradient squared. To understand this better, let us +rewrite this expression in terms of the variance +\( \boldsymbol{\sigma}_t^2 = \hat{\mathbf{s}}_t - +(\hat{\mathbf{m}}_t)^2 \). Consider a single parameter \( \theta_t \). The +update rule for this parameter is given by + +$$ +\Delta \theta_{t+1}= -\eta_t { \hat{m}_t \over \sqrt{\sigma_t^2 + m_t^2 }+\epsilon}. +$$ + +

+









+ +

Practical tips

+ + + +Geron's text, see chapter 11, has several interesting discussions. + +

+









+ +

Automatic differentiation

+ +

+Automatic differentiation (AD), +also called algorithmic +differentiation or computational differentiation,is a set of +techniques to numerically evaluate the derivative of a function +specified by a computer program. AD exploits the fact that every +computer program, no matter how complicated, executes a sequence of +elementary arithmetic operations (addition, subtraction, +multiplication, division, etc.) and elementary functions (exp, log, +sin, cos, etc.). By applying the chain rule repeatedly to these +operations, derivatives of arbitrary order can be computed +automatically, accurately to working precision, and using at most a +small constant factor more arithmetic operations than the original +program. + +

+Automatic differentiation is neither: + +

+ +Symbolic differentiation can lead to inefficient code and faces the +difficulty of converting a computer program into a single expression, +while numerical differentiation can introduce round-off errors in the +discretization process and cancellation + +

+Python has tools for so-called automatic differentiation. +Consider the following example +$$ +f(x) = \sin\left(2\pi x + x^2\right) +$$ + +which has the following derivative +$$ +f'(x) = \cos\left(2\pi x + x^2\right)\left(2\pi + 2x\right) +$$ + +Using autograd we have + +

+ + +

import autograd.numpy as np
+
+# To do elementwise differentiation:
+from autograd import elementwise_grad as egrad 
+
+# To plot:
+import matplotlib.pyplot as plt 
+
+
+def f(x):
+    return np.sin(2*np.pi*x + x**2)
+
+def f_grad_analytic(x):
+    return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)
+
+# Do the comparison:
+x = np.linspace(0,1,1000)
+
+f_grad = egrad(f)
+
+computed = f_grad(x)
+analytic = f_grad_analytic(x)
+
+plt.title('Derivative computed from Autograd compared with the analytical derivative')
+plt.plot(x,computed,label='autograd')
+plt.plot(x,analytic,label='analytic')
+
+plt.xlabel('x')
+plt.ylabel('y')
+plt.legend()
+
+plt.show()
+
+print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic))))
+
+

+ + +

Using autograd

+ +

+Here we +experiment with what kind of functions Autograd is capable +of finding the gradient of. The following Python functions are just +meant to illustrate what Autograd can do, but please feel free to +experiment with other, possibly more complicated, functions as well. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f1(x):
+    return x**3 + 1
+
+f1_grad = grad(f1)
+
+# Remember to send in float as argument to the computed gradient from Autograd!
+a = 1.0
+
+# See the evaluated gradient at a using autograd:
+print("The gradient of f1 evaluated at a = %g using autograd is: %g"%(a,f1_grad(a)))
+
+# Compare with the analytical derivative, that is f1'(x) = 3*x**2 
+grad_analytical = 3*a**2
+print("The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g"%(a,grad_analytical))
+
+

+









+ +

Autograd with more complicated functions

+ +

+To differentiate with respect to two (or more) arguments of a Python +function, Autograd need to know at which variable the function if +being differentiated with respect to. + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f2(x1,x2):
+    return 3*x1**3 + x2*(x1 - 5) + 1
+
+# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1
+f2_grad_x1 = grad(f2,0)
+
+# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad
+f2_grad_x2 = grad(f2,1)
+
+x1 = 1.0
+x2 = 3.0 
+
+print("Evaluating at x1 = %g, x2 = %g"%(x1,x2))
+print("-"*30)
+
+# Compare with the analytical derivatives:
+
+# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:
+f2_grad_x1_analytical = 9*x1**2 + x2
+
+# Derivative of f2 w.r.t x2 is: x1 - 5:
+f2_grad_x2_analytical = x1 - 5
+
+# See the evaluated derivations:
+print("The derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x1: %g"%( f2_grad_x1(x1,x2) ))
+
+print()
+
+print("The derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+print("The analytical derivative of f2 w.r.t x2: %g"%( f2_grad_x2(x1,x2) ))
+
+

+Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable. + +

+









+ +

More complicated functions using the elements of their arguments directly

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f3(x): # Assumes x is an array of length 5 or higher
+    return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2
+
+f3_grad = grad(f3)
+
+x = np.linspace(0,4,5)
+
+# Print the computed gradient:
+print("The computed gradient of f3 is: ", f3_grad(x))
+
+# The analytical gradient is: (2, 3, 5, 7, 22*x[4])
+f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])
+
+# Print the analytical gradient:
+print("The analytical gradient of f3 is: ", f3_grad_analytical)
+
+

+Note that in this case, when sending an array as input argument, the +output from Autograd is another array. This is the true gradient of +the function, as opposed to the function in the previous example. By +using arrays to represent the variables, the output from Autograd +might be easier to work with, as the output is closer to what one +could expect form a gradient-evaluting function. + +

+ + +

Functions using mathematical functions from Numpy

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f4(x):
+    return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)
+
+f4_grad = grad(f4)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f4 at x = %g is: %g"%(x,f4_grad(x)))
+
+# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi
+f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi
+
+# Print the analytical gradient:
+print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical))
+
+

+









+ +

More autograd

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f5(x):
+    if x >= 0:
+        return x**2
+    else:
+        return -3*x + 1
+
+f5_grad = grad(f5)
+
+x = 2.7
+
+# Print the computed derivative:
+print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x)))
+
+

+









+ +

And with loops

+ +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f6_for(x):
+    val = 0
+    for i in range(10):
+        val = val + x**i
+    return val
+
+def f6_while(x):
+    val = 0
+    i = 0
+    while i < 10:
+        val = val + x**i
+        i = i + 1
+    return val
+
+f6_for_grad = grad(f6_for)
+f6_while_grad = grad(f6_while)
+
+x = 0.5
+
+# Print the computed derivaties of f6_for and f6_while
+print("The computed derivative of f6_for at x = %g is: %g"%(x,f6_for_grad(x)))
+print("The computed derivative of f6_while at x = %g is: %g"%(x,f6_while_grad(x)))
+
+

+ + +

import autograd.numpy as np
+from autograd import grad
+# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9
+# The analytical derivative is: sum(i*x**(i-1)) 
+f6_grad_analytical = 0
+for i in range(10):
+    f6_grad_analytical += i*x**(i-1)
+
+print("The analytical derivative of f6 at x = %g is: %g"%(x,f6_grad_analytical))
+
+

+









+ +

Using recursion

+

+ + +

import autograd.numpy as np
+from autograd import grad
+
+def f7(n): # Assume that n is an integer
+    if n == 1 or n == 0:
+        return 1
+    else:
+        return n*f7(n-1)
+
+f7_grad = grad(f7)
+
+n = 2.0
+
+print("The computed derivative of f7 at n = %d is: %g"%(n,f7_grad(n)))
+
+# The function f7 is an implementation of the factorial of n.
+# By using the product rule, one can find that the derivative is:
+
+f7_grad_analytical = 0
+for i in range(int(n)-1):
+    tmp = 1
+    for k in range(int(n)-1):
+        if k != i:
+            tmp *= (n - k)
+    f7_grad_analytical += tmp
+
+print("The analytical derivative of f7 at n = %d is: %g"%(n,f7_grad_analytical))
+
+

+Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input. + +

+









+ +

Unsupported functions

+Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd. + +

+Assigning a value to the variable being differentiated with respect to +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f8(x): # Assume x is an array
+    x[2] = 3
+    return x*2
+
+f8_grad = grad(f8)
+
+x = 8.4
+
+print("The derivative of f8 is:",f8_grad(x))
+
+

+Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible. + +

+









+ +

The syntax a.dot(b) when finding the dot product

+

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9(a): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return a.dot(b)
+
+f9_grad = grad(f9)
+
+x = np.array([1.0,0.0])
+
+print("The derivative of f9 is:",f9_grad(x))
+
+

+Here we are told that the 'dot' function does not belong to Autograd's +version of a Numpy array. To overcome this, an alternative syntax +which also computed the dot product can be used: + +

+ + +

import autograd.numpy as np
+from autograd import grad
+def f9_alternative(x): # Assume a is an array with 2 elements
+    b = np.array([1.0,2.0])
+    return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2
+
+f9_alternative_grad = grad(f9_alternative)
+
+x = np.array([3.0,0.0])
+
+print("The gradient of f9 is:",f9_alternative_grad(x))
+
+# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively
+# w.r.t x is (b_1, b_2).
+
+

+









+ +

Recommended to avoid

+The documentation recommends to avoid inplace operations such as +

+ + +

a += b
+a -= b
+a*= b
+a /=b
+
+

+









+ +

Standard steepest descent

+ +

+Before we proceed, we would like to discuss the approach called the +standard Steepest descent, which again leads to us having to be able +to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG). + +

+The success of the CG method +for finding solutions of non-linear problems is based on the theory +of conjugate gradients for linear systems of equations. It belongs to +the class of iterative methods for solving problems from linear +algebra of the type +$$ +\begin{equation*} +\hat{A}\hat{x} = \hat{b}. +\end{equation*} +$$ + +

+In the iterative process we end up with a problem like + +$$ +\begin{equation*} + \hat{r}= \hat{b}-\hat{A}\hat{x}, +\end{equation*} +$$ + +where \( \hat{r} \) is the so-called residual or error in the iterative process. + +

+When we have found the exact solution, \( \hat{r}=0 \). + +

+









+ +

Gradient method

+ +

+The residual is zero when we reach the minimum of the quadratic equation +$$ +\begin{equation*} + P(\hat{x})=\frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T\hat{b}, +\end{equation*} +$$ + +

+with the constraint that the matrix \( \hat{A} \) is positive definite and +symmetric. This defines also the Hessian and we want it to be positive definite. + +

+









+ +

Steepest descent method

+ +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ + +or consider the system +$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ + +instead. + +

+









+ +

Steepest descent method

+
+ +

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ + +This suggests taking the first basis vector \( \hat{r}_1 \) (see below for definition) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ + +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). + + +

+ + +

+









+ +

Final expressions

+
+ +

+We can compute the residual iteratively as +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ + +which equals +$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{r}_k), + \end{equation*} +$$ + +or +$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{r}_k, + \end{equation*} +$$ + +which gives + +$$ +\alpha_k = \frac{\hat{r}_k^T\hat{r}_k}{\hat{r}_k^T\hat{A}\hat{r}_k} +$$ + +leading to the iterative scheme +$$ +\begin{equation*} +\hat{x}_{k+1}=\hat{x}_k-\alpha_k\hat{r}_{k}, + \end{equation*} +$$ +

+ + +

+









+ +

Code examples for steepest descent

+ +

+









+ +

Simple codes for steepest descent and conjugate gradient using a \( 2\times 2 \) matrix, in c++, Python code to come

+
+ +

+

+ + +

#include <cmath>
+#include <iostream>
+#include <fstream>
+#include <iomanip>
+#include "vectormatrixclass.h"
+using namespace  std;
+//   Main function begins here
+int main(int  argc, char * argv[]){
+  int dim = 2;
+  Vector x(dim),xsd(dim), b(dim),x0(dim);
+  Matrix A(dim,dim);
+
+  // Set our initial guess
+  x0(0) = x0(1) = 0;
+  // Set the matrix
+  A(0,0) =  3;    A(1,0) =  2;   A(0,1) =  2;   A(1,1) =  6;
+  b(0) = 2; b(1) = -8;
+  cout << "The Matrix A that we are using: " << endl;
+  A.Print();
+  cout << endl;
+  xsd = SteepestDescent(A,b,x0);
+  cout << "The approximate solution using Steepest Descent is: " << endl;
+  xsd.Print();
+  cout << endl;
+}
+
+ +
+ + +

+









+ +

The routine for the steepest descent method

+
+ +

+

+ + +

Vector SteepestDescent(Matrix A, Vector b, Vector x0){
+  int IterMax, i;
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),f(dim),z(dim);
+  double c,alpha,d;
+  IterMax = 30;
+  x = x0;
+  r = A*x-b;
+  i = 0;
+  while (i <= IterMax){
+    z = A*r;
+    c = dot(r,r);
+    alpha = c/dot(r,z);
+    x = x - alpha*r;
+    r =  A*x-b;
+    if(sqrt(dot(r,r)) < tolerance) break;
+    i++;
+  }
+  return x;
+}
+
+ +
+ + +

+









+ +

Steepest descent example

+ +

+ + +

import numpy as np
+import numpy.linalg as la
+
+import scipy.optimize as sopt
+
+import matplotlib.pyplot as pt
+from mpl_toolkits.mplot3d import axes3d
+
+def f(x):
+    return 0.5*x[0]**2 + 2.5*x[1]**2
+
+def df(x):
+    return np.array([x[0], 5*x[1]])
+
+fig = pt.figure()
+ax = fig.gca(projection="3d")
+
+xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
+fmesh = f(np.array([xmesh, ymesh]))
+ax.plot_surface(xmesh, ymesh, fmesh)
+
+

+And then as countor plot +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh)
+guesses = [np.array([2, 2./5])]
+
+

+Find guesses +

+ + +

x = guesses[-1]
+s = -df(x)
+
+

+Run it! +

+ + +

def f1d(alpha):
+    return f(x + alpha*s)
+
+alpha_opt = sopt.golden(f1d)
+next_guess = x + alpha_opt * s
+guesses.append(next_guess)
+print(next_guess)
+
+

+What happened? +

+ + +

pt.axis("equal")
+pt.contour(xmesh, ymesh, fmesh, 50)
+it_array = np.array(guesses)
+pt.plot(it_array.T[0], it_array.T[1], "x-")
+
+

+









+ +

Conjugate gradient method

+
+ +

+In the CG method we define so-called conjugate directions and two vectors +\( \hat{s} \) and \( \hat{t} \) +are said to be +conjugate if +$$ +\begin{equation*} +\hat{s}^T\hat{A}\hat{t}= 0. +\end{equation*} +$$ + +The philosophy of the CG method is to perform searches in various conjugate directions +of our vectors \( \hat{x}_i \) obeying the above criterion, namely +$$ +\begin{equation*} +\hat{x}_i^T\hat{A}\hat{x}_j= 0. +\end{equation*} +$$ + +Two vectors are conjugate if they are orthogonal with respect to +this inner product. Being conjugate is a symmetric relation: if \( \hat{s} \) is conjugate to \( \hat{t} \), then \( \hat{t} \) is conjugate to \( \hat{s} \). +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+An example is given by the eigenvectors of the matrix +$$ +\begin{equation*} +\hat{v}_i^T\hat{A}\hat{v}_j= \lambda\hat{v}_i^T\hat{v}_j, +\end{equation*} +$$ + +which is zero unless \( i=j \). +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+Assume now that we have a symmetric positive-definite matrix \( \hat{A} \) of size +\( n\times n \). At each iteration \( i+1 \) we obtain the conjugate direction of a vector +$$ +\begin{equation*} +\hat{x}_{i+1}=\hat{x}_{i}+\alpha_i\hat{p}_{i}. +\end{equation*} +$$ + +We assume that \( \hat{p}_{i} \) is a sequence of \( n \) mutually conjugate directions. +Then the \( \hat{p}_{i} \) form a basis of \( R^n \) and we can expand the solution +$ \hat{A}\hat{x} = \hat{b}$ in this basis, namely + +$$ +\begin{equation*} + \hat{x} = \sum^{n}_{i=1} \alpha_i \hat{p}_i. +\end{equation*} +$$ +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+The coefficients are given by +$$ +\begin{equation*} + \mathbf{A}\mathbf{x} = \sum^{n}_{i=1} \alpha_i \mathbf{A} \mathbf{p}_i = \mathbf{b}. +\end{equation*} +$$ + +Multiplying with \( \hat{p}_k^T \) from the left gives + +$$ +\begin{equation*} + \hat{p}_k^T \hat{A}\hat{x} = \sum^{n}_{i=1} \alpha_i\hat{p}_k^T \hat{A}\hat{p}_i= \hat{p}_k^T \hat{b}, +\end{equation*} +$$ + +and we can define the coefficients \( \alpha_k \) as + +$$ +\begin{equation*} + \alpha_k = \frac{\hat{p}_k^T \hat{b}}{\hat{p}_k^T \hat{A} \hat{p}_k} +\end{equation*} +$$ +

+ + +

+









+ +

Conjugate gradient method and iterations

+
+ +

+ +

+If we choose the conjugate vectors \( \hat{p}_k \) carefully, +then we may not need all of them to obtain a good approximation to the solution +\( \hat{x} \). +We want to regard the conjugate gradient method as an iterative method. +This will us to solve systems where \( n \) is so large that the direct +method would take too much time. + +

+We denote the initial guess for \( \hat{x} \) as \( \hat{x}_0 \). +We can assume without loss of generality that +$$ +\begin{equation*} +\hat{x}_0=0, +\end{equation*} +$$ + +or consider the system +$$ +\begin{equation*} +\hat{A}\hat{z} = \hat{b}-\hat{A}\hat{x}_0, +\end{equation*} +$$ + +instead. +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+One can show that the solution \( \hat{x} \) is also the unique minimizer of the quadratic form +$$ +\begin{equation*} + f(\hat{x}) = \frac{1}{2}\hat{x}^T\hat{A}\hat{x} - \hat{x}^T \hat{x} , \quad \hat{x}\in\mathbf{R}^n. +\end{equation*} +$$ + +This suggests taking the first basis vector \( \hat{p}_1 \) +to be the gradient of \( f \) at \( \hat{x}=\hat{x}_0 \), +which equals +$$ +\begin{equation*} +\hat{A}\hat{x}_0-\hat{b}, +\end{equation*} +$$ + +and +\( \hat{x}_0=0 \) it is equal \( -\hat{b} \). +The other vectors in the basis will be conjugate to the gradient, +hence the name conjugate gradient method. +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+Let \( \hat{r}_k \) be the residual at the \( k \)-th step: +$$ +\begin{equation*} +\hat{r}_k=\hat{b}-\hat{A}\hat{x}_k. +\end{equation*} +$$ + +Note that \( \hat{r}_k \) is the negative gradient of \( f \) at +\( \hat{x}=\hat{x}_k \), +so the gradient descent method would be to move in the direction \( \hat{r}_k \). +Here, we insist that the directions \( \hat{p}_k \) are conjugate to each other, +so we take the direction closest to the gradient \( \hat{r}_k \) +under the conjugacy constraint. +This gives the following expression +$$ +\begin{equation*} +\hat{p}_{k+1}=\hat{r}_k-\frac{\hat{p}_k^T \hat{A}\hat{r}_k}{\hat{p}_k^T\hat{A}\hat{p}_k} \hat{p}_k. +\end{equation*} +$$ +

+ + +

+









+ +

Conjugate gradient method

+
+ +

+We can also compute the residual iteratively as +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{b}-\hat{A}\hat{x}_{k+1}, + \end{equation*} +$$ + +which equals +$$ +\begin{equation*} +\hat{b}-\hat{A}(\hat{x}_k+\alpha_k\hat{p}_k), + \end{equation*} +$$ + +or +$$ +\begin{equation*} +(\hat{b}-\hat{A}\hat{x}_k)-\alpha_k\hat{A}\hat{p}_k, + \end{equation*} +$$ + +which gives + +$$ +\begin{equation*} +\hat{r}_{k+1}=\hat{r}_k-\hat{A}\hat{p}_{k}, + \end{equation*} +$$ +

+ + +

+









+ +

Simple implementation of the Conjugate gradient algorithm

+
+ +

+

+ + +

  Vector ConjugateGradient(Matrix A, Vector b, Vector x0){
+  int dim = x0.Dimension();
+  const double tolerance = 1.0e-14;
+  Vector x(dim),r(dim),v(dim),z(dim);
+  double c,t,d;
+
+  x = x0;
+  r = b - A*x;
+  v = r;
+  c = dot(r,r);
+  int i = 0; IterMax = dim;
+  while(i <= IterMax){
+    z = A*v;
+    t = c/dot(v,z);
+    x = x + t*v;
+    r = r - t*z;
+    d = dot(r,r);
+    if(sqrt(d) < tolerance)
+      break;
+    v = r + (d/c)*v;
+    c = d;  i++;
+  }
+  return x;
+} 
+
+ +
+ + +

+









+ +

Broyden–Fletcher–Goldfarb–Shanno algorithm

+
+ +

+The optimization problem is to minimize \( f(\mathbf {x} ) \) where \( \mathbf {x} \) is a vector in \( R^{n} \), and \( f \) is a differentiable scalar function. There are no constraints on the values that \( \mathbf {x} \) can take. + +

+The algorithm begins at an initial estimate for the optimal value \( \mathbf {x}_{0} \) and proceeds iteratively to get a better estimate at each stage. + +

+The search direction \( p_k \) at stage \( k \) is given by the solution of the analogue of the Newton equation +$$ +B_{k}\mathbf {p} _{k}=-\nabla f(\mathbf {x}_{k}), +$$ + +

+where \( B_{k} \) is an approximation to the Hessian matrix, which is +updated iteratively at each stage, and \( \nabla f(\mathbf {x} _{k}) \) +is the gradient of the function +evaluated at \( x_k \). +A line search in the direction \( p_k \) is then used to +find the next point \( x_{k+1} \) by minimising +$$ +f(\mathbf {x}_{k}+\alpha \mathbf {p}_{k}), +$$ + +over the scalar \( \alpha > 0 \). + + +

+ + +

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz b/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz new file mode 100644 index 000000000..8973b1f79 Binary files /dev/null and b/doc/pub/week39/ipynb/ipynb-week39-src.tar.gz differ diff --git a/doc/pub/week39/ipynb/week39.ipynb b/doc/pub/week39/ipynb/week39.ipynb new file mode 100644 index 000000000..29d5ff2bc --- /dev/null +++ b/doc/pub/week39/ipynb/week39.ipynb @@ -0,0 +1,3043 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Week 39: Optimization and Gradient Methods\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "## Plan for week 39\n", + "\n", + "* Thursday: Repetition of Logistic regression equations and discussion of Gradient methods\n", + "\n", + "* Friday: Stochastic Gradient descent with examples and automatic differeantion\n", + "\n", + "## Thursday September 24\n", + "\n", + "## Optimization, the central part of any Machine Learning algortithm\n", + "\n", + "Almost every problem in machine learning and data science starts with\n", + "a dataset $X$, a model $g(\\beta)$, which is a function of the\n", + "parameters $\\beta$ and a cost function $C(X, g(\\beta))$ that allows\n", + "us to judge how well the model $g(\\beta)$ explains the observations\n", + "$X$. The model is fit by finding the values of $\\beta$ that minimize\n", + "the cost function. Ideally we would be able to solve for $\\beta$\n", + "analytically, however this is not possible in general and we must use\n", + "some approximative/numerical method to compute the minimum.\n", + "\n", + "\n", + "## Revisiting our Logistic Regression case\n", + "\n", + "In our discussion on Logistic Regression we studied the \n", + "case of\n", + "two classes, with $y_i$ either\n", + "$0$ or $1$. Furthermore we assumed also that we have only two\n", + "parameters $\\beta$ in our fitting, that is we\n", + "defined probabilities" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + "p(y_i=1|x_i,\\hat{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", + "p(y_i=0|x_i,\\hat{\\beta}) &= 1 - p(y_i=1|x_i,\\hat{\\beta}),\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\hat{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", + "\n", + "## The equations to solve\n", + "\n", + "Our compact equations used a definition of a vector $\\hat{y}$ with $n$\n", + "elements $y_i$, an $n\\times p$ matrix $\\hat{X}$ which contains the\n", + "$x_i$ values and a vector $\\hat{p}$ of fitted probabilities\n", + "$p(y_i\\vert x_i,\\hat{\\beta})$. We rewrote in a more compact form\n", + "the first derivative of the cost function as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}} = -\\hat{X}^T\\left(\\hat{y}-\\hat{p}\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we in addition define a diagonal matrix $\\hat{W}$ with elements \n", + "$p(y_i\\vert x_i,\\hat{\\beta})(1-p(y_i\\vert x_i,\\hat{\\beta})$, we can obtain a compact expression of the second derivative as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T} = \\hat{X}^T\\hat{W}\\hat{X}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This defines what is called the Hessian matrix.\n", + "\n", + "## Solving using Newton-Raphson's method\n", + "\n", + "If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. \n", + "\n", + "Our iterative scheme is then given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\beta}^{\\mathrm{new}} = \\hat{\\beta}^{\\mathrm{old}}-\\left(\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T}\\right)^{-1}_{\\hat{\\beta}^{\\mathrm{old}}}\\times \\left(\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}}\\right)_{\\hat{\\beta}^{\\mathrm{old}}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or in matrix form as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\beta}^{\\mathrm{new}} = \\hat{\\beta}^{\\mathrm{old}}-\\left(\\hat{X}^T\\hat{W}\\hat{X} \\right)^{-1}\\times \\left(-\\hat{X}^T(\\hat{y}-\\hat{p}) \\right)_{\\hat{\\beta}^{\\mathrm{old}}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The right-hand side is computed with the old values of $\\beta$. \n", + "\n", + "If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement. \n", + "\n", + "\n", + "## Brief reminder on Newton-Raphson's method\n", + "\n", + "Let us quickly remind ourselves how we derive the above method.\n", + "\n", + "Perhaps the most celebrated of all one-dimensional root-finding\n", + "routines is Newton's method, also called the Newton-Raphson\n", + "method. This method requires the evaluation of both the\n", + "function $f$ and its derivative $f'$ at arbitrary points. \n", + "If you can only calculate the derivative\n", + "numerically and/or your function is not of the smooth type, we\n", + "normally discourage the use of this method.\n", + "\n", + "## The equations\n", + "\n", + "The Newton-Raphson formula consists geometrically of extending the\n", + "tangent line at a current point until it crosses zero, then setting\n", + "the next guess to the abscissa of that zero-crossing. The mathematics\n", + "behind this method is rather simple. Employing a Taylor expansion for\n", + "$x$ sufficiently close to the solution $s$, we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "f(s)=0=f(x)+(s-x)f'(x)+\\frac{(s-x)^2}{2}f''(x) +\\dots.\n", + " \\label{eq:taylornr} \\tag{1}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For small enough values of the function and for well-behaved\n", + "functions, the terms beyond linear are unimportant, hence we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(x)+(s-x)f'(x)\\approx 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "yielding" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "s\\approx x-\\frac{f(x)}{f'(x)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Having in mind an iterative procedure, it is natural to start iterating with" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "x_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simple geometric interpretation\n", + "\n", + "The above is Newton-Raphson's method. It has a simple geometric\n", + "interpretation, namely $x_{n+1}$ is the point where the tangent from\n", + "$(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution,\n", + "Newton-Raphson converges fast to the desired result. However, if we\n", + "are far from a root, where the higher-order terms in the series are\n", + "important, the Newton-Raphson formula can give grossly inaccurate\n", + "results. For instance, the initial guess for the root might be so far\n", + "from the true root as to let the search interval include a local\n", + "maximum or minimum of the function. If an iteration places a trial\n", + "guess near such a local extremum, so that the first derivative nearly\n", + "vanishes, then Newton-Raphson may fail totally\n", + "\n", + "\n", + "## Extending to more than one variable\n", + "\n", + "Newton's method can be generalized to systems of several non-linear equations\n", + "and variables. Consider the case with two equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{array}{cc} f_1(x_1,x_2) &=0\\\\\n", + " f_2(x_1,x_2) &=0,\\end{array}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which we Taylor expand to obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1\n", + " \\partial f_1/\\partial x_1+h_2\n", + " \\partial f_1/\\partial x_2+\\dots\\\\\n", + " 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1\n", + " \\partial f_2/\\partial x_1+h_2\n", + " \\partial f_2/\\partial x_2+\\dots\n", + " \\end{array}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Defining the Jacobian matrix ${\\bf \\hat{J}}$ we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\bf \\hat{J}}=\\left( \\begin{array}{cc}\n", + " \\partial f_1/\\partial x_1 & \\partial f_1/\\partial x_2 \\\\\n", + " \\partial f_2/\\partial x_1 &\\partial f_2/\\partial x_2\n", + " \\end{array} \\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "we can rephrase Newton's method as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\left(\\begin{array}{c} x_1^{n+1} \\\\ x_2^{n+1} \\end{array} \\right)=\n", + "\\left(\\begin{array}{c} x_1^{n} \\\\ x_2^{n} \\end{array} \\right)+\n", + "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n", + " -{\\bf \\hat{J}}^{-1}\n", + " \\left(\\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\\\ f_2(x_1^{n},x_2^{n}) \\end{array} \\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We need thus to compute the inverse of the Jacobian matrix and it\n", + "is to understand that difficulties may\n", + "arise in case ${\\bf \\hat{J}}$ is nearly singular.\n", + "\n", + "It is rather straightforward to extend the above scheme to systems of\n", + "more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. \n", + "\n", + "\n", + "\n", + "## Steepest descent\n", + "\n", + "The basic idea of gradient descent is\n", + "that a function $F(\\mathbf{x})$, \n", + "$\\mathbf{x} \\equiv (x_1,\\cdots,x_n)$, decreases fastest if one goes from $\\bf {x}$ in the\n", + "direction of the negative gradient $-\\nabla F(\\mathbf{x})$.\n", + "\n", + "It can be shown that if" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $\\gamma_k > 0$.\n", + "\n", + "For $\\gamma_k$ small enough, then $F(\\mathbf{x}_{k+1}) \\leq\n", + "F(\\mathbf{x}_k)$. This means that for a sufficiently small $\\gamma_k$\n", + "we are always moving towards smaller function values, i.e a minimum.\n", + "\n", + "\n", + "## More on Steepest descent\n", + "\n", + "The previous observation is the basis of the method of steepest\n", + "descent, which is also referred to as just gradient descent (GD). One\n", + "starts with an initial guess $\\mathbf{x}_0$ for a minimum of $F$ and\n", + "computes new approximations according to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k), \\ \\ k \\geq 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The parameter $\\gamma_k$ is often referred to as the step length or\n", + "the learning rate within the context of Machine Learning.\n", + "\n", + "\n", + "## The ideal\n", + "\n", + "Ideally the sequence $\\{\\mathbf{x}_k \\}_{k=0}$ converges to a global\n", + "minimum of the function $F$. In general we do not know if we are in a\n", + "global or local minimum. In the special case when $F$ is a convex\n", + "function, all local minima are also global minima, so in this case\n", + "gradient descent can converge to the global solution. The advantage of\n", + "this scheme is that it is conceptually simple and straightforward to\n", + "implement. However the method in this form has some severe\n", + "limitations:\n", + "\n", + "In machine learing we are often faced with non-convex high dimensional\n", + "cost functions with many local minima. Since GD is deterministic we\n", + "will get stuck in a local minimum, if the method converges, unless we\n", + "have a very good intial guess. This also implies that the scheme is\n", + "sensitive to the chosen initial condition.\n", + "\n", + "Note that the gradient is a function of $\\mathbf{x} =\n", + "(x_1,\\cdots,x_n)$ which makes it expensive to compute numerically.\n", + "\n", + "\n", + "\n", + "## The sensitiveness of the gradient descent\n", + "\n", + "The gradient descent method \n", + "is sensitive to the choice of learning rate $\\gamma_k$. This is due\n", + "to the fact that we are only guaranteed that $F(\\mathbf{x}_{k+1}) \\leq\n", + "F(\\mathbf{x}_k)$ for sufficiently small $\\gamma_k$. The problem is to\n", + "determine an optimal learning rate. If the learning rate is chosen too\n", + "small the method will take a long time to converge and if it is too\n", + "large we can experience erratic behavior.\n", + "\n", + "Many of these shortcomings can be alleviated by introducing\n", + "randomness. One such method is that of Stochastic Gradient Descent\n", + "(SGD), see below.\n", + "\n", + "\n", + "\n", + "## Convex functions\n", + "\n", + "Ideally we want our cost/loss function to be convex(concave).\n", + "\n", + "First we give the definition of a convex set: A set $C$ in\n", + "$\\mathbb{R}^n$ is said to be convex if, for all $x$ and $y$ in $C$ and\n", + "all $t \\in (0,1)$ , the point $(1 − t)x + ty$ also belongs to\n", + "C. Geometrically this means that every point on the line segment\n", + "connecting $x$ and $y$ is in $C$ as discussed below.\n", + "\n", + "The convex subsets of $\\mathbb{R}$ are the intervals of\n", + "$\\mathbb{R}$. Examples of convex sets of $\\mathbb{R}^2$ are the\n", + "regular polygons (triangles, rectangles, pentagons, etc...).\n", + "\n", + "## Convex function\n", + "\n", + "**Convex function**: Let $X \\subset \\mathbb{R}^n$ be a convex set. Assume that the function $f: X \\rightarrow \\mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \\leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \\in X$ and for all $t \\in [0,1]$. If $\\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \\neq x_2$ and $t\\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below.\n", + "\n", + "## Conditions on convex functions\n", + "\n", + "In the following we state first and second-order conditions which\n", + "ensures convexity of a function $f$. We write $D_f$ to denote the\n", + "domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\n", + "details and proofs we refer to: [S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press](http://stanford.edu/boyd/cvxbook/, 2004).\n", + "\n", + "**First order condition.**\n", + "\n", + "Suppose $f$ is differentiable (i.e $\\nabla f(x)$ is well defined for\n", + "all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$\n", + "is a convex set and $$f(y) \\geq f(x) + \\nabla f(x)^T (y-x) $$ holds\n", + "for all $x,y \\in D_f$. This condition means that for a convex function\n", + "the first order Taylor expansion (right hand side above) at any point\n", + "a global under estimator of the function. To convince yourself you can\n", + "make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\n", + "note that it is always below the graph.\n", + "\n", + "\n", + "\n", + "**Second order condition.**\n", + "\n", + "Assume that $f$ is twice\n", + "differentiable, i.e the Hessian matrix exists at each point in\n", + "$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its\n", + "Hessian is positive semi-definite for all $x\\in D_f$. For a\n", + "single-variable function this reduces to $f''(x) \\geq 0$. Geometrically this means that $f$ has nonnegative curvature\n", + "everywhere.\n", + "\n", + "\n", + "\n", + "This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition.\n", + "\n", + "## More on convex functions\n", + "\n", + "The next result is of great importance to us and the reason why we are\n", + "going on about convex functions. In machine learning we frequently\n", + "have to minimize a loss/cost function in order to find the best\n", + "parameters for the model we are considering. \n", + "\n", + "Ideally we want the\n", + "global minimum (for high-dimensional models it is hard to know\n", + "if we have local or global minimum). However, if the cost/loss function\n", + "is convex the following result provides invaluable information:\n", + "\n", + "**Any minimum is global for convex functions.**\n", + "\n", + "Consider the problem of finding $x \\in \\mathbb{R}^n$ such that $f(x)$\n", + "is minimal, where $f$ is convex and differentiable. Then, any point\n", + "$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n", + "\n", + "\n", + "\n", + "This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum.\n", + "\n", + "## Some simple problems\n", + "\n", + "1. Show that $f(x)=x^2$ is convex for $x \\in \\mathbb{R}$ using the definition of convexity. Hint: If you re-write the definition, $f$ is convex if the following holds for all $x,y \\in D_f$ and any $\\lambda \\in [0,1]$ $\\lambda f(x)+(1-\\lambda)f(y)-f(\\lambda x + (1-\\lambda) y ) \\geq 0$.\n", + "\n", + "2. Using the second order condition show that the following functions are convex on the specified domain.\n", + "\n", + " * $f(x) = e^x$ is convex for $x \\in \\mathbb{R}$.\n", + "\n", + " * $g(x) = -\\ln(x)$ is convex for $x \\in (0,\\infty)$.\n", + "\n", + "\n", + "3. Let $f(x) = x^2$ and $g(x) = e^x$. Show that $f(g(x))$ and $g(f(x))$ is convex for $x \\in \\mathbb{R}$. Also show that if $f(x)$ is any convex function than $h(x) = e^{f(x)}$ is convex.\n", + "\n", + "4. A norm is any function that satisfy the following properties\n", + "\n", + " * $f(\\alpha x) = |\\alpha| f(x)$ for all $\\alpha \\in \\mathbb{R}$.\n", + "\n", + " * $f(x+y) \\leq f(x) + f(y)$\n", + "\n", + " * $f(x) \\leq 0$ for all $x \\in \\mathbb{R}^n$ with equality if and only if $x = 0$\n", + "\n", + "\n", + "Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this).\n", + "\n", + "\n", + "\n", + "\n", + "## Revisiting our first homework\n", + "\n", + "We will use linear regression as a case study for the gradient descent\n", + "methods. Linear regression is a great test case for the gradient\n", + "descent methods discussed in the lectures since it has several\n", + "desirable properties such as:\n", + "\n", + "1. An analytical solution (recall homework set 1).\n", + "\n", + "2. The gradient can be computed analytically.\n", + "\n", + "3. The cost function is convex which guarantees that gradient descent converges for small enough learning rates\n", + "\n", + "We revisit the example from homework set 1 where we had" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i = 5x_i^2 + 0.1\\xi_i, \\ i=1,\\cdots,100\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $x_i \\in [0,1] $ chosen randomly with a uniform distribution. Additionally $\\xi_i$ represents stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n", + "The linear regression model is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "h_\\beta(x) = \\hat{y} = \\beta_0 + \\beta_1 x,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "such that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{y}_i = \\beta_0 + \\beta_1 x_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "## Gradient descent example\n", + "\n", + "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\hat{y}} = (\\hat{y}_1,\\cdots,\\hat{y}_n)^T$ and $\\beta = (\\beta_0, \\beta_1)^T$\n", + "\n", + "It is convenient to write $\\mathbf{\\hat{y}} = X\\beta$ where $X \\in \\mathbb{R}^{100 \\times 2} $ is the design matrix given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "X \\equiv \\begin{bmatrix}\n", + "1 & x_1 \\\\\n", + "\\vdots & \\vdots \\\\\n", + "1 & x_{100} & \\\\\n", + "\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The loss function is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\beta) = ||X\\beta-\\mathbf{y}||^2 = ||X\\beta||^2 - 2 \\mathbf{y}^T X\\beta + ||\\mathbf{y}||^2 = \\sum_{i=1}^{100} (\\beta_0 + \\beta_1 x_i)^2 - 2 y_i (\\beta_0 + \\beta_1 x_i) + y_i^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and we want to find $\\beta$ such that $C(\\beta)$ is minimized.\n", + "\n", + "## The derivative of the cost/loss function\n", + "\n", + "Computing $\\partial C(\\beta) / \\partial \\beta_0$ and $\\partial C(\\beta) / \\partial \\beta_1$ we can show that the gradient can be written as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\nabla_{\\beta} C(\\beta) = (\\partial C(\\beta) / \\partial \\beta_0, \\partial C(\\beta) / \\partial \\beta_1)^T = 2\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", + "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n", + "\\end{bmatrix} = 2X^T(X\\beta - \\mathbf{y}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $X$ is the design matrix defined above.\n", + "\n", + "## The Hessian matrix\n", + "The Hessian matrix of $C(\\beta)$ is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{H} \\equiv \\begin{bmatrix}\n", + "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0^2} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} \\\\\n", + "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_1^2} & \\\\\n", + "\\end{bmatrix} = 2X^T X.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This result implies that $C(\\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite.\n", + "\n", + "\n", + "\n", + "\n", + "## Simple program\n", + "\n", + "We can now write a program that minimizes $C(\\beta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\beta_{k+1} = \\beta_k - \\gamma \\nabla_\\beta C(\\beta_k), \\ k=0,1,\\cdots\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use the expression we computed for the gradient and let use a\n", + "$\\beta_0$ be chosen randomly and let $\\gamma = 0.001$. Stop iterating\n", + "when $||\\nabla_\\beta C(\\beta_k) || \\leq \\epsilon = 10^{-8}$. \n", + "\n", + "And finally we can compare our solution for $\\beta$ with the analytic result given by \n", + "$\\beta= (X^TX)^{-1} X^T \\mathbf{y}$.\n", + "\n", + "## Gradient Descent Example\n", + "\n", + "Here our simple example" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "\n", + "# Importing various packages\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.mplot3d import Axes3D\n", + "from matplotlib import cm\n", + "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", + "import sys\n", + "\n", + "# the number of datapoints\n", + "m = 100\n", + "x = 2*np.random.rand(m,1)\n", + "y = 4+3*x+np.random.randn(m,1)\n", + "\n", + "xb = np.c_[np.ones((m,1)), x]\n", + "beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", + "print(beta_linreg)\n", + "beta = np.random.randn(2,1)\n", + "\n", + "eta = 0.1\n", + "Niterations = 1000\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/m*xb.T.dot(xb.dot(beta)-y)\n", + " beta -= eta*gradients\n", + "\n", + "print(beta)\n", + "xnew = np.array([[0],[2]])\n", + "xbnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = xbnew.dot(beta)\n", + "ypredict2 = xbnew.dot(beta_linreg)\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Gradient descent example')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## And a corresponding example using **scikit-learn**" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import SGDRegressor\n", + "\n", + "x = 2*np.random.rand(100,1)\n", + "y = 4+3*x+np.random.randn(100,1)\n", + "\n", + "xb = np.c_[np.ones((100,1)), x]\n", + "beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", + "print(beta_linreg)\n", + "sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)\n", + "sgdreg.fit(x,y.ravel())\n", + "print(sgdreg.intercept_, sgdreg.coef_)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "## Gradient descent and Ridge\n", + "\n", + "We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\\beta$," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C_{\\text{ridge}}(\\beta) = ||X\\beta -\\mathbf{y}||^2 + \\lambda ||\\beta||^2, \\ \\lambda \\geq 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In order to minimize $C_{\\text{ridge}}(\\beta)$ using GD we only have adjust the gradient as follows" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\nabla_\\beta C_{\\text{ridge}}(\\beta) = 2\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", + "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n", + "\\end{bmatrix} + 2\\lambda\\begin{bmatrix} \\beta_0 \\\\ \\beta_1\\end{bmatrix} = 2 (X^T(X\\beta - \\mathbf{y})+\\lambda \\beta).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can easily extend our program to minimize $C_{\\text{ridge}}(\\beta)$ using gradient descent and compare with the analytical solution given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\beta_{\\text{ridge}} = \\left(X^T X + \\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Program example for gradient descent with Ridge Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.mplot3d import Axes3D\n", + "from matplotlib import cm\n", + "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", + "import sys\n", + "\n", + "# the number of datapoints\n", + "m = 100\n", + "x = 2*np.random.rand(m,1)\n", + "y = 4+3*x+np.random.randn(m,1)\n", + "\n", + "xb = np.c_[np.ones((m,1)), x]\n", + "XT_X = xb.T @ xb\n", + "\n", + "#Ridge parameter lambda\n", + "lmbda = 0.001\n", + "Id = lmbda* np.eye(XT_X.shape[0])\n", + "\n", + "beta_linreg = np.linalg.inv(XT_X+Id) @ xb.T @ y\n", + "print(beta_linreg)\n", + "# Start plain gradient descent\n", + "beta = np.random.randn(2,1)\n", + "\n", + "eta = 0.1\n", + "Niterations = 100\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/m*xb.T @ (xb @ (beta)-y)+2*lmbda*beta\n", + " beta -= eta*gradients\n", + "\n", + "print(beta)\n", + "ypredict = xb @ beta\n", + "ypredict2 = xb @ beta_linreg\n", + "plt.plot(x, ypredict, \"r-\")\n", + "plt.plot(x, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Gradient descent example for Ridge')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using gradient descent methods, limitations\n", + "\n", + "* **Gradient descent (GD) finds local minima of our function**. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our energy function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n", + "\n", + "* **GD is sensitive to initial conditions**. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.\n", + "\n", + "* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the energy function is a sum of terms, with one term for each data point. For example, in linear regression, $E \\propto \\sum_{i=1}^n (y_i - \\mathbf{w}^T\\cdot\\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called \"mini batches\". This has the added benefit of introducing stochasticity into our algorithm.\n", + "\n", + "* **GD is very sensitive to choices of learning rates**. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.\n", + "\n", + "* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n", + "\n", + "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points.\n", + "\n", + "## Friday September 25\n", + "\n", + "\n", + "## Stochastic Gradient Descent\n", + "\n", + "Stochastic gradient descent (SGD) and variants thereof address some of\n", + "the shortcomings of the Gradient descent method discussed above.\n", + "\n", + "The underlying idea of SGD comes from the observation that the cost\n", + "function, which we want to minimize, can almost always be written as a\n", + "sum over $n$ data points $\\{\\mathbf{x}_i\\}_{i=1}^n$," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Computation of gradients\n", + "\n", + "This in turn means that the gradient can be\n", + "computed as a sum over $i$-gradients" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Stochasticity/randomness is introduced by only taking the\n", + "gradient on a subset of the data called minibatches. If there are $n$\n", + "data points and the size of each minibatch is $M$, there will be $n/M$\n", + "minibatches. We denote these minibatches by $B_k$ where\n", + "$k=1,\\cdots,n/M$.\n", + "\n", + "## SGD example\n", + "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", + "and we choose to have $M=5$ minibathces,\n", + "then each minibatch contains two data points. In particular we have\n", + "$B_1 = (\\mathbf{x}_1,\\mathbf{x}_2), \\cdots, B_5 =\n", + "(\\mathbf{x}_9,\\mathbf{x}_{10})$. Note that if you choose $M=1$ you\n", + "have only a single batch with all data points and on the other extreme,\n", + "you may choose $M=n$ resulting in a minibatch for each datapoint, i.e\n", + "$B_k = \\mathbf{x}_k$.\n", + "\n", + "The idea is now to approximate the gradient by replacing the sum over\n", + "all data points with a sum over the data points in one the minibatches\n", + "picked at random in each gradient descent step" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\nabla_{\\beta}\n", + "C(\\mathbf{\\beta}) = \\sum_{i=1}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta}) \\rightarrow \\sum_{i \\in B_k}^n \\nabla_\\beta\n", + "c_i(\\mathbf{x}_i, \\mathbf{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The gradient step\n", + "\n", + "Thus a gradient descent step now looks like" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", + "\\mathbf{\\beta})\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $k$ is picked at random with equal\n", + "probability from $[1,n/M]$. An iteration over the number of\n", + "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n", + "typical to choose a number of epochs and for each epoch iterate over\n", + "the number of minibatches, as exemplified in the code below.\n", + "\n", + "## Simple example code" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np \n", + "\n", + "n = 100 #100 datapoints \n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "n_epochs = 10 #number of epochs\n", + "\n", + "j = 0\n", + "for epoch in range(1,n_epochs+1):\n", + " for i in range(m):\n", + " k = np.random.randint(m) #Pick the k-th minibatch at random\n", + " #Compute the gradient using the data in minibatch Bk\n", + " #Compute new suggestion for \n", + " j += 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Taking the gradient only on a subset of the data has two important\n", + "benefits. First, it introduces randomness which decreases the chance\n", + "that our opmization scheme gets stuck in a local minima. Second, if\n", + "the size of the minibatches are small relative to the number of\n", + "datapoints ($M < n$), the computation of the gradient is much\n", + "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n", + "all $n$ datapoints.\n", + "\n", + "## When do we stop?\n", + "\n", + "A natural question is when do we stop the search for a new minimum?\n", + "One possibility is to compute the full gradient after a given number\n", + "of epochs and check if the norm of the gradient is smaller than some\n", + "threshold and stop if true. However, the condition that the gradient\n", + "is zero is valid also for local minima, so this would only tell us\n", + "that we are close to a local/global minimum. However, we could also\n", + "evaluate the cost function at this point, store the result and\n", + "continue the search. If the test kicks in at a later stage we can\n", + "compare the values of the cost function and keep the $\\beta$ that\n", + "gave the lowest value.\n", + "\n", + "## Slightly different approach\n", + "\n", + "Another approach is to let the step length $\\gamma_j$ depend on the\n", + "number of epochs in such a way that it becomes very small after a\n", + "reasonable time such that we do not move at all.\n", + "\n", + "As an example, let $e = 0,1,2,3,\\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \\cdot m + i$ where $m$ is the number of minibatches and $i=0,\\cdots,m-1$. Then the function $$\\gamma_j(t; t_0, t_1) = \\frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.\n", + "\n", + "In this way we can fix the number of epochs, compute $\\beta$ and\n", + "evaluate the cost function at the end. Repeating the computation will\n", + "give a different result since the scheme is random by design. Then we\n", + "pick the final $\\beta$ that gives the lowest value of the cost\n", + "function." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np \n", + "\n", + "def step_length(t,t0,t1):\n", + " return t0/(t+t1)\n", + "\n", + "n = 100 #100 datapoints \n", + "M = 5 #size of each minibatch\n", + "m = int(n/M) #number of minibatches\n", + "n_epochs = 500 #number of epochs\n", + "t0 = 1.0\n", + "t1 = 10\n", + "\n", + "gamma_j = t0/t1\n", + "j = 0\n", + "for epoch in range(1,n_epochs+1):\n", + " for i in range(m):\n", + " k = np.random.randint(m) #Pick the k-th minibatch at random\n", + " #Compute the gradient using the data in minibatch Bk\n", + " #Compute new suggestion for beta\n", + " t = epoch*m+i\n", + " gamma_j = step_length(t,t0,t1)\n", + " j += 1\n", + "\n", + "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Program for stochastic gradient" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "from math import exp, sqrt\n", + "from random import random, seed\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import SGDRegressor\n", + "\n", + "m = 100\n", + "x = 2*np.random.rand(m,1)\n", + "y = 4+3*x+np.random.randn(m,1)\n", + "\n", + "xb = np.c_[np.ones((m,1)), x]\n", + "theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", + "print(\"Own inversion\")\n", + "print(theta_linreg)\n", + "sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)\n", + "sgdreg.fit(x,y.ravel())\n", + "print(\"sgdreg from scikit\")\n", + "print(sgdreg.intercept_, sgdreg.coef_)\n", + "\n", + "\n", + "theta = np.random.randn(2,1)\n", + "eta = 0.1\n", + "Niterations = 1000\n", + "\n", + "\n", + "for iter in range(Niterations):\n", + " gradients = 2.0/m*xb.T @ ((xb @ theta)-y)\n", + " theta -= eta*gradients\n", + "print(\"theta frm own gd\")\n", + "print(theta)\n", + "\n", + "xnew = np.array([[0],[2]])\n", + "xbnew = np.c_[np.ones((2,1)), xnew]\n", + "ypredict = xbnew.dot(theta)\n", + "ypredict2 = xbnew.dot(theta_linreg)\n", + "\n", + "\n", + "n_epochs = 50\n", + "t0, t1 = 5, 50\n", + "def learning_schedule(t):\n", + " return t0/(t+t1)\n", + "\n", + "theta = np.random.randn(2,1)\n", + "\n", + "for epoch in range(n_epochs):\n", + " for i in range(m):\n", + " random_index = np.random.randint(m)\n", + " xi = xb[random_index:random_index+1]\n", + " yi = y[random_index:random_index+1]\n", + " gradients = 2 * xi.T @ ((xi @ theta)-yi)\n", + " eta = learning_schedule(epoch*m+i)\n", + " theta = theta - eta*gradients\n", + "print(\"theta from own sdg\")\n", + "print(theta)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(xnew, ypredict2, \"b-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,2.0,0, 15.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Random numbers ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Challenge**: try to write a similar code for a Logistic Regression case.\n", + "\n", + "\n", + "## Momentum based GD\n", + "\n", + "The stochastic gradient descent (SGD) is almost always used with a\n", + "*momentum* or inertia term that serves as a memory of the direction we\n", + "are moving in parameter space. This is typically implemented as\n", + "follows" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", + "\\label{_auto1} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have introduced a momentum parameter $\\gamma$, with\n", + "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", + "indicate the gradient is to be taken over a different mini-batch at\n", + "each step. We call this algorithm gradient descent with momentum\n", + "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n", + "running average of recently encountered gradients and\n", + "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n", + "used in the averaging procedure. Consistent with this, when\n", + "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n", + "earlier. An equivalent way of writing the updates is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$.\n", + "\n", + "## More on momentum based approaches\n", + "\n", + "Let us try to get more intuition from these equations. It is helpful\n", + "to consider a simple physical analogy with a particle of mass $m$\n", + "moving in a viscous medium with drag coefficient $\\mu$ and potential\n", + "$E(\\mathbf{w})$. If we denote the particle's position by $\\mathbf{w}$,\n", + "then its motion is described by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can discretize this equation in the usual way to get" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Rearranging this equation, we can rewrite this as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Momentum parameter\n", + "\n", + "Notice that this equation is identical to previous one if we identify\n", + "the position of the particle, $\\mathbf{w}$, with the parameters\n", + "$\\boldsymbol{\\theta}$. This allows us to identify the momentum\n", + "parameter and learning rate with the mass of the particle and the\n", + "viscous drag as:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Thus, as the name suggests, the momentum parameter is proportional to\n", + "the mass of the particle and effectively provides inertia.\n", + "Furthermore, in the large viscosity/small learning rate limit, our\n", + "memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n", + "\n", + "Why is momentum useful? SGD momentum helps the gradient descent\n", + "algorithm gain speed in directions with persistent but small gradients\n", + "even in the presence of stochasticity, while suppressing oscillations\n", + "in high-curvature directions. This becomes especially important in\n", + "situations where the landscape is shallow and flat in some directions\n", + "and narrow and steep in others. It has been argued that first-order\n", + "methods (with appropriate initial conditions) can perform comparable\n", + "to more expensive second order methods, especially in the context of\n", + "complex deep learning models.\n", + "\n", + "These beneficial properties of momentum can sometimes become even more\n", + "pronounced by using a slight modification of the classical momentum\n", + "algorithm called Nesterov Accelerated Gradient (NAG).\n", + "\n", + "In the NAG algorithm, rather than calculating the gradient at the\n", + "current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one\n", + "calculates the gradient at the expected value of the parameters given\n", + "our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma\n", + "\\mathbf{v}_{t-1})$. This yields the NAG update rule" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n", + "\\label{_auto2} \\tag{3}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$.\n", + "\n", + "\n", + "## Second moment of the gradient\n", + "\n", + "\n", + "In stochastic gradient descent, with and without momentum, we still\n", + "have to specify a schedule for tuning the learning rates $\\eta_t$\n", + "as a function of time. As discussed in the context of Newton's\n", + "method, this presents a number of dilemmas. The learning rate is\n", + "limited by the steepest direction which can change depending on the\n", + "current position in the landscape. To circumvent this problem, ideally\n", + "our algorithm would keep track of curvature and take large steps in\n", + "shallow, flat directions and small steps in steep, narrow directions.\n", + "Second-order methods accomplish this by calculating or approximating\n", + "the Hessian and normalizing the learning rate by the\n", + "curvature. However, this is very computationally expensive for\n", + "extremely large models. Ideally, we would like to be able to\n", + "adaptively change the step size to match the landscape without paying\n", + "the steep computational price of calculating or approximating\n", + "Hessians.\n", + "\n", + "Recently, a number of methods have been introduced that accomplish\n", + "this by tracking not only the gradient, but also the second moment of\n", + "the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and\n", + "ADAM.\n", + "\n", + "## RMS prop\n", + "\n", + "In RMS prop, in addition to keeping a running average of the first\n", + "moment of the gradient, we also keep track of the second moment\n", + "denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule\n", + "for RMS prop is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", + "\\label{_auto3} \\tag{4}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\beta$ controls the averaging time of the second moment and is\n", + "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n", + "typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a\n", + "small regularization constant to prevent divergences. Multiplication\n", + "and division by vectors is understood as an element-wise operation. It\n", + "is clear from this formula that the learning rate is reduced in\n", + "directions where the norm of the gradient is consistently large. This\n", + "greatly speeds up the convergence by allowing us to use a larger\n", + "learning rate for flat directions.\n", + "\n", + "\n", + "## ADAM optimizer\n", + "\n", + "A related algorithm is the ADAM optimizer. In ADAM, we keep a running\n", + "average of both the first and second moment of the gradient and use\n", + "this information to adaptively change the learning rate for different\n", + "parameters. In addition to keeping a running average of the first and\n", + "second moments of the gradient\n", + "(i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and\n", + "$\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM\n", + "performs an additional bias correction to account for the fact that we\n", + "are estimating the first two moments of the gradient using a running\n", + "average (denoted by the hats in the update rule below). The update\n", + "rule for ADAM is given by (where multiplication and division are once\n", + "again understood to be element-wise operations below)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", + "\\label{_auto4} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\hat{\\mathbf{m}}_t \\over \\sqrt{\\hat{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\label{_auto5} \\tag{6}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n", + "second moment and are typically taken to be $0.9$ and $0.99$\n", + "respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n", + "\n", + "Like in RMSprop, the effective step size of a parameter depends on the\n", + "magnitude of its gradient squared. To understand this better, let us\n", + "rewrite this expression in terms of the variance\n", + "$\\boldsymbol{\\sigma}_t^2 = \\hat{\\mathbf{s}}_t -\n", + "(\\hat{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The\n", + "update rule for this parameter is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\Delta \\theta_{t+1}= -\\eta_t { \\hat{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Practical tips\n", + "\n", + "* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n", + "\n", + "* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the energy matrix is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n", + "\n", + "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", + "\n", + "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n", + "\n", + "Geron's text, see chapter 11, has several interesting discussions.\n", + "\n", + "\n", + "\n", + "## Automatic differentiation\n", + "\n", + "[Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation), \n", + "also called algorithmic\n", + "differentiation or computational differentiation,is a set of\n", + "techniques to numerically evaluate the derivative of a function\n", + "specified by a computer program. AD exploits the fact that every\n", + "computer program, no matter how complicated, executes a sequence of\n", + "elementary arithmetic operations (addition, subtraction,\n", + "multiplication, division, etc.) and elementary functions (exp, log,\n", + "sin, cos, etc.). By applying the chain rule repeatedly to these\n", + "operations, derivatives of arbitrary order can be computed\n", + "automatically, accurately to working precision, and using at most a\n", + "small constant factor more arithmetic operations than the original\n", + "program.\n", + "\n", + "Automatic differentiation is neither:\n", + "\n", + "* Symbolic differentiation, nor\n", + "\n", + "* Numerical differentiation (the method of finite differences).\n", + "\n", + "Symbolic differentiation can lead to inefficient code and faces the\n", + "difficulty of converting a computer program into a single expression,\n", + "while numerical differentiation can introduce round-off errors in the\n", + "discretization process and cancellation\n", + "\n", + "\n", + "\n", + "Python has tools for so-called **automatic differentiation**.\n", + "Consider the following example" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which has the following derivative" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using **autograd** we have" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "\n", + "# To do elementwise differentiation:\n", + "from autograd import elementwise_grad as egrad \n", + "\n", + "# To plot:\n", + "import matplotlib.pyplot as plt \n", + "\n", + "\n", + "def f(x):\n", + " return np.sin(2*np.pi*x + x**2)\n", + "\n", + "def f_grad_analytic(x):\n", + " return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)\n", + "\n", + "# Do the comparison:\n", + "x = np.linspace(0,1,1000)\n", + "\n", + "f_grad = egrad(f)\n", + "\n", + "computed = f_grad(x)\n", + "analytic = f_grad_analytic(x)\n", + "\n", + "plt.title('Derivative computed from Autograd compared with the analytical derivative')\n", + "plt.plot(x,computed,label='autograd')\n", + "plt.plot(x,analytic,label='analytic')\n", + "\n", + "plt.xlabel('x')\n", + "plt.ylabel('y')\n", + "plt.legend()\n", + "\n", + "plt.show()\n", + "\n", + "print(\"The max absolute difference is: %g\"%(np.max(np.abs(computed - analytic))))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "## Using autograd\n", + "\n", + "Here we\n", + "experiment with what kind of functions Autograd is capable\n", + "of finding the gradient of. The following Python functions are just\n", + "meant to illustrate what Autograd can do, but please feel free to\n", + "experiment with other, possibly more complicated, functions as well." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "\n", + "def f1(x):\n", + " return x**3 + 1\n", + "\n", + "f1_grad = grad(f1)\n", + "\n", + "# Remember to send in float as argument to the computed gradient from Autograd!\n", + "a = 1.0\n", + "\n", + "# See the evaluated gradient at a using autograd:\n", + "print(\"The gradient of f1 evaluated at a = %g using autograd is: %g\"%(a,f1_grad(a)))\n", + "\n", + "# Compare with the analytical derivative, that is f1'(x) = 3*x**2 \n", + "grad_analytical = 3*a**2\n", + "print(\"The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g\"%(a,grad_analytical))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Autograd with more complicated functions\n", + "\n", + "To differentiate with respect to two (or more) arguments of a Python\n", + "function, Autograd need to know at which variable the function if\n", + "being differentiated with respect to." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f2(x1,x2):\n", + " return 3*x1**3 + x2*(x1 - 5) + 1\n", + "\n", + "# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1\n", + "f2_grad_x1 = grad(f2,0)\n", + "\n", + "# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad\n", + "f2_grad_x2 = grad(f2,1)\n", + "\n", + "x1 = 1.0\n", + "x2 = 3.0 \n", + "\n", + "print(\"Evaluating at x1 = %g, x2 = %g\"%(x1,x2))\n", + "print(\"-\"*30)\n", + "\n", + "# Compare with the analytical derivatives:\n", + "\n", + "# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:\n", + "f2_grad_x1_analytical = 9*x1**2 + x2\n", + "\n", + "# Derivative of f2 w.r.t x2 is: x1 - 5:\n", + "f2_grad_x2_analytical = x1 - 5\n", + "\n", + "# See the evaluated derivations:\n", + "print(\"The derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n", + "print(\"The analytical derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n", + "\n", + "print()\n", + "\n", + "print(\"The derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))\n", + "print(\"The analytical derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable.\n", + "\n", + "\n", + "## More complicated functions using the elements of their arguments directly" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f3(x): # Assumes x is an array of length 5 or higher\n", + " return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2\n", + "\n", + "f3_grad = grad(f3)\n", + "\n", + "x = np.linspace(0,4,5)\n", + "\n", + "# Print the computed gradient:\n", + "print(\"The computed gradient of f3 is: \", f3_grad(x))\n", + "\n", + "# The analytical gradient is: (2, 3, 5, 7, 22*x[4])\n", + "f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])\n", + "\n", + "# Print the analytical gradient:\n", + "print(\"The analytical gradient of f3 is: \", f3_grad_analytical)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that in this case, when sending an array as input argument, the\n", + "output from Autograd is another array. This is the true gradient of\n", + "the function, as opposed to the function in the previous example. By\n", + "using arrays to represent the variables, the output from Autograd\n", + "might be easier to work with, as the output is closer to what one\n", + "could expect form a gradient-evaluting function.\n", + "\n", + "\n", + "## Functions using mathematical functions from Numpy" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f4(x):\n", + " return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)\n", + "\n", + "f4_grad = grad(f4)\n", + "\n", + "x = 2.7\n", + "\n", + "# Print the computed derivative:\n", + "print(\"The computed derivative of f4 at x = %g is: %g\"%(x,f4_grad(x)))\n", + "\n", + "# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi\n", + "f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi\n", + "\n", + "# Print the analytical gradient:\n", + "print(\"The analytical gradient of f4 at x = %g is: %g\"%(x,f4_grad_analytical))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## More autograd" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f5(x):\n", + " if x >= 0:\n", + " return x**2\n", + " else:\n", + " return -3*x + 1\n", + "\n", + "f5_grad = grad(f5)\n", + "\n", + "x = 2.7\n", + "\n", + "# Print the computed derivative:\n", + "print(\"The computed derivative of f5 at x = %g is: %g\"%(x,f5_grad(x)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## And with loops" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1\n", + "2\n", + " \n", + "<\n", + "<\n", + "<\n", + "!\n", + "!\n", + "C\n", + "O\n", + "D\n", + "E\n", + "_\n", + "B\n", + "L\n", + "O\n", + "C\n", + "K\n", + " \n", + " \n", + "p\n", + "y\n", + "c\n", + "o\n", + "d" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9\n", + "# The analytical derivative is: sum(i*x**(i-1)) \n", + "f6_grad_analytical = 0\n", + "for i in range(10):\n", + " f6_grad_analytical += i*x**(i-1)\n", + "\n", + "print(\"The analytical derivative of f6 at x = %g is: %g\"%(x,f6_grad_analytical))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using recursion" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "\n", + "def f7(n): # Assume that n is an integer\n", + " if n == 1 or n == 0:\n", + " return 1\n", + " else:\n", + " return n*f7(n-1)\n", + "\n", + "f7_grad = grad(f7)\n", + "\n", + "n = 2.0\n", + "\n", + "print(\"The computed derivative of f7 at n = %d is: %g\"%(n,f7_grad(n)))\n", + "\n", + "# The function f7 is an implementation of the factorial of n.\n", + "# By using the product rule, one can find that the derivative is:\n", + "\n", + "f7_grad_analytical = 0\n", + "for i in range(int(n)-1):\n", + " tmp = 1\n", + " for k in range(int(n)-1):\n", + " if k != i:\n", + " tmp *= (n - k)\n", + " f7_grad_analytical += tmp\n", + "\n", + "print(\"The analytical derivative of f7 at n = %d is: %g\"%(n,f7_grad_analytical))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input.\n", + "\n", + "## Unsupported functions\n", + "Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.\n", + "\n", + "Assigning a value to the variable being differentiated with respect to" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f8(x): # Assume x is an array\n", + " x[2] = 3\n", + " return x*2\n", + "\n", + "f8_grad = grad(f8)\n", + "\n", + "x = 8.4\n", + "\n", + "print(\"The derivative of f8 is:\",f8_grad(x))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible.\n", + "\n", + "## The syntax a.dot(b) when finding the dot product" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f9(a): # Assume a is an array with 2 elements\n", + " b = np.array([1.0,2.0])\n", + " return a.dot(b)\n", + "\n", + "f9_grad = grad(f9)\n", + "\n", + "x = np.array([1.0,0.0])\n", + "\n", + "print(\"The derivative of f9 is:\",f9_grad(x))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we are told that the 'dot' function does not belong to Autograd's\n", + "version of a Numpy array. To overcome this, an alternative syntax\n", + "which also computed the dot product can be used:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "from autograd import grad\n", + "def f9_alternative(x): # Assume a is an array with 2 elements\n", + " b = np.array([1.0,2.0])\n", + " return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2\n", + "\n", + "f9_alternative_grad = grad(f9_alternative)\n", + "\n", + "x = np.array([3.0,0.0])\n", + "\n", + "print(\"The gradient of f9 is:\",f9_alternative_grad(x))\n", + "\n", + "# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively\n", + "# w.r.t x is (b_1, b_2)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Recommended to avoid\n", + "The documentation recommends to avoid inplace operations such as" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "a += b\n", + "a -= b\n", + "a*= b\n", + "a /=b" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Standard steepest descent\n", + "\n", + "\n", + "Before we proceed, we would like to discuss the approach called the\n", + "**standard Steepest descent**, which again leads to us having to be able\n", + "to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG).\n", + "\n", + "[The success of the CG method](https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf)\n", + "for finding solutions of non-linear problems is based on the theory\n", + "of conjugate gradients for linear systems of equations. It belongs to\n", + "the class of iterative methods for solving problems from linear\n", + "algebra of the type" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{A}\\hat{x} = \\hat{b}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the iterative process we end up with a problem like" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{r}= \\hat{b}-\\hat{A}\\hat{x},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\hat{r}$ is the so-called residual or error in the iterative process.\n", + "\n", + "When we have found the exact solution, $\\hat{r}=0$.\n", + "\n", + "## Gradient method\n", + "\n", + "The residual is zero when we reach the minimum of the quadratic equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "P(\\hat{x})=\\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T\\hat{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with the constraint that the matrix $\\hat{A}$ is positive definite and\n", + "symmetric. This defines also the Hessian and we want it to be positive definite. \n", + "\n", + "\n", + "## Steepest descent method\n", + "\n", + "We denote the initial guess for $\\hat{x}$ as $\\hat{x}_0$. \n", + "We can assume without loss of generality that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{x}_0=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or consider the system" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{A}\\hat{z} = \\hat{b}-\\hat{A}\\hat{x}_0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "instead.\n", + "\n", + "\n", + "## Steepest descent method\n", + "One can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(\\hat{x}) = \\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T \\hat{x} , \\quad \\hat{x}\\in\\mathbf{R}^n.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This suggests taking the first basis vector $\\hat{r}_1$ (see below for definition) \n", + "to be the gradient of $f$ at $\\hat{x}=\\hat{x}_0$, \n", + "which equals" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{A}\\hat{x}_0-\\hat{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and \n", + "$\\hat{x}_0=0$ it is equal $-\\hat{b}$.\n", + "\n", + "\n", + "\n", + "## Final expressions\n", + "We can compute the residual iteratively as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{r}_{k+1}=\\hat{b}-\\hat{A}\\hat{x}_{k+1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which equals" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{b}-\\hat{A}(\\hat{x}_k+\\alpha_k\\hat{r}_k),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\hat{b}-\\hat{A}\\hat{x}_k)-\\alpha_k\\hat{A}\\hat{r}_k,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which gives" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\alpha_k = \\frac{\\hat{r}_k^T\\hat{r}_k}{\\hat{r}_k^T\\hat{A}\\hat{r}_k}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "leading to the iterative scheme" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{x}_{k+1}=\\hat{x}_k-\\alpha_k\\hat{r}_{k},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Code examples for steepest descent\n", + "\n", + "## Simple codes for steepest descent and conjugate gradient using a $2\\times 2$ matrix, in c++, Python code to come" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " #include \n", + " #include \n", + " #include \n", + " #include \n", + " #include \"vectormatrixclass.h\"\n", + " using namespace std;\n", + " // Main function begins here\n", + " int main(int argc, char * argv[]){\n", + " int dim = 2;\n", + " Vector x(dim),xsd(dim), b(dim),x0(dim);\n", + " Matrix A(dim,dim);\n", + " \n", + " // Set our initial guess\n", + " x0(0) = x0(1) = 0;\n", + " // Set the matrix\n", + " A(0,0) = 3; A(1,0) = 2; A(0,1) = 2; A(1,1) = 6;\n", + " b(0) = 2; b(1) = -8;\n", + " cout << \"The Matrix A that we are using: \" << endl;\n", + " A.Print();\n", + " cout << endl;\n", + " xsd = SteepestDescent(A,b,x0);\n", + " cout << \"The approximate solution using Steepest Descent is: \" << endl;\n", + " xsd.Print();\n", + " cout << endl;\n", + " }\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The routine for the steepest descent method" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " Vector SteepestDescent(Matrix A, Vector b, Vector x0){\n", + " int IterMax, i;\n", + " int dim = x0.Dimension();\n", + " const double tolerance = 1.0e-14;\n", + " Vector x(dim),f(dim),z(dim);\n", + " double c,alpha,d;\n", + " IterMax = 30;\n", + " x = x0;\n", + " r = A*x-b;\n", + " i = 0;\n", + " while (i <= IterMax){\n", + " z = A*r;\n", + " c = dot(r,r);\n", + " alpha = c/dot(r,z);\n", + " x = x - alpha*r;\n", + " r = A*x-b;\n", + " if(sqrt(dot(r,r)) < tolerance) break;\n", + " i++;\n", + " }\n", + " return x;\n", + " }\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Steepest descent example" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import numpy.linalg as la\n", + "\n", + "import scipy.optimize as sopt\n", + "\n", + "import matplotlib.pyplot as pt\n", + "from mpl_toolkits.mplot3d import axes3d\n", + "\n", + "def f(x):\n", + " return 0.5*x[0]**2 + 2.5*x[1]**2\n", + "\n", + "def df(x):\n", + " return np.array([x[0], 5*x[1]])\n", + "\n", + "fig = pt.figure()\n", + "ax = fig.gca(projection=\"3d\")\n", + "\n", + "xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]\n", + "fmesh = f(np.array([xmesh, ymesh]))\n", + "ax.plot_surface(xmesh, ymesh, fmesh)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And then as countor plot" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pt.axis(\"equal\")\n", + "pt.contour(xmesh, ymesh, fmesh)\n", + "guesses = [np.array([2, 2./5])]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Find guesses" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = guesses[-1]\n", + "s = -df(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Run it!" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def f1d(alpha):\n", + " return f(x + alpha*s)\n", + "\n", + "alpha_opt = sopt.golden(f1d)\n", + "next_guess = x + alpha_opt * s\n", + "guesses.append(next_guess)\n", + "print(next_guess)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What happened?" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pt.axis(\"equal\")\n", + "pt.contour(xmesh, ymesh, fmesh, 50)\n", + "it_array = np.array(guesses)\n", + "pt.plot(it_array.T[0], it_array.T[1], \"x-\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conjugate gradient method\n", + "In the CG method we define so-called conjugate directions and two vectors \n", + "$\\hat{s}$ and $\\hat{t}$\n", + "are said to be\n", + "conjugate if" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{s}^T\\hat{A}\\hat{t}= 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The philosophy of the CG method is to perform searches in various conjugate directions\n", + "of our vectors $\\hat{x}_i$ obeying the above criterion, namely" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{x}_i^T\\hat{A}\\hat{x}_j= 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Two vectors are conjugate if they are orthogonal with respect to \n", + "this inner product. Being conjugate is a symmetric relation: if $\\hat{s}$ is conjugate to $\\hat{t}$, then $\\hat{t}$ is conjugate to $\\hat{s}$.\n", + "\n", + "\n", + "\n", + "## Conjugate gradient method\n", + "An example is given by the eigenvectors of the matrix" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{v}_i^T\\hat{A}\\hat{v}_j= \\lambda\\hat{v}_i^T\\hat{v}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which is zero unless $i=j$.\n", + "\n", + "\n", + "\n", + "\n", + "## Conjugate gradient method\n", + "Assume now that we have a symmetric positive-definite matrix $\\hat{A}$ of size\n", + "$n\\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{x}_{i+1}=\\hat{x}_{i}+\\alpha_i\\hat{p}_{i}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We assume that $\\hat{p}_{i}$ is a sequence of $n$ mutually conjugate directions. \n", + "Then the $\\hat{p}_{i}$ form a basis of $R^n$ and we can expand the solution \n", + "$ \\hat{A}\\hat{x} = \\hat{b}$ in this basis, namely" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{x} = \\sum^{n}_{i=1} \\alpha_i \\hat{p}_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conjugate gradient method\n", + "The coefficients are given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbf{A}\\mathbf{x} = \\sum^{n}_{i=1} \\alpha_i \\mathbf{A} \\mathbf{p}_i = \\mathbf{b}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Multiplying with $\\hat{p}_k^T$ from the left gives" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{p}_k^T \\hat{A}\\hat{x} = \\sum^{n}_{i=1} \\alpha_i\\hat{p}_k^T \\hat{A}\\hat{p}_i= \\hat{p}_k^T \\hat{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and we can define the coefficients $\\alpha_k$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\alpha_k = \\frac{\\hat{p}_k^T \\hat{b}}{\\hat{p}_k^T \\hat{A} \\hat{p}_k}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conjugate gradient method and iterations\n", + "\n", + "If we choose the conjugate vectors $\\hat{p}_k$ carefully, \n", + "then we may not need all of them to obtain a good approximation to the solution \n", + "$\\hat{x}$. \n", + "We want to regard the conjugate gradient method as an iterative method. \n", + "This will us to solve systems where $n$ is so large that the direct \n", + "method would take too much time.\n", + "\n", + "We denote the initial guess for $\\hat{x}$ as $\\hat{x}_0$. \n", + "We can assume without loss of generality that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{x}_0=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or consider the system" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{A}\\hat{z} = \\hat{b}-\\hat{A}\\hat{x}_0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "instead.\n", + "\n", + "\n", + "\n", + "\n", + "## Conjugate gradient method\n", + "One can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(\\hat{x}) = \\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T \\hat{x} , \\quad \\hat{x}\\in\\mathbf{R}^n.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This suggests taking the first basis vector $\\hat{p}_1$ \n", + "to be the gradient of $f$ at $\\hat{x}=\\hat{x}_0$, \n", + "which equals" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{A}\\hat{x}_0-\\hat{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and \n", + "$\\hat{x}_0=0$ it is equal $-\\hat{b}$.\n", + "The other vectors in the basis will be conjugate to the gradient, \n", + "hence the name conjugate gradient method.\n", + "\n", + "\n", + "\n", + "\n", + "## Conjugate gradient method\n", + "Let $\\hat{r}_k$ be the residual at the $k$-th step:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{r}_k=\\hat{b}-\\hat{A}\\hat{x}_k.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that $\\hat{r}_k$ is the negative gradient of $f$ at \n", + "$\\hat{x}=\\hat{x}_k$, \n", + "so the gradient descent method would be to move in the direction $\\hat{r}_k$. \n", + "Here, we insist that the directions $\\hat{p}_k$ are conjugate to each other, \n", + "so we take the direction closest to the gradient $\\hat{r}_k$ \n", + "under the conjugacy constraint. \n", + "This gives the following expression" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{p}_{k+1}=\\hat{r}_k-\\frac{\\hat{p}_k^T \\hat{A}\\hat{r}_k}{\\hat{p}_k^T\\hat{A}\\hat{p}_k} \\hat{p}_k.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conjugate gradient method\n", + "We can also compute the residual iteratively as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{r}_{k+1}=\\hat{b}-\\hat{A}\\hat{x}_{k+1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which equals" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{b}-\\hat{A}(\\hat{x}_k+\\alpha_k\\hat{p}_k),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\hat{b}-\\hat{A}\\hat{x}_k)-\\alpha_k\\hat{A}\\hat{p}_k,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which gives" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{r}_{k+1}=\\hat{r}_k-\\hat{A}\\hat{p}_{k},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simple implementation of the Conjugate gradient algorithm" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " Vector ConjugateGradient(Matrix A, Vector b, Vector x0){\n", + " int dim = x0.Dimension();\n", + " const double tolerance = 1.0e-14;\n", + " Vector x(dim),r(dim),v(dim),z(dim);\n", + " double c,t,d;\n", + " \n", + " x = x0;\n", + " r = b - A*x;\n", + " v = r;\n", + " c = dot(r,r);\n", + " int i = 0; IterMax = dim;\n", + " while(i <= IterMax){\n", + " z = A*v;\n", + " t = c/dot(v,z);\n", + " x = x + t*v;\n", + " r = r - t*z;\n", + " d = dot(r,r);\n", + " if(sqrt(d) < tolerance)\n", + " break;\n", + " v = r + (d/c)*v;\n", + " c = d; i++;\n", + " }\n", + " return x;\n", + " } \n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Broyden–Fletcher–Goldfarb–Shanno algorithm\n", + "The optimization problem is to minimize $f(\\mathbf {x} )$ where $\\mathbf {x}$ is a vector in $R^{n}$, and $f$ is a differentiable scalar function. There are no constraints on the values that $\\mathbf {x}$ can take.\n", + "\n", + "The algorithm begins at an initial estimate for the optimal value $\\mathbf {x}_{0}$ and proceeds iteratively to get a better estimate at each stage.\n", + "\n", + "The search direction $p_k$ at stage $k$ is given by the solution of the analogue of the Newton equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "B_{k}\\mathbf {p} _{k}=-\\nabla f(\\mathbf {x}_{k}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $B_{k}$ is an approximation to the Hessian matrix, which is\n", + "updated iteratively at each stage, and $\\nabla f(\\mathbf {x} _{k})$\n", + "is the gradient of the function\n", + "evaluated at $x_k$. \n", + "A line search in the direction $p_k$ is then used to\n", + "find the next point $x_{k+1}$ by minimising" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(\\mathbf {x}_{k}+\\alpha \\mathbf {p}_{k}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "over the scalar $\\alpha > 0$." + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/pub/week40/ipynb/ipynb-week40-src.tar.gz b/doc/pub/week40/ipynb/ipynb-week40-src.tar.gz new file mode 100644 index 000000000..376809880 Binary files /dev/null and b/doc/pub/week40/ipynb/ipynb-week40-src.tar.gz differ diff --git a/doc/pub/week40/ipynb/week40.ipynb b/doc/pub/week40/ipynb/week40.ipynb new file mode 100644 index 000000000..5783e637b --- /dev/null +++ b/doc/pub/week40/ipynb/week40.ipynb @@ -0,0 +1,3316 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Weeke 40: Neural networks, from the simple perceptron to deep learning\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Neural networks\n", + "\n", + "Artificial neural networks are computational systems that can learn to\n", + "perform tasks by considering examples, generally without being\n", + "programmed with any task-specific rules. It is supposed to mimic a\n", + "biological system, wherein neurons interact by sending signals in the\n", + "form of mathematical functions between layers. All layers can contain\n", + "an arbitrary number of neurons, and each connection is represented by\n", + "a weight variable.\n", + "\n", + "\n", + "## Artificial neurons\n", + "\n", + "The field of artificial neural networks has a long history of\n", + "development, and is closely connected with the advancement of computer\n", + "science and computers in general. A model of artificial neurons was\n", + "first developed by McCulloch and Pitts in 1943 to study signal\n", + "processing in the brain and has later been refined by others. The\n", + "general idea is to mimic neural networks in the human brain, which is\n", + "composed of billions of neurons that communicate with each other by\n", + "sending electrical signals. Each neuron accumulates its incoming\n", + "signals, which must exceed an activation threshold to yield an\n", + "output. If the threshold is not overcome, the neuron remains inactive,\n", + "i.e. has zero output.\n", + "\n", + "This behaviour has inspired a simple mathematical model for an artificial neuron." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y = f\\left(\\sum_{i=1}^n w_ix_i\\right) = f(u)\n", + "\\label{artificialNeuron} \\tag{1}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", + "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", + "\n", + "Conceptually, it is helpful to divide neural networks into four\n", + "categories:\n", + "1. general purpose neural networks for supervised learning,\n", + "\n", + "2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),\n", + "\n", + "3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and\n", + "\n", + "4. neural networks for unsupervised learning such as Deep Boltzmann Machines.\n", + "\n", + "In natural science, DNNs and CNNs have already found numerous\n", + "applications. In statistical physics, they have been applied to detect\n", + "phase transitions in 2D Ising and Potts models, lattice gauge\n", + "theories, and different phases of polymers, or solving the\n", + "Navier-Stokes equation in weather forecasting. Deep learning has also\n", + "found interesting applications in quantum physics. Various quantum\n", + "phase transitions can be detected and studied using DNNs and CNNs,\n", + "topological phases, and even non-equilibrium many-body\n", + "localization. Representing quantum states as DNNs quantum state\n", + "tomography are among some of the impressive achievements to reveal the\n", + "potential of DNNs to facilitate the study of quantum systems.\n", + "\n", + "In quantum information theory, it has been shown that one can perform\n", + "gate decompositions with the help of neural. \n", + "\n", + "The applications are not limited to the natural sciences. There is a\n", + "plethora of applications in essentially all disciplines, from the\n", + "humanities to life science and medicine.\n", + "\n", + "## Neural network types\n", + "\n", + "An artificial neural network (ANN), is a computational model that\n", + "consists of layers of connected neurons, or nodes or units. We will\n", + "refer to these interchangeably as units or nodes, and sometimes as\n", + "neurons.\n", + "\n", + "It is supposed to mimic a biological nervous system by letting each\n", + "neuron interact with other neurons by sending signals in the form of\n", + "mathematical functions between layers. A wide variety of different\n", + "ANNs have been developed, but most of them consist of an input layer,\n", + "an output layer and eventual layers in-between, called *hidden\n", + "layers*. All layers can contain an arbitrary number of nodes, and each\n", + "connection between two nodes is associated with a weight variable.\n", + "\n", + "Neural networks (also called neural nets) are neural-inspired\n", + "nonlinear models for supervised learning. As we will see, neural nets\n", + "can be viewed as natural, more powerful extensions of supervised\n", + "learning methods such as linear and logistic regression and soft-max\n", + "methods we discussed earlier.\n", + "\n", + "\n", + "## Feed-forward neural networks\n", + "\n", + "The feed-forward neural network (FFNN) was the first and simplest type\n", + "of ANNs that were devised. In this network, the information moves in\n", + "only one direction: forward through the layers.\n", + "\n", + "Nodes are represented by circles, while the arrows display the\n", + "connections between the nodes, including the direction of information\n", + "flow. Additionally, each arrow corresponds to a weight variable\n", + "(figure to come). We observe that each node in a layer is connected\n", + "to *all* nodes in the subsequent layer, making this a so-called\n", + "*fully-connected* FFNN.\n", + "\n", + "\n", + "\n", + "## Convolutional Neural Network\n", + "\n", + "A different variant of FFNNs are *convolutional neural networks*\n", + "(CNNs), which have a connectivity pattern inspired by the animal\n", + "visual cortex. Individual neurons in the visual cortex only respond to\n", + "stimuli from small sub-regions of the visual field, called a receptive\n", + "field. This makes the neurons well-suited to exploit the strong\n", + "spatially local correlation present in natural images. The response of\n", + "each neuron can be approximated mathematically as a convolution\n", + "operation. (figure to come)\n", + "\n", + "Convolutional neural networks emulate the behaviour of neurons in the\n", + "visual cortex by enforcing a *local* connectivity pattern between\n", + "nodes of adjacent layers: Each node in a convolutional layer is\n", + "connected only to a subset of the nodes in the previous layer, in\n", + "contrast to the fully-connected FFNN. Often, CNNs consist of several\n", + "convolutional layers that learn local features of the input, with a\n", + "fully-connected layer at the end, which gathers all the local data and\n", + "produces the outputs. They have wide applications in image and video\n", + "recognition.\n", + "\n", + "## Recurrent neural networks\n", + "\n", + "So far we have only mentioned ANNs where information flows in one\n", + "direction: forward. *Recurrent neural networks* on the other hand,\n", + "have connections between nodes that form directed *cycles*. This\n", + "creates a form of internal memory which are able to capture\n", + "information on what has been calculated before; the output is\n", + "dependent on the previous computations. Recurrent NNs make use of\n", + "sequential information by performing the same task for every element\n", + "in a sequence, where each element depends on previous elements. An\n", + "example of such information is sentences, making recurrent NNs\n", + "especially well-suited for handwriting and speech recognition.\n", + "\n", + "## Other types of networks\n", + "\n", + "There are many other kinds of ANNs that have been developed. One type\n", + "that is specifically designed for interpolation in multidimensional\n", + "space is the radial basis function (RBF) network. RBFs are typically\n", + "made up of three layers: an input layer, a hidden layer with\n", + "non-linear radial symmetric activation functions and a linear output\n", + "layer (''linear'' here means that each node in the output layer has a\n", + "linear activation function). The layers are normally fully-connected\n", + "and there are no cycles, thus RBFs can be viewed as a type of\n", + "fully-connected FFNN. They are however usually treated as a separate\n", + "type of NN due the unusual activation functions.\n", + "\n", + "## Multilayer perceptrons\n", + "\n", + "One uses often so-called fully-connected feed-forward neural networks\n", + "with three or more layers (an input layer, one or more hidden layers\n", + "and an output layer) consisting of neurons that have non-linear\n", + "activation functions.\n", + "\n", + "Such networks are often called *multilayer perceptrons* (MLPs).\n", + "\n", + "## Why multilayer perceptrons?\n", + "\n", + "According to the *Universal approximation theorem*, a feed-forward\n", + "neural network with just a single hidden layer containing a finite\n", + "number of neurons can approximate a continuous multidimensional\n", + "function to arbitrary accuracy, assuming the activation function for\n", + "the hidden layer is a **non-constant, bounded and\n", + "monotonically-increasing continuous function**.\n", + "\n", + "Note that the requirements on the activation function only applies to\n", + "the hidden layer, the output nodes are always assumed to be linear, so\n", + "as to not restrict the range of output values.\n", + "\n", + "\n", + "## Mathematical model\n", + "\n", + "The output $y$ is produced via the activation function $f$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This function receives $x_i$ as inputs.\n", + "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", + "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n", + "the neurons in the preceding layer. Furthermore, an MLP is\n", + "fully-connected, which means that each neuron receives a weighted sum\n", + "of the outputs of *all* neurons in the previous layer.\n", + "\n", + "## Mathematical model\n", + "\n", + "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} z_i^1 = \\sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1\n", + "\\label{_auto1} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here $b_i$ is the so-called bias which is normally needed in\n", + "case of zero activation weights or inputs. How to fix the biases and\n", + "the weights will be discussed below. The value of $z_i^1$ is the\n", + "argument to the activation function $f_i$ of each node $i$, The\n", + "variable $M$ stands for all possible inputs to a given node $i$ in the\n", + "first layer. We define the output $y_i^1$ of all neurons in layer 1 as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^1 = f(z_i^1) = f\\left(\\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\\right)\n", + "\\label{outputLayer1} \\tag{3}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we assume that all nodes in the same layer have identical\n", + "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", + "In this case we would identify these functions with a superscript $l$ for the $l$-th layer," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^l = f^l(u_i^l) = f^l\\left(\\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\\right)\n", + "\\label{generalLayer} \\tag{4}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $N_l$ is the number of nodes in layer $l$. When the output of\n", + "all the nodes in the first hidden layer are computed, the values of\n", + "the subsequent layer can be calculated and so forth until the output\n", + "is obtained.\n", + "\n", + "\n", + "\n", + "## Mathematical model\n", + "\n", + "The output of neuron $i$ in layer 2 is thus," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^2 = f^2\\left(\\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\\right) \n", + "\\label{_auto2} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + " = f^2\\left[\\sum_{j=1}^N w_{ij}^2f^1\\left(\\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\\right) + b_i^2\\right]\n", + "\\label{outputLayer2} \\tag{6}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y_i^3 = f^3\\left(\\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\\right) \n", + "\\label{_auto3} \\tag{7}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + " = f_3\\left[\\sum_{j} w_{ij}^3 f^2\\left(\\sum_{k} w_{jk}^2 f^1\\left(\\sum_{m} w_{km}^1 x_m + b_k^1\\right) + b_j^2\\right)\n", + " + b_1^3\\right]\n", + "\\label{_auto4} \\tag{8}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mathematical model\n", + "\n", + "We can generalize this expression to an MLP with $l$ hidden\n", + "layers. The complete functional form is," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "y^{l+1}_i = f^{l+1}\\left[\\!\\sum_{j=1}^{N_l} w_{ij}^3 f^l\\left(\\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\\left(\\dots f^1\\left(\\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\\right)\\dots\\right)+b_k^2\\right)+b_1^3\\right] \n", + "\\label{completeNN} \\tag{9}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which illustrates a basic property of MLPs: The only independent\n", + "variables are the input values $x_n$.\n", + "\n", + "## Mathematical model\n", + "\n", + "This confirms that an MLP, despite its quite convoluted mathematical\n", + "form, is nothing more than an analytic function, specifically a\n", + "mapping of real-valued vectors $\\hat{x} \\in \\mathbb{R}^n \\rightarrow\n", + "\\hat{y} \\in \\mathbb{R}^m$.\n", + "\n", + "Furthermore, the flexibility and universality of an MLP can be\n", + "illustrated by realizing that the expression is essentially a nested\n", + "sum of scaled activation functions of the form" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " f(x) = c_1 f(c_2 x + c_3) + c_4\n", + "\\label{_auto5} \\tag{10}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the parameters $c_i$ are weights and biases. By adjusting these\n", + "parameters, the activation functions can be shifted up and down or\n", + "left and right, change slope or be rescaled which is the key to the\n", + "flexibility of a neural network.\n", + "\n", + "### Matrix-vector notation\n", + "\n", + "We can introduce a more convenient notation for the activations in an A NN. \n", + "\n", + "Additionally, we can represent the biases and activations\n", + "as layer-wise column vectors $\\hat{b}_l$ and $\\hat{y}_l$, so that the $i$-th element of each vector \n", + "is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. \n", + "\n", + "We have that $\\mathrm{W}_l$ is an $N_{l-1} \\times N_l$ matrix, while $\\hat{b}_l$ and $\\hat{y}_l$ are $N_l \\times 1$ column vectors. \n", + "With this notation, the sum becomes a matrix-vector multiplication, and we can write\n", + "the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\hat{y}_2 = f_2(\\mathrm{W}_2 \\hat{y}_{1} + \\hat{b}_{2}) = \n", + " f_2\\left(\\left[\\begin{array}{ccc}\n", + " w^2_{11} &w^2_{12} &w^2_{13} \\\\\n", + " w^2_{21} &w^2_{22} &w^2_{23} \\\\\n", + " w^2_{31} &w^2_{32} &w^2_{33} \\\\\n", + " \\end{array} \\right] \\cdot\n", + " \\left[\\begin{array}{c}\n", + " y^1_1 \\\\\n", + " y^1_2 \\\\\n", + " y^1_3 \\\\\n", + " \\end{array}\\right] + \n", + " \\left[\\begin{array}{c}\n", + " b^2_1 \\\\\n", + " b^2_2 \\\\\n", + " b^2_3 \\\\\n", + " \\end{array}\\right]\\right).\n", + "\\label{_auto6} \\tag{11}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Matrix-vector notation and activation\n", + "\n", + "The activation of node $i$ in layer 2 is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " y^2_i = f_2\\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\\Bigr) = \n", + " f_2\\left(\\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\\right).\n", + "\\label{_auto7} \\tag{12}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is not just a convenient and compact notation, but also a useful\n", + "and intuitive way to think about MLPs: The output is calculated by a\n", + "series of matrix-vector multiplications and vector additions that are\n", + "used as input to the activation functions. For each operation\n", + "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer.\n", + "\n", + "\n", + "### Activation functions\n", + "\n", + "A property that characterizes a neural network, other than its\n", + "connectivity, is the choice of activation function(s). As described\n", + "in, the following restrictions are imposed on an activation function\n", + "for a FFNN to fulfill the universal approximation theorem\n", + "\n", + " * Non-constant\n", + "\n", + " * Bounded\n", + "\n", + " * Monotonically-increasing\n", + "\n", + " * Continuous\n", + "\n", + "### Activation functions, Logistic and Hyperbolic ones\n", + "\n", + "The second requirement excludes all linear functions. Furthermore, in\n", + "a MLP with only linear activation functions, each layer simply\n", + "performs a linear transformation of its inputs.\n", + "\n", + "Regardless of the number of layers, the output of the NN will be\n", + "nothing but a linear function of the inputs. Thus we need to introduce\n", + "some kind of non-linearity to the NN to be able to fit non-linear\n", + "functions Typical examples are the logistic *Sigmoid*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(x) = \\frac{1}{1 + e^{-x}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the *hyperbolic tangent* function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(x) = \\tanh(x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Relevance\n", + "\n", + "The *sigmoid* function are more biologically plausible because the\n", + "output of inactive neurons are zero. Such activation function are\n", + "called *one-sided*. However, it has been shown that the hyperbolic\n", + "tangent performs better than the sigmoid for training MLPs. has\n", + "become the most popular for *deep neural networks*" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "\"\"\"The sigmoid function (or the logistic curve) is a \n", + "function that takes any real number, z, and outputs a number (0,1).\n", + "It is useful in neural networks for assigning weights on a relative scale.\n", + "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", + "\n", + "import numpy\n", + "import matplotlib.pyplot as plt\n", + "import math as mt\n", + "\n", + "z = numpy.arange(-5, 5, .1)\n", + "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", + "sigma = sigma_fn(z)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, sigma)\n", + "ax.set_ylim([-0.1, 1.1])\n", + "ax.set_xlim([-5,5])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('sigmoid function')\n", + "\n", + "plt.show()\n", + "\n", + "\"\"\"Step Function\"\"\"\n", + "z = numpy.arange(-5, 5, .02)\n", + "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", + "step = step_fn(z)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, step)\n", + "ax.set_ylim([-0.5, 1.5])\n", + "ax.set_xlim([-5,5])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('step function')\n", + "\n", + "plt.show()\n", + "\n", + "\"\"\"Sine Function\"\"\"\n", + "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", + "t = numpy.sin(z)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, t)\n", + "ax.set_ylim([-1.0, 1.0])\n", + "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('sine function')\n", + "\n", + "plt.show()\n", + "\n", + "\"\"\"Plots a graph of the squashing function used by a rectified linear\n", + "unit\"\"\"\n", + "z = numpy.arange(-2, 2, .1)\n", + "zero = numpy.zeros(len(z))\n", + "y = numpy.max([zero, z], axis=0)\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.add_subplot(111)\n", + "ax.plot(z, y)\n", + "ax.set_ylim([-2.0, 2.0])\n", + "ax.set_xlim([-2.0, 2.0])\n", + "ax.grid(True)\n", + "ax.set_xlabel('z')\n", + "ax.set_title('Rectified linear unit')\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The multilayer perceptron (MLP)\n", + "\n", + "The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of\n", + "1. A neural network with one or more layers of nodes between the input and the output nodes.\n", + "\n", + "2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.\n", + "\n", + "3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.\n", + "\n", + "As a convention it is normal to call a network with one layer of input units, one layer of hidden\n", + "units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc.\n", + "\n", + "For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units.\n", + "Hereafter we will call the various entities of a layer for nodes.\n", + "There are also no connections within a single layer.\n", + "\n", + "The number of input nodes does not need to equal the number of output\n", + "nodes. This applies also to the hidden layers. Each layer may have its\n", + "own number of nodes and activation functions.\n", + "\n", + "The hidden layers have their name from the fact that they are not\n", + "linked to observables and as we will see below when we define the\n", + "so-called activation $\\hat{z}$, we can think of this as a basis\n", + "expansion of the original inputs $\\hat{x}$. The difference however\n", + "between neural networks and say linear regression is that now these\n", + "basis functions (which will correspond to the weights in the network)\n", + "are learned from data. This results in an important difference between\n", + "neural networks and deep learning approaches on one side and methods\n", + "like logistic regression or linear regression and their modifications on the other side.\n", + "\n", + "\n", + "## From one to many layers, the universal approximation theorem\n", + "\n", + "\n", + "A neural network with only one layer, what we called the simple\n", + "perceptron, is best suited if we have a standard binary model with\n", + "clear (linear) boundaries between the outcomes. As such it could\n", + "equally well be replaced by standard linear regression or logistic\n", + "regression. Networks with one or more hidden layers approximate\n", + "systems with more complex boundaries.\n", + "\n", + "As stated earlier, \n", + "an important theorem in studies of neural networks, restated without\n", + "proof here, is the [universal approximation\n", + "theorem](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf).\n", + "\n", + "It states that a feed-forward network with a single hidden layer\n", + "containing a finite number of neurons can approximate continuous\n", + "functions on compact subsets of real functions. The theorem thus\n", + "states that simple neural networks can represent a wide variety of\n", + "interesting functions when given appropriate parameters. It is the\n", + "multilayer feedforward architecture itself which gives neural networks\n", + "the potential of being universal approximators.\n", + "\n", + "\n", + "## Deriving the back propagation code for a multilayer perceptron model\n", + "\n", + "\n", + "**Note: figures will be inserted later!**\n", + "\n", + "As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.\n", + "The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.\n", + "This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).\n", + "\n", + "The questions we want to ask are how do changes in the biases and the\n", + "weights in our network change the cost function and how can we use the\n", + "final output to modify the weights?\n", + "\n", + "To derive these equations let us start with a plain regression problem\n", + "and define our cost function as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the $t_i$s are our $n$ targets (the values we want to\n", + "reproduce), while the outputs of the network after having propagated\n", + "all inputs $\\hat{x}$ are given by $y_i$. Below we will demonstrate\n", + "how the basic equations arising from the back propagation algorithm\n", + "can be modified in order to study classification problems with $K$\n", + "classes.\n", + "\n", + "## Definitions\n", + "\n", + "With our definition of the targets $\\hat{t}$, the outputs of the\n", + "network $\\hat{y}$ and the inputs $\\hat{x}$ we\n", + "define now the activation $z_j^l$ of node/neuron/unit $j$ of the\n", + "$l$-th layer as a function of the bias, the weights which add up from\n", + "the previous layer $l-1$ and the forward passes/outputs\n", + "$\\hat{a}^{l-1}$ from the previous layer as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", + "represents the total number of nodes/neurons/units of layer $l-1$. The\n", + "figure here illustrates this equation. We can rewrite this in a more\n", + "compact form as the matrix-vector products we discussed earlier," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With the activation values $\\hat{z}^l$ we can in turn define the\n", + "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n", + "activation function. In the examples here we will use the sigmoid\n", + "function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers\n", + "and their nodes. It means we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Derivatives and the chain rule\n", + "\n", + "From the definition of the activation $z_j^l$ we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Derivative of the cost function\n", + "\n", + "With these definitions we can now compute the derivative of the cost function in terms of the weights.\n", + "\n", + "Let us specialize to the output layer $l=L$. Our cost function is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal C}(\\hat{W^L}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - t_i\\right)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The derivative of this function with respect to the weights is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The last partial derivative can easily be computed and reads (by applying the chain rule)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Bringing it together, first back propagation equation\n", + "\n", + "We have thus" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Defining" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - t_j\\right) = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and using the Hadamard product of two vectors we can write this as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is an important expression. The second term on the right handside\n", + "measures how fast the cost function is changing as a function of the $j$th\n", + "output activation. If, for example, the cost function doesn't depend\n", + "much on a particular output node $j$, then $\\delta_j^L$ will be small,\n", + "which is what we would expect. The first term on the right, measures\n", + "how fast the activation function $f$ is changing at a given activation\n", + "value $z_j^L$.\n", + "\n", + "Notice that everything in the above equations is easily computed. In\n", + "particular, we compute $z_j^L$ while computing the behaviour of the\n", + "network, and it is only a small additional overhead to compute\n", + "$f'(z^L_j)$. The exact form of the derivative with respect to the\n", + "output depends on the form of the cost function.\n", + "However, provided the cost function is known there should be little\n", + "trouble in calculating" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Derivatives in terms of $z_j^L$\n", + "\n", + "It is also easy to see that our previous equation can be written as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. \n", + "## Bringing it together\n", + "\n", + "We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are\n", + "\n", + "**The starting equations.**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1},\n", + "\\label{_auto8} \\tag{13}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", + "\\label{_auto9} \\tag{14}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", + "\\label{_auto10} \\tag{15}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An interesting consequence of the above equations is that when the\n", + "activation $a_k^{L-1}$ is small, the gradient term, that is the\n", + "derivative of the cost function with respect to the weights, will also\n", + "tend to be small. We say then that the weight learns slowly, meaning\n", + "that it changes slowly when we minimize the weights via say gradient\n", + "descent. In this case we say the system learns slowly.\n", + "\n", + "Another interesting feature is that is when the activation function,\n", + "represented by the sigmoid function here, is rather flat when we move towards\n", + "its end values $0$ and $1$ (see the above Python codes). In these\n", + "cases, the derivatives of the activation function will also be close\n", + "to zero, meaning again that the gradients will be small and the\n", + "network learns slowly again.\n", + "\n", + "\n", + "\n", + "We need a fourth equation and we are set. We are going to propagate\n", + "backwards in order to the determine the weights and biases. In order\n", + "to do so we need to represent the error in the layer before the final\n", + "one $L-1$ in terms of the errors in the final output layer.\n", + "\n", + "## Final back propagating equation\n", + "\n", + "We have that (replacing $L$ with a general layer $l$)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and recalling that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $M_l$ being the number of nodes in layer $l$, we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is our final equation.\n", + "\n", + "We are now ready to set up the algorithm for back propagation and learning the weights and biases.\n", + "\n", + "## Setting up the Back propagation algorithm\n", + "\n", + "\n", + "\n", + "The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", + "\n", + "First, we set up the input data $\\hat{x}$ and the activations\n", + "$\\hat{z}_1$ of the input layer and compute the activation function and\n", + "the pertinent outputs $\\hat{a}^1$.\n", + "\n", + "\n", + "\n", + "Secondly, we perform then the feed forward till we reach the output\n", + "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n", + "activation function and the pertinent outputs $\\hat{a}^l$ for\n", + "$l=2,3,\\dots,L$.\n", + "\n", + "\n", + "\n", + "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", + "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training.\n", + "\n", + "\n", + "\n", + "## Setting up a Multi-layer perceptron model for classification\n", + "\n", + "We are now gong to develop an example based on the MNIST data\n", + "base. This is a classification problem and we need to use our\n", + "cross-entropy function we discussed in connection with logistic\n", + "regression. The cross-entropy defines our cost function for the\n", + "classificaton problems with neural networks.\n", + "\n", + "In binary classification with two classes $(0, 1)$ we define the\n", + "logistic/sigmoid function as the probability that a particular input\n", + "is in class $0$ or $1$. This is possible because the logistic\n", + "function takes any input from the real numbers and inputs a number\n", + "between 0 and 1, and can therefore be interpreted as a probability. It\n", + "also has other nice properties, such as a derivative that is simple to\n", + "calculate.\n", + "\n", + "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", + "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", + "represents our activation values $z$. We have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) = \\frac{1}{1 + \\exp{(- \\hat{x}})} ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "P(y = 1 \\mid \\hat{x}, \\hat{\\theta}) = 1 - P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $y \\in \\{0, 1\\}$ and $\\hat{\\theta}$ represents the weights and biases\n", + "of our network.\n", + "\n", + "\n", + "## Defining the cost function\n", + "\n", + "Our cost function is given as (see the Logistic regression lectures)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\hat{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\hat{\\theta}) = - \\sum_{i=1}^n\n", + "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\hat{\\theta}) .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", + "for each point in the dataset $\\mathcal{L}_i(\\hat{\\theta})$. \n", + "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", + "than maximizing a negative number. \n", + "\n", + "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", + "\n", + "$y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", + "\n", + "\n", + "$y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", + "\n", + "\n", + "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. \n", + "\n", + "If $\\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", + "output vector $\\hat{y}_i$. \n", + "The probability of $\\hat{x}_i$ being in class $c$ will be given by the softmax function:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "P(y_{ic} = 1 \\mid \\hat{x}_i, \\hat{\\theta}) = \\frac{\\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_c)}}\n", + "{\\sum_{c'=0}^{C-1} \\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_{c'})}} ,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which reduces to the logistic function in the binary case. \n", + "The likelihood of this $C$-class classifier\n", + "is now given as:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "P(\\mathcal{D} \\mid \\hat{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Again we take the negative log-likelihood to define our cost function:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\hat{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\hat{\\theta})}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "See the logistic regression lectures for a full definition of the cost function.\n", + "\n", + "The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!\n", + "\n", + "## Example: binary classification problem\n", + "\n", + "As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\\beta$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\hat{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\hat{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\hat{\\beta})}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we had defined the logistic (sigmoid) function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p(y_i =1\\vert x_i,\\hat{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p(y_i =0\\vert x_i,\\hat{\\beta})=1-p(y_i =1\\vert x_i,\\hat{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The parameters $\\hat{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", + "\n", + "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", + "We have then" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", + "Our cost function at the final layer $l=L$ is now" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\hat{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial \\mathcal{C}(\\hat{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In case we use another activation function than the logistic one, we need to evaluate other derivatives. \n", + "\n", + "\n", + "## The Softmax function\n", + "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", + "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the Softmax function we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Its derivative with respect to $z_j^l$ gives" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which in case of the simply binary model reduces to having $i=j$. \n", + "\n", + "\n", + "## Developing a code for doing neural networks with back propagation\n", + "\n", + "\n", + "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", + "\n", + "1. Collect and pre-process data \n", + "\n", + "2. Define model and architecture \n", + "\n", + "3. Choose cost function and optimizer \n", + "\n", + "4. Train the model \n", + "\n", + "5. Evaluate model performance on test data \n", + "\n", + "6. Adjust hyperparameters (if necessary, network architecture)\n", + "\n", + "## Collect and pre-process data\n", + "\n", + "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", + "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", + "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", + "of handwritten digits that is commonly used for training various image processing systems. \n", + "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", + "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", + "\n", + "To feed data into a feed-forward neural network we need to represent\n", + "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", + "row represents an *input*, in this case a handwritten digit, and\n", + "each column represents a *feature*, in this case a pixel. The\n", + "correct answers, also known as *labels* or *targets* are\n", + "represented as a 1D array of integers \n", + "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", + "\n", + "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", + "measurements of height (in m) \n", + "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", + "\n", + "$$ X = \\begin{bmatrix}\n", + "1.85 & 81\\\\\n", + "1.71 & 65\\\\\n", + "1.95 & 103\\\\\n", + "1.55 & 42\\\\\n", + "1.63 & 56\n", + "\\end{bmatrix} ,$$ \n", + "\n", + "and the targets would be: \n", + "\n", + "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", + "\n", + "Since each input image is a 2D matrix, we need to flatten the image\n", + "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", + "design/feature matrix. This means we lose all spatial information in the\n", + "image, such as locality and translational invariance. More complicated\n", + "architectures such as Convolutional Neural Networks can take advantage\n", + "of such information, and are most commonly applied when analyzing\n", + "images." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Train and test datasets\n", + "\n", + "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", + "\n", + "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", + "\n", + "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", + "no bias in the sampling. \n", + "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", + "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", + "collected from 12.00 to 24.00." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# one-liner from scikit-learn library\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)\n", + "\n", + "# equivalently in numpy\n", + "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", + " n_inputs = len(inputs)\n", + " inputs_shuffled = inputs.copy()\n", + " labels_shuffled = labels.copy()\n", + " \n", + " np.random.shuffle(inputs_shuffled)\n", + " np.random.shuffle(labels_shuffled)\n", + " \n", + " train_end = int(n_inputs*train_size)\n", + " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", + " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", + " \n", + " return X_train, X_test, Y_train, Y_test\n", + "\n", + "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", + "\n", + "print(\"Number of training images: \" + str(len(X_train)))\n", + "print(\"Number of test images: \" + str(len(X_test)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Define model and architecture\n", + "\n", + "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", + "\n", + "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", + "\n", + "$$ y = f(z) ,$$\n", + "\n", + "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", + "and $w_i$ is the weight to input $i$. \n", + "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", + "\n", + "The simplest activation function for a neuron is the *Heaviside* function:\n", + "\n", + "$$ f(z) = \n", + "\\begin{cases}\n", + "1, & z > 0\\\\\n", + "0, & \\text{otherwise}\n", + "\\end{cases}\n", + "$$\n", + "\n", + "A feed-forward neural network with this activation is known as a *perceptron*. \n", + "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", + "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", + "and we call these architectures *multiclass perceptrons*. \n", + "\n", + "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", + "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", + "\n", + "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", + "We will be using the sigmoid function $\\sigma(x)$: \n", + "\n", + "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", + "\n", + "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.\n", + "\n", + "\n", + "## Layers\n", + "\n", + "* Input \n", + "\n", + "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", + "\n", + "* Hidden layer\n", + "\n", + "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", + "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", + "\n", + "* Output\n", + "\n", + "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", + "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", + "\n", + "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", + "\n", + "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", + "\n", + "$$ P(\\text{class $j$} \\mid \\text{input $\\hat{a}$}) = \\frac{\\exp{(\\hat{a}^T \\hat{w}_j)}}\n", + "{\\sum_{c=0}^{9} \\exp{(\\hat{a}^T \\hat{w}_c)}} ,$$ \n", + "\n", + "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\hat{a}$, with $\\hat{w}_j$ the weights of neuron $j$ to the inputs. \n", + "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", + "The exponent is just the weighted sum of inputs as before: \n", + "\n", + "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", + "\n", + "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", + "weights to the output layer.\n", + "\n", + "\n", + "## Weights and biases\n", + "\n", + "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", + "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", + "\n", + "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", + "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", + "\n", + "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", + "\n", + "The bias weights $\\hat{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# building our neural network\n", + "\n", + "n_inputs, n_features = X_train.shape\n", + "n_hidden_neurons = 50\n", + "n_categories = 10\n", + "\n", + "# we make the weights normally distributed using numpy.random.randn\n", + "\n", + "# weights and bias in the hidden layer\n", + "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", + "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", + "\n", + "# weights and bias in the output layer\n", + "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", + "output_bias = np.zeros(n_categories) + 0.01" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Feed-forward pass\n", + "\n", + "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", + "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", + "\n", + "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", + "\n", + "this is then passed through our activation function \n", + "\n", + "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", + "\n", + "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", + "\n", + "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", + "\n", + "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", + "\n", + "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", + "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$ \n", + "\n", + "\n", + "## Matrix multiplications\n", + "\n", + "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", + "layer have the dimensions \n", + "$W_{hidden} = (n_{features}, n_{hidden})$,\n", + "we can easily feed the network all our training data in one go by taking the matrix product \n", + "\n", + "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", + "\n", + "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", + "for each input image and each hidden neuron. \n", + "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", + "\n", + "$$ \\hat{z}^{l} = \\hat{X} \\hat{W}^{l} + \\hat{b}^{l} ,$$\n", + "\n", + "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", + "This is then passed through the activation: \n", + "\n", + "$$ \\hat{a}^{l} = f(\\hat{z}^l) .$$ \n", + "\n", + "This is fed to the output layer: \n", + "\n", + "$$ \\hat{z}^{L} = \\hat{a}^{L} \\hat{W}^{L} + \\hat{b}^{L} .$$\n", + "\n", + "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", + "\n", + "$$ output = softmax (\\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# setup the feed-forward pass, subscript h = hidden layer\n", + "\n", + "def sigmoid(x):\n", + " return 1/(1 + np.exp(-x))\n", + "\n", + "def feed_forward(X):\n", + " # weighted sum of inputs to the hidden layer\n", + " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", + " # activation in the hidden layer\n", + " a_h = sigmoid(z_h)\n", + " \n", + " # weighted sum of inputs to the output layer\n", + " z_o = np.matmul(a_h, output_weights) + output_bias\n", + " # softmax output\n", + " # axis 0 holds each input and axis 1 the probabilities of each category\n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " \n", + " return probabilities\n", + "\n", + "probabilities = feed_forward(X_train)\n", + "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", + "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", + "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", + "print()\n", + "\n", + "# we obtain a prediction by taking the class with the highest likelihood\n", + "def predict(X):\n", + " probabilities = feed_forward(X)\n", + " return np.argmax(probabilities, axis=1)\n", + "\n", + "predictions = predict(X_train)\n", + "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", + "print(\"prediction for image 0: \" + str(predictions[0]))\n", + "print(\"correct label for image 0: \" + str(Y_train[0]))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Choose cost function and optimizer\n", + "\n", + "To measure how well our neural network is doing we need to introduce a cost function. \n", + "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", + "that gives the total error of our network across all samples the *cost* function.\n", + "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", + "\n", + "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", + "\n", + "$$ y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", + "\n", + "\n", + "$$ y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", + "\n", + "\n", + "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", + "\n", + "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", + "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\hat{x}_i$ in the dataset.\n", + "\n", + "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", + "probability of the correct category $c'$ \n", + "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", + "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\hat{\\theta}$ represents the parameters of our network, i.e. all the weights and biases. \n", + "\n", + "\n", + "## Optimizing the cost function\n", + "\n", + "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", + "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", + "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", + "\n", + "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", + "\n", + "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", + "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", + "\n", + "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", + "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", + "on a subset of the data called a *minibatch*. \n", + "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", + "is $N/M$. \n", + "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", + "\n", + "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", + "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", + "\n", + "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", + "\n", + "This has two important benefits: \n", + "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", + "\n", + "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", + "\n", + "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).\n", + "\n", + "\n", + "## Regularization\n", + "\n", + "It is common to add an extra term to the cost function, proportional\n", + "to the size of the weights. This is equivalent to constraining the\n", + "size of the weights, so that they do not grow out of control.\n", + "Constraining the size of the weights means that the weights cannot\n", + "grow arbitrarily large to fit the training data, and in this way\n", + "reduces *overfitting*.\n", + "\n", + "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", + "\n", + "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", + "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\hat{w} \\rvert \\rvert_2^2 \n", + "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", + "\n", + "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", + "\n", + "\n", + "In order to train the model, we need to calculate the derivative of\n", + "the cost function with respect to every bias and weight in the\n", + "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", + "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", + "layer ($+1$ for the bias), and the gradient must be calculated for\n", + "every parameter. We use the *backpropagation* algorithm discussed\n", + "above. This is a clever use of the chain rule that allows us to\n", + "calculate the gradient efficently. \n", + "\n", + "\n", + "## Matrix multiplication\n", + "\n", + "To more efficently train our network these equations are implemented using matrix operations. \n", + "The error in the output layer is calculated simply as, with $\\hat{t}$ being our targets, \n", + "\n", + "$$ \\delta_L = \\hat{t} - \\hat{y} = (n_{inputs}, n_{categories}) .$$ \n", + "\n", + "The gradient for the output weights is calculated as \n", + "\n", + "$$ \\nabla W_{L} = \\hat{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", + "\n", + "where $\\hat{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", + "Since we are going backwards we have to transpose the activation matrix. \n", + "\n", + "The gradient with respect to the output bias is then \n", + "\n", + "$$ \\nabla \\hat{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", + "\n", + "The error in the hidden layer is \n", + "\n", + "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", + "\n", + "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", + "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", + "the *Hadamard product*, meaning element-wise multiplication. \n", + "\n", + "This again gives us the gradients in the hidden layer: \n", + "\n", + "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", + "\n", + "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# to categorical turns our integer vector into a onehot representation\n", + "from sklearn.metrics import accuracy_score\n", + "\n", + "# one-hot in numpy\n", + "def to_categorical_numpy(integer_vector):\n", + " n_inputs = len(integer_vector)\n", + " n_categories = np.max(integer_vector) + 1\n", + " onehot_vector = np.zeros((n_inputs, n_categories))\n", + " onehot_vector[range(n_inputs), integer_vector] = 1\n", + " \n", + " return onehot_vector\n", + "\n", + "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", + "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", + "\n", + "def feed_forward_train(X):\n", + " # weighted sum of inputs to the hidden layer\n", + " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", + " # activation in the hidden layer\n", + " a_h = sigmoid(z_h)\n", + " \n", + " # weighted sum of inputs to the output layer\n", + " z_o = np.matmul(a_h, output_weights) + output_bias\n", + " # softmax output\n", + " # axis 0 holds each input and axis 1 the probabilities of each category\n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " \n", + " # for backpropagation need activations in hidden and output layers\n", + " return a_h, probabilities\n", + "\n", + "def backpropagation(X, Y):\n", + " a_h, probabilities = feed_forward_train(X)\n", + " \n", + " # error in the output layer\n", + " error_output = probabilities - Y\n", + " # error in the hidden layer\n", + " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", + " \n", + " # gradients for the output layer\n", + " output_weights_gradient = np.matmul(a_h.T, error_output)\n", + " output_bias_gradient = np.sum(error_output, axis=0)\n", + " \n", + " # gradient for the hidden layer\n", + " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", + " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", + "\n", + " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", + "\n", + "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", + "\n", + "eta = 0.01\n", + "lmbd = 0.01\n", + "for i in range(1000):\n", + " # calculate gradients\n", + " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", + " \n", + " # regularization term gradients\n", + " dWo += lmbd * output_weights\n", + " dWh += lmbd * hidden_weights\n", + " \n", + " # update weights and biases\n", + " output_weights -= eta * dWo\n", + " output_bias -= eta * dBo\n", + " hidden_weights -= eta * dWh\n", + " hidden_bias -= eta * dBh\n", + "\n", + "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Improving performance\n", + "\n", + "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", + "In order to obtain a network that does something useful, we will have to do a bit more work. \n", + "\n", + "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", + "\n", + "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", + "going through the entire dataset ($n/M$ batches) an *epoch*.\n", + "\n", + "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", + "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/). \n", + "\n", + "## Full object-oriented implementation\n", + "\n", + "It is very natural to think of the network as an object, with specific instances of the network\n", + "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "class NeuralNetwork:\n", + " def __init__(\n", + " self,\n", + " X_data,\n", + " Y_data,\n", + " n_hidden_neurons=50,\n", + " n_categories=10,\n", + " epochs=10,\n", + " batch_size=100,\n", + " eta=0.1,\n", + " lmbd=0.0):\n", + "\n", + " self.X_data_full = X_data\n", + " self.Y_data_full = Y_data\n", + "\n", + " self.n_inputs = X_data.shape[0]\n", + " self.n_features = X_data.shape[1]\n", + " self.n_hidden_neurons = n_hidden_neurons\n", + " self.n_categories = n_categories\n", + "\n", + " self.epochs = epochs\n", + " self.batch_size = batch_size\n", + " self.iterations = self.n_inputs // self.batch_size\n", + " self.eta = eta\n", + " self.lmbd = lmbd\n", + "\n", + " self.create_biases_and_weights()\n", + "\n", + " def create_biases_and_weights(self):\n", + " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", + " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", + "\n", + " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", + " self.output_bias = np.zeros(self.n_categories) + 0.01\n", + "\n", + " def feed_forward(self):\n", + " # feed-forward for training\n", + " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", + " self.a_h = sigmoid(self.z_h)\n", + "\n", + " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", + "\n", + " exp_term = np.exp(self.z_o)\n", + " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + "\n", + " def feed_forward_out(self, X):\n", + " # feed-forward for output\n", + " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", + " a_h = sigmoid(z_h)\n", + "\n", + " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", + " \n", + " exp_term = np.exp(z_o)\n", + " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", + " return probabilities\n", + "\n", + " def backpropagation(self):\n", + " error_output = self.probabilities - self.Y_data\n", + " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", + "\n", + " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", + " self.output_bias_gradient = np.sum(error_output, axis=0)\n", + "\n", + " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", + " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", + "\n", + " if self.lmbd > 0.0:\n", + " self.output_weights_gradient += self.lmbd * self.output_weights\n", + " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", + "\n", + " self.output_weights -= self.eta * self.output_weights_gradient\n", + " self.output_bias -= self.eta * self.output_bias_gradient\n", + " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", + " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", + "\n", + " def predict(self, X):\n", + " probabilities = self.feed_forward_out(X)\n", + " return np.argmax(probabilities, axis=1)\n", + "\n", + " def predict_probabilities(self, X):\n", + " probabilities = self.feed_forward_out(X)\n", + " return probabilities\n", + "\n", + " def train(self):\n", + " data_indices = np.arange(self.n_inputs)\n", + "\n", + " for i in range(self.epochs):\n", + " for j in range(self.iterations):\n", + " # pick datapoints with replacement\n", + " chosen_datapoints = np.random.choice(\n", + " data_indices, size=self.batch_size, replace=False\n", + " )\n", + "\n", + " # minibatch training data\n", + " self.X_data = self.X_data_full[chosen_datapoints]\n", + " self.Y_data = self.Y_data_full[chosen_datapoints]\n", + "\n", + " self.feed_forward()\n", + " self.backpropagation()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluate model performance on test data\n", + "\n", + "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", + "We measure the performance of the network using the *accuracy* score. \n", + "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", + "\n", + "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\hat{y}_i = y_i)}{n} ,$$ \n", + "\n", + "where $I$ is the indicator function, $1$ if $\\hat{y}_i = y_i$ and $0$ otherwise." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "epochs = 100\n", + "batch_size = 100\n", + "\n", + "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", + " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", + "dnn.train()\n", + "test_predict = dnn.predict(X_test)\n", + "\n", + "# accuracy score from scikit library\n", + "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", + "\n", + "# equivalent in numpy\n", + "def accuracy_score_numpy(Y_test, Y_pred):\n", + " return np.sum(Y_test == Y_pred) / len(Y_test)\n", + "\n", + "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Adjust hyperparameters\n", + "\n", + "We now perform a grid search to find the optimal hyperparameters for the network. \n", + "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)\n", + "# store the models for later use\n", + "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + "\n", + "# grid search\n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", + " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", + " dnn.train()\n", + " \n", + " DNN_numpy[i][j] = dnn\n", + " \n", + " test_predict = dnn.predict(X_test)\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# visual representation of grid search\n", + "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " dnn = DNN_numpy[i][j]\n", + " \n", + " train_pred = dnn.predict(X_train) \n", + " test_pred = dnn.predict(X_test)\n", + "\n", + " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", + " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## scikit-learn implementation\n", + "\n", + "**scikit-learn** focuses more\n", + "on traditional machine learning methods, such as regression,\n", + "clustering, decision trees, etc. As such, it has only two types of\n", + "neural networks: Multi Layer Perceptron outputting continuous values,\n", + "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", + "*MLPClassifier*. We will see how simple it is to use these classes.\n", + "\n", + "**scikit-learn** implements a few improvements from our neural network,\n", + "such as early stopping, a varying learning rate, different\n", + "optimization methods, etc. We would therefore expect a better\n", + "performance overall." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.neural_network import MLPClassifier\n", + "# store models for later use\n", + "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + "\n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", + " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", + " dnn.fit(X_train, Y_train)\n", + " \n", + " DNN_scikit[i][j] = dnn\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " dnn = DNN_scikit[i][j]\n", + " \n", + " train_pred = dnn.predict(X_train) \n", + " test_pred = dnn.predict(X_test)\n", + "\n", + " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", + " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Building neural networks in Tensorflow and Keras\n", + "\n", + "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", + "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", + "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", + "\n", + "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", + "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", + "NumPy arrays.\n", + "\n", + "## Tensorflow\n", + "\n", + "Tensorflow is an open source library machine learning library\n", + "developed by the Google Brain team for internal use. It was released\n", + "under the Apache 2.0 open source license in November 9, 2015.\n", + "\n", + "Tensorflow is a computational framework that allows you to construct\n", + "machine learning models at different levels of abstraction, from\n", + "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", + "that Tensorflow is built upon. The higher levels of abstraction are\n", + "simpler to use, but less flexible, and our choice of implementation\n", + "should reflect the problems we are trying to solve.\n", + "\n", + "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", + "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", + "to represent your model, and then create a Tensorflow *session* to run the graph.\n", + "\n", + "In this guide we will analyze the same data as we did in our NumPy and\n", + "scikit-learn tutorial, gathered from the MNIST database of images. We\n", + "will give an introduction to the lower level Python Application\n", + "Program Interfaces (APIs), and see how we use them to build our graph.\n", + "Then we will build (effectively) the same graph in Keras, to see just\n", + "how simple solving a machine learning problem can be.\n", + "\n", + "To install tensorflow on Unix/Linux systems, use pip as" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pip3 install tensorflow" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and/or if you use **anaconda**, just write (or install from the graphical user interface)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "conda install tensorflow" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Collect and pre-process data" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from keras.utils import to_categorical\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# one-hot representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using TensorFlow backend\n", + "\n", + "1. Define model and architecture\n", + "\n", + "2. Choose cost function and optimizer" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import tensorflow as tf\n", + "\n", + "class NeuralNetworkTensorflow:\n", + " def __init__(\n", + " self,\n", + " X_train,\n", + " Y_train,\n", + " X_test,\n", + " Y_test,\n", + " n_neurons_layer1=100,\n", + " n_neurons_layer2=50,\n", + " n_categories=2,\n", + " epochs=10,\n", + " batch_size=100,\n", + " eta=0.1,\n", + " lmbd=0.0):\n", + " \n", + " # keep track of number of steps\n", + " self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n", + " \n", + " self.X_train = X_train\n", + " self.Y_train = Y_train\n", + " self.X_test = X_test\n", + " self.Y_test = Y_test\n", + " \n", + " self.n_inputs = X_train.shape[0]\n", + " self.n_features = X_train.shape[1]\n", + " self.n_neurons_layer1 = n_neurons_layer1\n", + " self.n_neurons_layer2 = n_neurons_layer2\n", + " self.n_categories = n_categories\n", + " \n", + " self.epochs = epochs\n", + " self.batch_size = batch_size\n", + " self.iterations = self.n_inputs // self.batch_size\n", + " self.eta = eta\n", + " self.lmbd = lmbd\n", + " \n", + " # build network piece by piece\n", + " # name scopes (with) are used to enforce creation of new variables\n", + " # https://www.tensorflow.org/guide/variables\n", + " self.create_placeholders()\n", + " self.create_DNN()\n", + " self.create_loss()\n", + " self.create_optimiser()\n", + " self.create_accuracy()\n", + " \n", + " def create_placeholders(self):\n", + " # placeholders are fine here, but \"Datasets\" are the preferred method\n", + " # of streaming data into a model\n", + " with tf.name_scope('data'):\n", + " self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')\n", + " self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')\n", + " \n", + " def create_DNN(self):\n", + " with tf.name_scope('DNN'):\n", + " # the weights are stored to calculate regularization loss later\n", + " \n", + " # Fully connected layer 1\n", + " self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", + " b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", + " a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)\n", + " \n", + " # Fully connected layer 2\n", + " self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", + " b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", + " a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)\n", + " \n", + " # Output layer\n", + " self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)\n", + " b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)\n", + " self.z_out = tf.matmul(a_fc2, self.W_out) + b_out\n", + " \n", + " def create_loss(self):\n", + " with tf.name_scope('loss'):\n", + " softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))\n", + " \n", + " regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)\n", + " regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)\n", + " regularizer_loss_out = tf.nn.l2_loss(self.W_out)\n", + " regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)\n", + " \n", + " self.loss = softmax_loss + regularizer_loss\n", + "\n", + " def create_accuracy(self):\n", + " with tf.name_scope('accuracy'):\n", + " probabilities = tf.nn.softmax(self.z_out)\n", + " predictions = tf.argmax(probabilities, axis=1)\n", + " labels = tf.argmax(self.Y, axis=1)\n", + " \n", + " correct_predictions = tf.equal(predictions, labels)\n", + " correct_predictions = tf.cast(correct_predictions, tf.float32)\n", + " self.accuracy = tf.reduce_mean(correct_predictions)\n", + " \n", + " def create_optimiser(self):\n", + " with tf.name_scope('optimizer'):\n", + " self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)\n", + " \n", + " def weight_variable(self, shape, name='', dtype=tf.float32):\n", + " initial = tf.truncated_normal(shape, stddev=0.1)\n", + " return tf.Variable(initial, name=name, dtype=dtype)\n", + " \n", + " def bias_variable(self, shape, name='', dtype=tf.float32):\n", + " initial = tf.constant(0.1, shape=shape)\n", + " return tf.Variable(initial, name=name, dtype=dtype)\n", + " \n", + " def fit(self):\n", + " data_indices = np.arange(self.n_inputs)\n", + "\n", + " with tf.Session() as sess:\n", + " sess.run(tf.global_variables_initializer())\n", + " for i in range(self.epochs):\n", + " for j in range(self.iterations):\n", + " chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)\n", + " batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]\n", + " \n", + " sess.run([DNN.loss, DNN.optimizer],\n", + " feed_dict={DNN.X: batch_X,\n", + " DNN.Y: batch_Y})\n", + " accuracy = sess.run(DNN.accuracy,\n", + " feed_dict={DNN.X: batch_X,\n", + " DNN.Y: batch_Y})\n", + " step = sess.run(DNN.global_step)\n", + " \n", + " self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", + " feed_dict={DNN.X: self.X_train,\n", + " DNN.Y: self.Y_train})\n", + " \n", + " self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", + " feed_dict={DNN.X: self.X_test,\n", + " DNN.Y: self.Y_test})" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Optimizing and using gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "epochs = 100\n", + "batch_size = 100\n", + "n_neurons_layer1 = 100\n", + "n_neurons_layer2 = 50\n", + "n_categories = 10\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,\n", + " n_neurons_layer1, n_neurons_layer2, n_categories,\n", + " epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)\n", + " DNN.fit()\n", + " \n", + " DNN_tf[i][j] = DNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % DNN.test_accuracy)\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " DNN = DNN_tf[i][j]\n", + "\n", + " train_accuracy[i][j] = DNN.train_accuracy\n", + " test_accuracy[i][j] = DNN.test_accuracy\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# optional\n", + "# we can use log files to visualize our graph in Tensorboard\n", + "writer = tf.summary.FileWriter('logs/')\n", + "writer.add_graph(tf.get_default_graph())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Keras\n", + "\n", + "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", + "that supports Tensorflow, CTNK and Theano as backends. \n", + "If you have Tensorflow installed Keras is available through the *tf.keras* module. \n", + "If you have Anaconda installed you may run the following command" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "conda install keras" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pip3 install keras" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or look up the [instructions here](https://keras.io/)." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from keras.models import Sequential\n", + "from keras.layers import Dense\n", + "from keras.regularizers import l2\n", + "from keras.optimizers import SGD\n", + "\n", + "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", + " model = Sequential()\n", + " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", + " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", + " model.add(Dense(n_categories, activation='softmax'))\n", + " \n", + " sgd = SGD(lr=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", + " eta=eta, lmbd=lmbd)\n", + " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = DNN.evaluate(X_test, Y_test)\n", + " \n", + " DNN_keras[i][j] = DNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " DNN = DNN_keras[i][j]\n", + "\n", + " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "## Which activation function should I use?\n", + "\n", + "The Back propagation algorithm we derived above works by going from\n", + "the output layer to the input layer, propagating the error gradient on\n", + "the way. Once the algorithm has computed the gradient of the cost\n", + "function with regards to each parameter in the network, it uses these\n", + "gradients to update each parameter with a Gradient Descent (GD) step.\n", + "\n", + "\n", + "Unfortunately for us, the gradients often get smaller and smaller as the\n", + "algorithm progresses down to the first hidden layers. As a result, the\n", + "GD update leaves the lower layer connection weights\n", + "virtually unchanged, and training never converges to a good\n", + "solution. This is known in the literature as \n", + "**the vanishing gradients problem**. \n", + "\n", + "In other cases, the opposite can happen, namely the the gradients can grow bigger and\n", + "bigger. The result is that many of the layers get large updates of the \n", + "weights the\n", + "algorithm diverges. This is the **exploding gradients problem**, which is\n", + "mostly encountered in recurrent neural networks. More generally, deep\n", + "neural networks suffer from unstable gradients, different layers may\n", + "learn at widely different speeds\n", + "\n", + "\n", + "## Is the Logistic activation function (Sigmoid) our choice?\n", + "\n", + "Although this unfortunate behavior has been empirically observed for\n", + "quite a while (it was one of the reasons why deep neural networks were\n", + "mostly abandoned for a long time), it is only around 2010 that\n", + "significant progress was made in understanding it.\n", + "\n", + "A paper titled [Understanding the Difficulty of Training Deep\n", + "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", + "the problems with the popular logistic\n", + "sigmoid activation function and the weight initialization technique\n", + "that was most popular at the time, namely random initialization using\n", + "a normal distribution with a mean of 0 and a standard deviation of\n", + "1. \n", + "\n", + "They showed that with this activation function and this\n", + "initialization scheme, the variance of the outputs of each layer is\n", + "much greater than the variance of its inputs. Going forward in the\n", + "network, the variance keeps increasing after each layer until the\n", + "activation function saturates at the top layers. This is actually made\n", + "worse by the fact that the logistic function has a mean of 0.5, not 0\n", + "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", + "better than the logistic function in deep networks).\n", + "\n", + "\n", + "## The derivative of the Logistic funtion\n", + "\n", + "Looking at the logistic activation function, when inputs become large\n", + "(negative or positive), the function saturates at 0 or 1, with a\n", + "derivative extremely close to 0. Thus when backpropagation kicks in,\n", + "it has virtually no gradient to propagate back through the network,\n", + "and what little gradient exists keeps getting diluted as\n", + "backpropagation progresses down through the top layers, so there is\n", + "really nothing left for the lower layers.\n", + "\n", + "In their paper, Glorot and Bengio propose a way to significantly\n", + "alleviate this problem. We need the signal to flow properly in both\n", + "directions: in the forward direction when making predictions, and in\n", + "the reverse direction when backpropagating gradients. We don’t want\n", + "the signal to die out, nor do we want it to explode and saturate. For\n", + "the signal to flow properly, the authors argue that we need the\n", + "variance of the outputs of each layer to be equal to the variance of\n", + "its inputs, and we also need the gradients to have equal variance\n", + "before and after flowing through a layer in the reverse direction.\n", + "\n", + "\n", + "\n", + "One of the insights in the 2010 paper by Glorot and Bengio was that\n", + "the vanishing/exploding gradients problems were in part due to a poor\n", + "choice of activation function. Until then most people had assumed that\n", + "if Nature had chosen to use roughly sigmoid activation functions in\n", + "biological neurons, they must be an excellent choice. But it turns out\n", + "that other activation functions behave much better in deep neural\n", + "networks, in particular the ReLU activation function, mostly because\n", + "it does not saturate for positive values (and also because it is quite\n", + "fast to compute).\n", + "\n", + "\n", + "## The RELU function family\n", + "\n", + "The ReLU activation function suffers from a problem known as the dying\n", + "ReLUs: during training, some neurons effectively die, meaning they\n", + "stop outputting anything other than 0.\n", + "\n", + "In some cases, you may find that half of your network’s neurons are\n", + "dead, especially if you used a large learning rate. During training,\n", + "if a neuron’s weights get updated such that the weighted sum of the\n", + "neuron’s inputs is negative, it will start outputting 0. When this\n", + "happen, the neuron is unlikely to come back to life since the gradient\n", + "of the ReLU function is 0 when its input is negative.\n", + "\n", + "To solve this problem, nowadays practitioners use a variant of the ReLU\n", + "function, such as the leaky ReLU discussed above or the so-called\n", + "exponential linear unit (ELU) function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Which activation function should we use?\n", + "\n", + "In general it seems that the ELU activation function is better than\n", + "the leaky ReLU function (and its variants), which is better than\n", + "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", + "than the logistic function. \n", + "\n", + "If runtime\n", + "performance is an issue, then you may opt for the leaky ReLU function over the \n", + "ELU function If you don’t\n", + "want to tweak yet another hyperparameter, you may just use the default\n", + "$\\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have\n", + "spare time and computing power, you can use cross-validation or\n", + "bootstrap to evaluate other activation functions.\n", + "\n", + "\n", + "\n", + "## A top-down perspective on Neural networks\n", + "\n", + "\n", + "The first thing we would like to do is divide the data into two or three\n", + "parts. A training set, a validation or dev (development) set, and a\n", + "test set. The test set is the data on which we want to make\n", + "predictions. The dev set is a subset of the training data we use to\n", + "check how well we are doing out-of-sample, after training the model on\n", + "the training dataset. We use the validation error as a proxy for the\n", + "test error in order to make tweaks to our model. It is crucial that we\n", + "do not use any of the test data to train the algorithm. This is a\n", + "cardinal sin in ML. Then:\n", + "\n", + "\n", + "* Estimate optimal error rate\n", + "\n", + "* Minimize underfitting (bias) on training data set.\n", + "\n", + "* Make sure you are not overfitting.\n", + "\n", + "If the validation and test sets are drawn from the same distributions,\n", + "then a good performance on the validation set should lead to similarly\n", + "good performance on the test set. \n", + "\n", + "However, sometimes\n", + "the training data and test data differ in subtle ways because, for\n", + "example, they are collected using slightly different methods, or\n", + "because it is cheaper to collect data in one way versus another. In\n", + "this case, there can be a mismatch between the training and test\n", + "data. This can lead to the neural network overfitting these small\n", + "differences between the test and training sets, and a poor performance\n", + "on the test set despite having a good performance on the validation\n", + "set. To rectify this, Andrew Ng suggests making two validation or dev\n", + "sets, one constructed from the training data and one constructed from\n", + "the test data. The difference between the performance of the algorithm\n", + "on these two validation sets quantifies the train-test mismatch. This\n", + "can serve as another important diagnostic when using DNNs for\n", + "supervised learning.\n", + "\n", + "## Limitations of supervised learning with deep networks\n", + "\n", + "Like all statistical methods, supervised learning using neural\n", + "networks has important limitations. This is especially important when\n", + "one seeks to apply these methods, especially to physics problems. Like\n", + "all tools, DNNs are not a universal solution. Often, the same or\n", + "better performance on a task can be achieved by using a few\n", + "hand-engineered features (or even a collection of random\n", + "features). \n", + "\n", + "Here we list some of the important limitations of supervised neural network based models. \n", + "\n", + "\n", + "\n", + "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", + "\n", + "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.\n", + "\n", + "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.\n", + "\n", + "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", + "\n", + "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems." + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/pub/week41/html/._week41-bs000.html b/doc/pub/week41/html/._week41-bs000.html new file mode 100644 index 000000000..2d605a454 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs000.html @@ -0,0 +1,219 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +

 

 

 

+ + + + + + +
+

Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs001.html b/doc/pub/week41/html/._week41-bs001.html new file mode 100644 index 000000000..ebfb1bdde --- /dev/null +++ b/doc/pub/week41/html/._week41-bs001.html @@ -0,0 +1,229 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Convolutional Neural Networks (recognizing images)

+ +

+Convolutional neural networks (CNNs) were developed during the last +decade of the previous century, with a focus on character recognition +tasks. Nowadays, CNNs are a central element in the spectacular success +of dee learning methods. The success in for example image +classifications have made them a central tool for most machine +learning practitioners. + +

+CNNs are very similar to ordinary Neural Networks. +They are made up of neurons that have learnable weights and +biases. Each neuron receives some inputs, performs a dot product and +optionally follows it with a non-linearity. The whole network still +expresses a single differentiable score function: from the raw image +pixels on one end to class scores at the other. And they still have a +loss function (for example Softmax) on the last (fully-connected) layer +and all the tips/tricks we developed for learning regular Neural +Networks still apply (back propagation, gradient descent etc etc). + +

+What is the difference? CNN architectures make the explicit assumption that +the inputs are images, which allows us to encode certain properties +into the architecture. These then make the forward function more +efficient to implement and vastly reduce the amount of parameters in +the network. + +

+Here we provide only a superficial overview, for the more interested, we recommend highly the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231. + +

+Another good read is the article here https://arxiv.org/pdf/1603.07285.pdf. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs002.html b/doc/pub/week41/html/._week41-bs002.html new file mode 100644 index 000000000..9cd64b985 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs002.html @@ -0,0 +1,219 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Regular NNs don’t scale well to full images

+ +

+As an example, consider +an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a +single fully-connected neuron in a first hidden layer of a regular +Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still +seems manageable, but clearly this fully-connected structure does not +scale to larger images. For example, an image of more respectable +size, say \( 200\times 200\times 3 \), would lead to neurons that have +\( 200\times 200\times 3 = 120,000 \) weights. + +

+We could have +several such neurons, and the parameters would add up quickly! Clearly, +this full connectivity is wasteful and the huge number of parameters +would quickly lead to possible overfitting. + +

+

+
+

Figure 1: A regular 3-layer Neural Network.

+

+
+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs003.html b/doc/pub/week41/html/._week41-bs003.html new file mode 100644 index 000000000..c7d1e2c90 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs003.html @@ -0,0 +1,232 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

3D volumes of neurons

+ +

+Convolutional Neural Networks take advantage of the fact that the +input consists of images and they constrain the architecture in a more +sensible way. + +

+In particular, unlike a regular Neural Network, the +layers of a CNN have neurons arranged in 3 dimensions: width, +height, depth. (Note that the word depth here refers to the third +dimension of an activation volume, not to the depth of a full Neural +Network, which can refer to the total number of layers in a network.) + +

+To understand it better, the above example of an image +with an input volume of +activations has dimensions \( 32\times 32\times 3 \) (width, height, +depth respectively). + +

+The neurons in a layer will +only be connected to a small region of the layer before it, instead of +all of the neurons in a fully-connected manner. Moreover, the final +output layer could for this specific image have dimensions \( 1\times 1 \times 10 \), +because by the +end of the CNN architecture we will reduce the full image into a +single vector of class scores, arranged along the depth +dimension. + +

+

+
+

Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

+

+
+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs004.html b/doc/pub/week41/html/._week41-bs004.html new file mode 100644 index 000000000..701a7a0e4 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs004.html @@ -0,0 +1,216 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Layers used to build CNNs

+ +

+A simple CNN is a sequence of layers, and every layer of a CNN +transforms one volume of activations to another through a +differentiable function. We use three main types of layers to build +CNN architectures: Convolutional Layer, Pooling Layer, and +Fully-Connected Layer (exactly as seen in regular Neural Networks). We +will stack these layers to form a full CNN architecture. + +

+A simple CNN for image classification could have the architecture: + +

+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs005.html b/doc/pub/week41/html/._week41-bs005.html new file mode 100644 index 000000000..8ee02e01b --- /dev/null +++ b/doc/pub/week41/html/._week41-bs005.html @@ -0,0 +1,213 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Transforming images

+ +

+CNNs transform the original image layer by layer from the original +pixel values to the final class scores. + +

+Observe that some layers contain +parameters and other don’t. In particular, the CNN layers perform +transformations that are a function of not only the activations in the +input volume, but also of the parameters (the weights and biases of +the neurons). On the other hand, the RELU/POOL layers will implement a +fixed function. The parameters in the CONV/FC layers will be trained +with gradient descent so that the class scores that the CNN computes +are consistent with the labels in the training set for each image. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs006.html b/doc/pub/week41/html/._week41-bs006.html new file mode 100644 index 000000000..041a03b41 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs006.html @@ -0,0 +1,216 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

CNNs in brief

+ +

+In summary: + +

+ +For more material on convolutional networks, we strongly recommend +the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231 which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs007.html b/doc/pub/week41/html/._week41-bs007.html new file mode 100644 index 000000000..528796d71 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs007.html @@ -0,0 +1,212 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

CNNs in more detail, building convolutional neural networks in Tensorflow and Keras

+ +

+As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. + +

+As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs008.html b/doc/pub/week41/html/._week41-bs008.html new file mode 100644 index 000000000..41a92332c --- /dev/null +++ b/doc/pub/week41/html/._week41-bs008.html @@ -0,0 +1,209 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Setting it up

+ +

+It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs009.html b/doc/pub/week41/html/._week41-bs009.html new file mode 100644 index 000000000..79edd608d --- /dev/null +++ b/doc/pub/week41/html/._week41-bs009.html @@ -0,0 +1,216 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The MNIST dataset again

+ +

+The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. + +

+If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs010.html b/doc/pub/week41/html/._week41-bs010.html new file mode 100644 index 000000000..527c6f64f --- /dev/null +++ b/doc/pub/week41/html/._week41-bs010.html @@ -0,0 +1,215 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Strong correlations

+Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. + +

+Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs011.html b/doc/pub/week41/html/._week41-bs011.html new file mode 100644 index 000000000..dad56be77 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs011.html @@ -0,0 +1,221 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Layers of a CNN

+The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. + +

+A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. + +

+Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs012.html b/doc/pub/week41/html/._week41-bs012.html new file mode 100644 index 000000000..1f1d5303c --- /dev/null +++ b/doc/pub/week41/html/._week41-bs012.html @@ -0,0 +1,212 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Systematic reduction

+ +

+By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs013.html b/doc/pub/week41/html/._week41-bs013.html new file mode 100644 index 000000000..33119da27 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs013.html @@ -0,0 +1,244 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Prerequisites: Collect and pre-process data

+

+ + +

# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+# RGB images have a depth of 3
+# our images are grayscale so they should have a depth of 1
+inputs = inputs[:,:,:,np.newaxis]
+
+print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# choose some random images to display
+n_inputs = len(inputs)
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+    plt.subplot(1, 5, i+1)
+    plt.axis('off')
+    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+    plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs014.html b/doc/pub/week41/html/._week41-bs014.html new file mode 100644 index 000000000..6968789cc --- /dev/null +++ b/doc/pub/week41/html/._week41-bs014.html @@ -0,0 +1,215 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Importing Keras and Tensorflow

+

+ + +

from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+                                                    test_size=test_size)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs015.html b/doc/pub/week41/html/._week41-bs015.html new file mode 100644 index 000000000..e27b7bcf0 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs015.html @@ -0,0 +1,342 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Using TensorFlow backend

+ +

+We need to define model and architecture and choose cost function and optmizer. +

+ + +

import tensorflow as tf
+
+class ConvolutionalNeuralNetworkTensorflow:
+    def __init__(
+            self,
+            X_train,
+            Y_train,
+            X_test,
+            Y_test,
+            n_filters=10,
+            n_neurons_connected=50,
+            n_categories=10,
+            receptive_field=3,
+            stride=1,
+            padding=1,
+            epochs=10,
+            batch_size=100,
+            eta=0.1,
+            lmbd=0.0):
+        
+        self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+        
+        self.X_train = X_train
+        self.Y_train = Y_train
+        self.X_test = X_test
+        self.Y_test = Y_test
+        
+        self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
+        
+        self.n_filters = n_filters
+        self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
+        self.n_neurons_connected = n_neurons_connected
+        self.n_categories = n_categories
+        
+        self.receptive_field = receptive_field
+        self.stride = stride
+        self.strides = [stride, stride, stride, stride]
+        self.padding = padding
+        
+        self.epochs = epochs
+        self.batch_size = batch_size
+        self.iterations = self.n_inputs // self.batch_size
+        self.eta = eta
+        self.lmbd = lmbd
+        
+        self.create_placeholders()
+        self.create_CNN()
+        self.create_loss()
+        self.create_optimiser()
+        self.create_accuracy()
+    
+    def create_placeholders(self):
+        with tf.name_scope('data'):
+            self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
+            self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+    
+    def create_CNN(self):
+        with tf.name_scope('CNN'):
+            
+            # Convolutional layer
+            self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
+            b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
+            z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
+            a_conv = tf.nn.relu(z_conv)
+            
+            # 2x2 max pooling
+            a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
+            
+            # Fully connected layer
+            a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
+            self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
+            b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
+            a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
+            
+            # Output layer
+            self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
+            b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+            self.z_out = tf.matmul(a_fc, self.W_out) + b_out
+    
+    def create_loss(self):
+        with tf.name_scope('loss'):
+            softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+            
+            regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
+            regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
+            regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+            regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
+            
+            self.loss = softmax_loss + regularizer_loss
+
+    def create_accuracy(self):
+        with tf.name_scope('accuracy'):
+            probabilities = tf.nn.softmax(self.z_out)
+            predictions = tf.argmax(probabilities, 1)
+            labels = tf.argmax(self.Y, 1)
+            
+            correct_predictions = tf.equal(predictions, labels)
+            correct_predictions = tf.cast(correct_predictions, tf.float32)
+            self.accuracy = tf.reduce_mean(correct_predictions)
+    
+    def create_optimiser(self):
+        with tf.name_scope('optimizer'):
+            self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+            
+    def weight_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.truncated_normal(shape, stddev=0.1)
+        return tf.Variable(initial, name=name, dtype=dtype)
+    
+    def bias_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.constant(0.1, shape=shape)
+        return tf.Variable(initial, name=name, dtype=dtype)
+
+    def fit(self):
+        data_indices = np.arange(self.n_inputs)
+
+        with tf.Session() as sess:
+            sess.run(tf.global_variables_initializer())
+            for i in range(self.epochs):
+                for j in range(self.iterations):
+                    chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+                    batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+            
+                    sess.run([CNN.loss, CNN.optimizer],
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    accuracy = sess.run(CNN.accuracy,
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    step = sess.run(CNN.global_step)
+    
+            self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_train,
+                           CNN.Y: self.Y_train})
+        
+            self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_test,
+                           CNN.Y: self.Y_test})
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs016.html b/doc/pub/week41/html/._week41-bs016.html new file mode 100644 index 000000000..c6486199d --- /dev/null +++ b/doc/pub/week41/html/._week41-bs016.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Train the model

+ +

+We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. +

+ + +

epochs = 100
+batch_size = 100
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+                                      n_filters=n_filters, n_neurons_connected=n_neurons_connected,
+                                      n_categories=n_categories, epochs=epochs, batch_size=batch_size,
+                                      eta=eta, lmbd=lmbd)
+        CNN.fit()
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % CNN.test_accuracy)
+        print()
+            
+        CNN_tf[i][j] = CNN
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs017.html b/doc/pub/week41/html/._week41-bs017.html new file mode 100644 index 000000000..2667dae4b --- /dev/null +++ b/doc/pub/week41/html/._week41-bs017.html @@ -0,0 +1,231 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Visualizing the results

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_tf[i][j]
+
+        train_accuracy[i][j] = CNN.train_accuracy
+        test_accuracy[i][j] = CNN.test_accuracy
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs018.html b/doc/pub/week41/html/._week41-bs018.html new file mode 100644 index 000000000..cc2172079 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs018.html @@ -0,0 +1,234 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Running with Keras

+ +

+ + +

from keras.models import Sequential
+from keras.layers.convolutional import Conv2D
+from keras.layers.convolutional import MaxPooling2D
+from keras.layers import Flatten
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd):
+    model = Sequential()
+    model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
+              activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(MaxPooling2D(pool_size=(2, 2)))
+    model.add(Flatten())
+    model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
+    
+    sgd = SGD(lr=eta)
+    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+    
+    return model
+
+epochs = 100
+batch_size = 100
+input_shape = X_train.shape[1:4]
+receptive_field = 3
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs019.html b/doc/pub/week41/html/._week41-bs019.html new file mode 100644 index 000000000..f78036ff1 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs019.html @@ -0,0 +1,215 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Final part

+ +

+ + +

CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd)
+        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+        scores = CNN.evaluate(X_test, Y_test)
+        
+        CNN_keras[i][j] = CNN
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % scores[1])
+        print()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs020.html b/doc/pub/week41/html/._week41-bs020.html new file mode 100644 index 000000000..dd7b06487 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs020.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Final visualization

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_keras[i][j]
+
+        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
+        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/._week41-bs021.html b/doc/pub/week41/html/._week41-bs021.html new file mode 100644 index 000000000..275cd4af3 --- /dev/null +++ b/doc/pub/week41/html/._week41-bs021.html @@ -0,0 +1,197 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Fun links

+ +
    +
  1. Self-Driving cars using a convolutional neural network
  2. +
  3. Abstract art using convolutional neural networks
  4. +
+ + +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week41/html/reveal.js/.gitignore b/doc/pub/week41/html/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/pub/week41/html/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/pub/week41/html/reveal.js/.travis.yml b/doc/pub/week41/html/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/pub/week41/html/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/week41/html/reveal.js/CONTRIBUTING.md b/doc/pub/week41/html/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/pub/week41/html/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/pub/week41/html/reveal.js/Gruntfile.js b/doc/pub/week41/html/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/pub/week41/html/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/pub/week41/html/reveal.js/LICENSE b/doc/pub/week41/html/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/pub/week41/html/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/pub/week41/html/reveal.js/README.md b/doc/pub/week41/html/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/pub/week41/html/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
+
+
Single Horizontal Slide
+
+
Vertical Slide 1
+
Vertical Slide 2
+
+
+
+``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` +
+``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
+
+``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
+ +
+``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. + +```html +
+ +
+``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
+``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
+

All CSS color formats are supported, like rgba() or hsl().

+
+
+

This slide will have a full-size background image.

+
+
+

This background image will be sized to 100px and repeated.

+
+
+

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

+
+
+

Embeds a web page as a background. Note that the page won't be interactive.

+
+``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
+

This slide will override the presentation transition and zoom!

+
+ +
+

Choose from three transition speeds: default, fast or slow!

+
+``` + +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
+

grow

+

shrink

+

fade-out

+

visible only once

+

blue only once

+

highlight-red

+

highlight-green

+

highlight-blue

+
+``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
+ + I'll fade in, then out + +
+``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
+

Appears last

+

Appears first

+

Appears second

+
+``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
+

+(def lazy-fib
+  (concat
+   [0 1]
+   ((fn rfib [a b]
+        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
+	
+
+``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `
+ +
+ +

 

 

 

+ + + + + + +
+

Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week41/html/week41-reveal.html b/doc/pub/week41/html/week41-reveal.html new file mode 100644 index 000000000..755f227a9 --- /dev/null +++ b/doc/pub/week41/html/week41-reveal.html @@ -0,0 +1,993 @@ + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + + + + + + + + + + +
+ + + + +

Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

 
+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

 
+

Sep 16, 2020

+
+

+ +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+
+ + +
+

Convolutional Neural Networks (recognizing images)

+ +

+Convolutional neural networks (CNNs) were developed during the last +decade of the previous century, with a focus on character recognition +tasks. Nowadays, CNNs are a central element in the spectacular success +of dee learning methods. The success in for example image +classifications have made them a central tool for most machine +learning practitioners. + +

+CNNs are very similar to ordinary Neural Networks. +They are made up of neurons that have learnable weights and +biases. Each neuron receives some inputs, performs a dot product and +optionally follows it with a non-linearity. The whole network still +expresses a single differentiable score function: from the raw image +pixels on one end to class scores at the other. And they still have a +loss function (for example Softmax) on the last (fully-connected) layer +and all the tips/tricks we developed for learning regular Neural +Networks still apply (back propagation, gradient descent etc etc). + +

+What is the difference? CNN architectures make the explicit assumption that +the inputs are images, which allows us to encode certain properties +into the architecture. These then make the forward function more +efficient to implement and vastly reduce the amount of parameters in +the network. + +

+Here we provide only a superficial overview, for the more interested, we recommend highly the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231. + +

+Another good read is the article here https://arxiv.org/pdf/1603.07285.pdf. +

+ + +
+

Regular NNs don’t scale well to full images

+ +

+As an example, consider +an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a +single fully-connected neuron in a first hidden layer of a regular +Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still +seems manageable, but clearly this fully-connected structure does not +scale to larger images. For example, an image of more respectable +size, say \( 200\times 200\times 3 \), would lead to neurons that have +\( 200\times 200\times 3 = 120,000 \) weights. + +

+We could have +several such neurons, and the parameters would add up quickly! Clearly, +this full connectivity is wasteful and the huge number of parameters +would quickly lead to possible overfitting. + +

+

+
+

Figure 1: A regular 3-layer Neural Network.

+

+
+
+ + +
+

3D volumes of neurons

+ +

+Convolutional Neural Networks take advantage of the fact that the +input consists of images and they constrain the architecture in a more +sensible way. + +

+In particular, unlike a regular Neural Network, the +layers of a CNN have neurons arranged in 3 dimensions: width, +height, depth. (Note that the word depth here refers to the third +dimension of an activation volume, not to the depth of a full Neural +Network, which can refer to the total number of layers in a network.) + +

+To understand it better, the above example of an image +with an input volume of +activations has dimensions \( 32\times 32\times 3 \) (width, height, +depth respectively). + +

+The neurons in a layer will +only be connected to a small region of the layer before it, instead of +all of the neurons in a fully-connected manner. Moreover, the final +output layer could for this specific image have dimensions \( 1\times 1 \times 10 \), +because by the +end of the CNN architecture we will reduce the full image into a +single vector of class scores, arranged along the depth +dimension. + +

+

+
+

Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

+

+
+
+ + +
+

Layers used to build CNNs

+ +

+A simple CNN is a sequence of layers, and every layer of a CNN +transforms one volume of activations to another through a +differentiable function. We use three main types of layers to build +CNN architectures: Convolutional Layer, Pooling Layer, and +Fully-Connected Layer (exactly as seen in regular Neural Networks). We +will stack these layers to form a full CNN architecture. + +

+A simple CNN for image classification could have the architecture: + +

    +

  • INPUT (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
  • +

  • CONV (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.
  • +

  • RELU layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).
  • +

  • POOL (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).
  • +

  • FC (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
  • +
+
+ + +
+

Transforming images

+ +

+CNNs transform the original image layer by layer from the original +pixel values to the final class scores. + +

+Observe that some layers contain +parameters and other don’t. In particular, the CNN layers perform +transformations that are a function of not only the activations in the +input volume, but also of the parameters (the weights and biases of +the neurons). On the other hand, the RELU/POOL layers will implement a +fixed function. The parameters in the CONV/FC layers will be trained +with gradient descent so that the class scores that the CNN computes +are consistent with the labels in the training set for each image. +

+ + +
+

CNNs in brief

+ +

+In summary: + +

    +

  • A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
  • +

  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
  • +

  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
  • +

  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
  • +

  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
  • +
+

+ +For more material on convolutional networks, we strongly recommend +the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231 which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs. +

+ + +
+

CNNs in more detail, building convolutional neural networks in Tensorflow and Keras

+ +

+As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. + +

+As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). +

+ + +
+

Setting it up

+ +

+It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: + +

 
+$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ +

 
+

+ + +
+

The MNIST dataset again

+ +

+The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. + +

+If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. +

+ + +
+

Strong correlations

+Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. + +

+Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. +

+ + +
+

Layers of a CNN

+The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. + +

+A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. + +

+Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. +

+ + +
+

Systematic reduction

+ +

+By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. +

+ + +
+

Prerequisites: Collect and pre-process data

+

+ + +

# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+# RGB images have a depth of 3
+# our images are grayscale so they should have a depth of 1
+inputs = inputs[:,:,:,np.newaxis]
+
+print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# choose some random images to display
+n_inputs = len(inputs)
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+    plt.subplot(1, 5, i+1)
+    plt.axis('off')
+    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+    plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+
+
+ + +
+

Importing Keras and Tensorflow

+

+ + +

from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+                                                    test_size=test_size)
+
+
+ + +
+

Using TensorFlow backend

+ +

+We need to define model and architecture and choose cost function and optmizer. +

+ + +

import tensorflow as tf
+
+class ConvolutionalNeuralNetworkTensorflow:
+    def __init__(
+            self,
+            X_train,
+            Y_train,
+            X_test,
+            Y_test,
+            n_filters=10,
+            n_neurons_connected=50,
+            n_categories=10,
+            receptive_field=3,
+            stride=1,
+            padding=1,
+            epochs=10,
+            batch_size=100,
+            eta=0.1,
+            lmbd=0.0):
+        
+        self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+        
+        self.X_train = X_train
+        self.Y_train = Y_train
+        self.X_test = X_test
+        self.Y_test = Y_test
+        
+        self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
+        
+        self.n_filters = n_filters
+        self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
+        self.n_neurons_connected = n_neurons_connected
+        self.n_categories = n_categories
+        
+        self.receptive_field = receptive_field
+        self.stride = stride
+        self.strides = [stride, stride, stride, stride]
+        self.padding = padding
+        
+        self.epochs = epochs
+        self.batch_size = batch_size
+        self.iterations = self.n_inputs // self.batch_size
+        self.eta = eta
+        self.lmbd = lmbd
+        
+        self.create_placeholders()
+        self.create_CNN()
+        self.create_loss()
+        self.create_optimiser()
+        self.create_accuracy()
+    
+    def create_placeholders(self):
+        with tf.name_scope('data'):
+            self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
+            self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+    
+    def create_CNN(self):
+        with tf.name_scope('CNN'):
+            
+            # Convolutional layer
+            self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
+            b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
+            z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
+            a_conv = tf.nn.relu(z_conv)
+            
+            # 2x2 max pooling
+            a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
+            
+            # Fully connected layer
+            a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
+            self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
+            b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
+            a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
+            
+            # Output layer
+            self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
+            b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+            self.z_out = tf.matmul(a_fc, self.W_out) + b_out
+    
+    def create_loss(self):
+        with tf.name_scope('loss'):
+            softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+            
+            regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
+            regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
+            regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+            regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
+            
+            self.loss = softmax_loss + regularizer_loss
+
+    def create_accuracy(self):
+        with tf.name_scope('accuracy'):
+            probabilities = tf.nn.softmax(self.z_out)
+            predictions = tf.argmax(probabilities, 1)
+            labels = tf.argmax(self.Y, 1)
+            
+            correct_predictions = tf.equal(predictions, labels)
+            correct_predictions = tf.cast(correct_predictions, tf.float32)
+            self.accuracy = tf.reduce_mean(correct_predictions)
+    
+    def create_optimiser(self):
+        with tf.name_scope('optimizer'):
+            self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+            
+    def weight_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.truncated_normal(shape, stddev=0.1)
+        return tf.Variable(initial, name=name, dtype=dtype)
+    
+    def bias_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.constant(0.1, shape=shape)
+        return tf.Variable(initial, name=name, dtype=dtype)
+
+    def fit(self):
+        data_indices = np.arange(self.n_inputs)
+
+        with tf.Session() as sess:
+            sess.run(tf.global_variables_initializer())
+            for i in range(self.epochs):
+                for j in range(self.iterations):
+                    chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+                    batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+            
+                    sess.run([CNN.loss, CNN.optimizer],
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    accuracy = sess.run(CNN.accuracy,
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    step = sess.run(CNN.global_step)
+    
+            self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_train,
+                           CNN.Y: self.Y_train})
+        
+            self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_test,
+                           CNN.Y: self.Y_test})
+
+
+ + +
+

Train the model

+ +

+We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. +

+ + +

epochs = 100
+batch_size = 100
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+                                      n_filters=n_filters, n_neurons_connected=n_neurons_connected,
+                                      n_categories=n_categories, epochs=epochs, batch_size=batch_size,
+                                      eta=eta, lmbd=lmbd)
+        CNN.fit()
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % CNN.test_accuracy)
+        print()
+            
+        CNN_tf[i][j] = CNN
+
+
+ + +
+

Visualizing the results

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_tf[i][j]
+
+        train_accuracy[i][j] = CNN.train_accuracy
+        test_accuracy[i][j] = CNN.test_accuracy
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+
+ + +
+

Running with Keras

+ +

+ + +

from keras.models import Sequential
+from keras.layers.convolutional import Conv2D
+from keras.layers.convolutional import MaxPooling2D
+from keras.layers import Flatten
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd):
+    model = Sequential()
+    model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
+              activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(MaxPooling2D(pool_size=(2, 2)))
+    model.add(Flatten())
+    model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
+    
+    sgd = SGD(lr=eta)
+    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+    
+    return model
+
+epochs = 100
+batch_size = 100
+input_shape = X_train.shape[1:4]
+receptive_field = 3
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+
+
+ + +
+

Final part

+ +

+ + +

CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd)
+        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+        scores = CNN.evaluate(X_test, Y_test)
+        
+        CNN_keras[i][j] = CNN
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % scores[1])
+        print()
+
+
+ + +
+

Final visualization

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_keras[i][j]
+
+        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
+        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+
+ + +
+

Fun links

+ +
    +

  1. Self-Driving cars using a convolutional neural network
  2. +

  3. Abstract art using convolutional neural networks
  4. +
+
+ + + +
+
+ + + + + + + + + + + + diff --git a/doc/pub/week41/html/week41-solarized.html b/doc/pub/week41/html/week41-solarized.html new file mode 100644 index 000000000..1a169875d --- /dev/null +++ b/doc/pub/week41/html/week41-solarized.html @@ -0,0 +1,803 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Convolutional Neural Networks (recognizing images)

+ +

+Convolutional neural networks (CNNs) were developed during the last +decade of the previous century, with a focus on character recognition +tasks. Nowadays, CNNs are a central element in the spectacular success +of dee learning methods. The success in for example image +classifications have made them a central tool for most machine +learning practitioners. + +

+CNNs are very similar to ordinary Neural Networks. +They are made up of neurons that have learnable weights and +biases. Each neuron receives some inputs, performs a dot product and +optionally follows it with a non-linearity. The whole network still +expresses a single differentiable score function: from the raw image +pixels on one end to class scores at the other. And they still have a +loss function (for example Softmax) on the last (fully-connected) layer +and all the tips/tricks we developed for learning regular Neural +Networks still apply (back propagation, gradient descent etc etc). + +

+What is the difference? CNN architectures make the explicit assumption that +the inputs are images, which allows us to encode certain properties +into the architecture. These then make the forward function more +efficient to implement and vastly reduce the amount of parameters in +the network. + +

+Here we provide only a superficial overview, for the more interested, we recommend highly the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231. + +

+Another good read is the article here https://arxiv.org/pdf/1603.07285.pdf. + +

+









+ +

Regular NNs don’t scale well to full images

+ +

+As an example, consider +an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a +single fully-connected neuron in a first hidden layer of a regular +Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still +seems manageable, but clearly this fully-connected structure does not +scale to larger images. For example, an image of more respectable +size, say \( 200\times 200\times 3 \), would lead to neurons that have +\( 200\times 200\times 3 = 120,000 \) weights. + +

+We could have +several such neurons, and the parameters would add up quickly! Clearly, +this full connectivity is wasteful and the huge number of parameters +would quickly lead to possible overfitting. + +

+

+
+

Figure 1: A regular 3-layer Neural Network.

+

+
+ +

+









+ +

3D volumes of neurons

+ +

+Convolutional Neural Networks take advantage of the fact that the +input consists of images and they constrain the architecture in a more +sensible way. + +

+In particular, unlike a regular Neural Network, the +layers of a CNN have neurons arranged in 3 dimensions: width, +height, depth. (Note that the word depth here refers to the third +dimension of an activation volume, not to the depth of a full Neural +Network, which can refer to the total number of layers in a network.) + +

+To understand it better, the above example of an image +with an input volume of +activations has dimensions \( 32\times 32\times 3 \) (width, height, +depth respectively). + +

+The neurons in a layer will +only be connected to a small region of the layer before it, instead of +all of the neurons in a fully-connected manner. Moreover, the final +output layer could for this specific image have dimensions \( 1\times 1 \times 10 \), +because by the +end of the CNN architecture we will reduce the full image into a +single vector of class scores, arranged along the depth +dimension. + +

+

+
+

Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

+

+
+ +

+ + +

Layers used to build CNNs

+ +

+A simple CNN is a sequence of layers, and every layer of a CNN +transforms one volume of activations to another through a +differentiable function. We use three main types of layers to build +CNN architectures: Convolutional Layer, Pooling Layer, and +Fully-Connected Layer (exactly as seen in regular Neural Networks). We +will stack these layers to form a full CNN architecture. + +

+A simple CNN for image classification could have the architecture: + +

    +
  • INPUT (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
  • +
  • CONV (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.
  • +
  • RELU layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).
  • +
  • POOL (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).
  • +
  • FC (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
  • +
+ +









+ +

Transforming images

+ +

+CNNs transform the original image layer by layer from the original +pixel values to the final class scores. + +

+Observe that some layers contain +parameters and other don’t. In particular, the CNN layers perform +transformations that are a function of not only the activations in the +input volume, but also of the parameters (the weights and biases of +the neurons). On the other hand, the RELU/POOL layers will implement a +fixed function. The parameters in the CONV/FC layers will be trained +with gradient descent so that the class scores that the CNN computes +are consistent with the labels in the training set for each image. + +

+









+ +

CNNs in brief

+ +

+In summary: + +

    +
  • A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
  • +
  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
  • +
  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
  • +
  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
  • +
  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
  • +
+ +For more material on convolutional networks, we strongly recommend +the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231 which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs. + +

+









+ +

CNNs in more detail, building convolutional neural networks in Tensorflow and Keras

+ +

+As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. + +

+As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). + +

+









+ +

Setting it up

+ +

+It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ + +

+









+ +

The MNIST dataset again

+ +

+The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. + +

+If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. + +

+









+ +

Strong correlations

+Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. + +

+Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. + +

+ + +

Layers of a CNN

+The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. + +

+A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. + +

+Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. + +

+









+ +

Systematic reduction

+ +

+By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. + +

+









+ +

Prerequisites: Collect and pre-process data

+

+ + +

# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+# RGB images have a depth of 3
+# our images are grayscale so they should have a depth of 1
+inputs = inputs[:,:,:,np.newaxis]
+
+print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# choose some random images to display
+n_inputs = len(inputs)
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+    plt.subplot(1, 5, i+1)
+    plt.axis('off')
+    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+    plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+
+

+









+ +

Importing Keras and Tensorflow

+

+ + +

from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+                                                    test_size=test_size)
+
+

+









+ +

Using TensorFlow backend

+ +

+We need to define model and architecture and choose cost function and optmizer. +

+ + +

import tensorflow as tf
+
+class ConvolutionalNeuralNetworkTensorflow:
+    def __init__(
+            self,
+            X_train,
+            Y_train,
+            X_test,
+            Y_test,
+            n_filters=10,
+            n_neurons_connected=50,
+            n_categories=10,
+            receptive_field=3,
+            stride=1,
+            padding=1,
+            epochs=10,
+            batch_size=100,
+            eta=0.1,
+            lmbd=0.0):
+        
+        self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+        
+        self.X_train = X_train
+        self.Y_train = Y_train
+        self.X_test = X_test
+        self.Y_test = Y_test
+        
+        self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
+        
+        self.n_filters = n_filters
+        self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
+        self.n_neurons_connected = n_neurons_connected
+        self.n_categories = n_categories
+        
+        self.receptive_field = receptive_field
+        self.stride = stride
+        self.strides = [stride, stride, stride, stride]
+        self.padding = padding
+        
+        self.epochs = epochs
+        self.batch_size = batch_size
+        self.iterations = self.n_inputs // self.batch_size
+        self.eta = eta
+        self.lmbd = lmbd
+        
+        self.create_placeholders()
+        self.create_CNN()
+        self.create_loss()
+        self.create_optimiser()
+        self.create_accuracy()
+    
+    def create_placeholders(self):
+        with tf.name_scope('data'):
+            self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
+            self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+    
+    def create_CNN(self):
+        with tf.name_scope('CNN'):
+            
+            # Convolutional layer
+            self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
+            b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
+            z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
+            a_conv = tf.nn.relu(z_conv)
+            
+            # 2x2 max pooling
+            a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
+            
+            # Fully connected layer
+            a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
+            self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
+            b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
+            a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
+            
+            # Output layer
+            self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
+            b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+            self.z_out = tf.matmul(a_fc, self.W_out) + b_out
+    
+    def create_loss(self):
+        with tf.name_scope('loss'):
+            softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+            
+            regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
+            regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
+            regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+            regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
+            
+            self.loss = softmax_loss + regularizer_loss
+
+    def create_accuracy(self):
+        with tf.name_scope('accuracy'):
+            probabilities = tf.nn.softmax(self.z_out)
+            predictions = tf.argmax(probabilities, 1)
+            labels = tf.argmax(self.Y, 1)
+            
+            correct_predictions = tf.equal(predictions, labels)
+            correct_predictions = tf.cast(correct_predictions, tf.float32)
+            self.accuracy = tf.reduce_mean(correct_predictions)
+    
+    def create_optimiser(self):
+        with tf.name_scope('optimizer'):
+            self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+            
+    def weight_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.truncated_normal(shape, stddev=0.1)
+        return tf.Variable(initial, name=name, dtype=dtype)
+    
+    def bias_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.constant(0.1, shape=shape)
+        return tf.Variable(initial, name=name, dtype=dtype)
+
+    def fit(self):
+        data_indices = np.arange(self.n_inputs)
+
+        with tf.Session() as sess:
+            sess.run(tf.global_variables_initializer())
+            for i in range(self.epochs):
+                for j in range(self.iterations):
+                    chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+                    batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+            
+                    sess.run([CNN.loss, CNN.optimizer],
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    accuracy = sess.run(CNN.accuracy,
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    step = sess.run(CNN.global_step)
+    
+            self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_train,
+                           CNN.Y: self.Y_train})
+        
+            self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_test,
+                           CNN.Y: self.Y_test})
+
+

+









+ +

Train the model

+ +

+We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. +

+ + +

epochs = 100
+batch_size = 100
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+                                      n_filters=n_filters, n_neurons_connected=n_neurons_connected,
+                                      n_categories=n_categories, epochs=epochs, batch_size=batch_size,
+                                      eta=eta, lmbd=lmbd)
+        CNN.fit()
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % CNN.test_accuracy)
+        print()
+            
+        CNN_tf[i][j] = CNN
+
+

+









+ +

Visualizing the results

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_tf[i][j]
+
+        train_accuracy[i][j] = CNN.train_accuracy
+        test_accuracy[i][j] = CNN.test_accuracy
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+

+ + +

Running with Keras

+ +

+ + +

from keras.models import Sequential
+from keras.layers.convolutional import Conv2D
+from keras.layers.convolutional import MaxPooling2D
+from keras.layers import Flatten
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd):
+    model = Sequential()
+    model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
+              activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(MaxPooling2D(pool_size=(2, 2)))
+    model.add(Flatten())
+    model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
+    
+    sgd = SGD(lr=eta)
+    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+    
+    return model
+
+epochs = 100
+batch_size = 100
+input_shape = X_train.shape[1:4]
+receptive_field = 3
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+
+

+









+ +

Final part

+ +

+ + +

CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd)
+        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+        scores = CNN.evaluate(X_test, Y_test)
+        
+        CNN_keras[i][j] = CNN
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % scores[1])
+        print()
+
+

+









+ +

Final visualization

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_keras[i][j]
+
+        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
+        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+

+









+ +

Fun links

+ +
    +
  1. Self-Driving cars using a convolutional neural network
  2. +
  3. Abstract art using convolutional neural networks
  4. +
+ + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week41/html/week41.html b/doc/pub/week41/html/week41.html new file mode 100644 index 000000000..96486431c --- /dev/null +++ b/doc/pub/week41/html/week41.html @@ -0,0 +1,808 @@ + + + + + + + + +Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks + + + + + + + + + + + + + + + + + + + + + + + +

Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Convolutional Neural Networks (recognizing images)

+ +

+Convolutional neural networks (CNNs) were developed during the last +decade of the previous century, with a focus on character recognition +tasks. Nowadays, CNNs are a central element in the spectacular success +of dee learning methods. The success in for example image +classifications have made them a central tool for most machine +learning practitioners. + +

+CNNs are very similar to ordinary Neural Networks. +They are made up of neurons that have learnable weights and +biases. Each neuron receives some inputs, performs a dot product and +optionally follows it with a non-linearity. The whole network still +expresses a single differentiable score function: from the raw image +pixels on one end to class scores at the other. And they still have a +loss function (for example Softmax) on the last (fully-connected) layer +and all the tips/tricks we developed for learning regular Neural +Networks still apply (back propagation, gradient descent etc etc). + +

+What is the difference? CNN architectures make the explicit assumption that +the inputs are images, which allows us to encode certain properties +into the architecture. These then make the forward function more +efficient to implement and vastly reduce the amount of parameters in +the network. + +

+Here we provide only a superficial overview, for the more interested, we recommend highly the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231. + +

+Another good read is the article here https://arxiv.org/pdf/1603.07285.pdf. + +

+









+ +

Regular NNs don’t scale well to full images

+ +

+As an example, consider +an image of size \( 32\times 32\times 3 \) (32 wide, 32 high, 3 color channels), so a +single fully-connected neuron in a first hidden layer of a regular +Neural Network would have \( 32\times 32\times 3 = 3072 \) weights. This amount still +seems manageable, but clearly this fully-connected structure does not +scale to larger images. For example, an image of more respectable +size, say \( 200\times 200\times 3 \), would lead to neurons that have +\( 200\times 200\times 3 = 120,000 \) weights. + +

+We could have +several such neurons, and the parameters would add up quickly! Clearly, +this full connectivity is wasteful and the huge number of parameters +would quickly lead to possible overfitting. + +

+

+
+

Figure 1: A regular 3-layer Neural Network.

+

+
+ +

+









+ +

3D volumes of neurons

+ +

+Convolutional Neural Networks take advantage of the fact that the +input consists of images and they constrain the architecture in a more +sensible way. + +

+In particular, unlike a regular Neural Network, the +layers of a CNN have neurons arranged in 3 dimensions: width, +height, depth. (Note that the word depth here refers to the third +dimension of an activation volume, not to the depth of a full Neural +Network, which can refer to the total number of layers in a network.) + +

+To understand it better, the above example of an image +with an input volume of +activations has dimensions \( 32\times 32\times 3 \) (width, height, +depth respectively). + +

+The neurons in a layer will +only be connected to a small region of the layer before it, instead of +all of the neurons in a fully-connected manner. Moreover, the final +output layer could for this specific image have dimensions \( 1\times 1 \times 10 \), +because by the +end of the CNN architecture we will reduce the full image into a +single vector of class scores, arranged along the depth +dimension. + +

+

+
+

Figure 2: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

+

+
+ +

+ + +

Layers used to build CNNs

+ +

+A simple CNN is a sequence of layers, and every layer of a CNN +transforms one volume of activations to another through a +differentiable function. We use three main types of layers to build +CNN architectures: Convolutional Layer, Pooling Layer, and +Fully-Connected Layer (exactly as seen in regular Neural Networks). We +will stack these layers to form a full CNN architecture. + +

+A simple CNN for image classification could have the architecture: + +

    +
  • INPUT (\( 32\times 32 \times 3 \)) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
  • +
  • CONV (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as \( [32\times 32\times 12] \) if we decided to use 12 filters.
  • +
  • RELU layer will apply an elementwise activation function, such as the \( max(0,x) \) thresholding at zero. This leaves the size of the volume unchanged (\( [32\times 32\times 12] \)).
  • +
  • POOL (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as \( [16\times 16\times 12] \).
  • +
  • FC (i.e. fully-connected) layer will compute the class scores, resulting in volume of size \( [1\times 1\times 10] \), where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
  • +
+ +









+ +

Transforming images

+ +

+CNNs transform the original image layer by layer from the original +pixel values to the final class scores. + +

+Observe that some layers contain +parameters and other don’t. In particular, the CNN layers perform +transformations that are a function of not only the activations in the +input volume, but also of the parameters (the weights and biases of +the neurons). On the other hand, the RELU/POOL layers will implement a +fixed function. The parameters in the CONV/FC layers will be trained +with gradient descent so that the class scores that the CNN computes +are consistent with the labels in the training set for each image. + +

+









+ +

CNNs in brief

+ +

+In summary: + +

    +
  • A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
  • +
  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
  • +
  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
  • +
  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
  • +
  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
  • +
+ +For more material on convolutional networks, we strongly recommend +the course +IN5400 – Machine Learning for Image Analysis +and the slides of CS231 which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs. + +

+









+ +

CNNs in more detail, building convolutional neural networks in Tensorflow and Keras

+ +

+As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. + +

+As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). + +

+









+ +

Setting it up

+ +

+It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ + +

+









+ +

The MNIST dataset again

+ +

+The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. + +

+If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. + +

+









+ +

Strong correlations

+Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. + +

+Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. + +

+ + +

Layers of a CNN

+The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. + +

+A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. + +

+Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. + +

+









+ +

Systematic reduction

+ +

+By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. + +

+









+ +

Prerequisites: Collect and pre-process data

+

+ + +

# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+# RGB images have a depth of 3
+# our images are grayscale so they should have a depth of 1
+inputs = inputs[:,:,:,np.newaxis]
+
+print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# choose some random images to display
+n_inputs = len(inputs)
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+    plt.subplot(1, 5, i+1)
+    plt.axis('off')
+    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+    plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
+
+

+









+ +

Importing Keras and Tensorflow

+

+ + +

from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+# one-liner from scikit-learn library
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+                                                    test_size=test_size)
+
+

+









+ +

Using TensorFlow backend

+ +

+We need to define model and architecture and choose cost function and optmizer. +

+ + +

import tensorflow as tf
+
+class ConvolutionalNeuralNetworkTensorflow:
+    def __init__(
+            self,
+            X_train,
+            Y_train,
+            X_test,
+            Y_test,
+            n_filters=10,
+            n_neurons_connected=50,
+            n_categories=10,
+            receptive_field=3,
+            stride=1,
+            padding=1,
+            epochs=10,
+            batch_size=100,
+            eta=0.1,
+            lmbd=0.0):
+        
+        self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+        
+        self.X_train = X_train
+        self.Y_train = Y_train
+        self.X_test = X_test
+        self.Y_test = Y_test
+        
+        self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
+        
+        self.n_filters = n_filters
+        self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
+        self.n_neurons_connected = n_neurons_connected
+        self.n_categories = n_categories
+        
+        self.receptive_field = receptive_field
+        self.stride = stride
+        self.strides = [stride, stride, stride, stride]
+        self.padding = padding
+        
+        self.epochs = epochs
+        self.batch_size = batch_size
+        self.iterations = self.n_inputs // self.batch_size
+        self.eta = eta
+        self.lmbd = lmbd
+        
+        self.create_placeholders()
+        self.create_CNN()
+        self.create_loss()
+        self.create_optimiser()
+        self.create_accuracy()
+    
+    def create_placeholders(self):
+        with tf.name_scope('data'):
+            self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
+            self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+    
+    def create_CNN(self):
+        with tf.name_scope('CNN'):
+            
+            # Convolutional layer
+            self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
+            b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
+            z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
+            a_conv = tf.nn.relu(z_conv)
+            
+            # 2x2 max pooling
+            a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
+            
+            # Fully connected layer
+            a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
+            self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
+            b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
+            a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
+            
+            # Output layer
+            self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
+            b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+            self.z_out = tf.matmul(a_fc, self.W_out) + b_out
+    
+    def create_loss(self):
+        with tf.name_scope('loss'):
+            softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+            
+            regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
+            regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
+            regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+            regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
+            
+            self.loss = softmax_loss + regularizer_loss
+
+    def create_accuracy(self):
+        with tf.name_scope('accuracy'):
+            probabilities = tf.nn.softmax(self.z_out)
+            predictions = tf.argmax(probabilities, 1)
+            labels = tf.argmax(self.Y, 1)
+            
+            correct_predictions = tf.equal(predictions, labels)
+            correct_predictions = tf.cast(correct_predictions, tf.float32)
+            self.accuracy = tf.reduce_mean(correct_predictions)
+    
+    def create_optimiser(self):
+        with tf.name_scope('optimizer'):
+            self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+            
+    def weight_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.truncated_normal(shape, stddev=0.1)
+        return tf.Variable(initial, name=name, dtype=dtype)
+    
+    def bias_variable(self, shape, name='', dtype=tf.float32):
+        initial = tf.constant(0.1, shape=shape)
+        return tf.Variable(initial, name=name, dtype=dtype)
+
+    def fit(self):
+        data_indices = np.arange(self.n_inputs)
+
+        with tf.Session() as sess:
+            sess.run(tf.global_variables_initializer())
+            for i in range(self.epochs):
+                for j in range(self.iterations):
+                    chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+                    batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+            
+                    sess.run([CNN.loss, CNN.optimizer],
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    accuracy = sess.run(CNN.accuracy,
+                        feed_dict={CNN.X: batch_X,
+                                   CNN.Y: batch_Y})
+                    step = sess.run(CNN.global_step)
+    
+            self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_train,
+                           CNN.Y: self.Y_train})
+        
+            self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
+                feed_dict={CNN.X: self.X_test,
+                           CNN.Y: self.Y_test})
+
+

+









+ +

Train the model

+ +

+We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters. +

+ + +

epochs = 100
+batch_size = 100
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+                                      n_filters=n_filters, n_neurons_connected=n_neurons_connected,
+                                      n_categories=n_categories, epochs=epochs, batch_size=batch_size,
+                                      eta=eta, lmbd=lmbd)
+        CNN.fit()
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % CNN.test_accuracy)
+        print()
+            
+        CNN_tf[i][j] = CNN
+
+

+









+ +

Visualizing the results

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_tf[i][j]
+
+        train_accuracy[i][j] = CNN.train_accuracy
+        test_accuracy[i][j] = CNN.test_accuracy
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+

+ + +

Running with Keras

+ +

+ + +

from keras.models import Sequential
+from keras.layers.convolutional import Conv2D
+from keras.layers.convolutional import MaxPooling2D
+from keras.layers import Flatten
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd):
+    model = Sequential()
+    model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
+              activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(MaxPooling2D(pool_size=(2, 2)))
+    model.add(Flatten())
+    model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
+    model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
+    
+    sgd = SGD(lr=eta)
+    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+    
+    return model
+
+epochs = 100
+batch_size = 100
+input_shape = X_train.shape[1:4]
+receptive_field = 3
+n_filters = 10
+n_neurons_connected = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
+
+

+









+ +

Final part

+ +

+ + +

CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+        
+for i, eta in enumerate(eta_vals):
+    for j, lmbd in enumerate(lmbd_vals):
+        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
+                                              n_filters, n_neurons_connected, n_categories,
+                                              eta, lmbd)
+        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+        scores = CNN.evaluate(X_test, Y_test)
+        
+        CNN_keras[i][j] = CNN
+        
+        print("Learning rate = ", eta)
+        print("Lambda = ", lmbd)
+        print("Test accuracy: %.3f" % scores[1])
+        print()
+
+

+









+ +

Final visualization

+ +

+ + +

# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+    for j in range(len(lmbd_vals)):
+        CNN = CNN_keras[i][j]
+
+        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
+        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
+
+        
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+

+









+ +

Fun links

+ +
    +
  1. Self-Driving cars using a convolutional neural network
  2. +
  3. Abstract art using convolutional neural networks
  4. +
+ + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz new file mode 100644 index 000000000..c6f20f9c7 Binary files /dev/null and b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz differ diff --git a/doc/pub/week41/ipynb/week41.ipynb b/doc/pub/week41/ipynb/week41.ipynb new file mode 100644 index 000000000..8230ccc2a --- /dev/null +++ b/doc/pub/week41/ipynb/week41.ipynb @@ -0,0 +1,737 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "\n", + "## Convolutional Neural Networks (recognizing images)\n", + "\n", + "\n", + "Convolutional neural networks (CNNs) were developed during the last\n", + "decade of the previous century, with a focus on character recognition\n", + "tasks. Nowadays, CNNs are a central element in the spectacular success\n", + "of dee learning methods. The success in for example image\n", + "classifications have made them a central tool for most machine\n", + "learning practitioners.\n", + "\n", + "CNNs are very similar to ordinary Neural Networks.\n", + "They are made up of neurons that have learnable weights and\n", + "biases. Each neuron receives some inputs, performs a dot product and\n", + "optionally follows it with a non-linearity. The whole network still\n", + "expresses a single differentiable score function: from the raw image\n", + "pixels on one end to class scores at the other. And they still have a\n", + "loss function (for example Softmax) on the last (fully-connected) layer\n", + "and all the tips/tricks we developed for learning regular Neural\n", + "Networks still apply (back propagation, gradient descent etc etc).\n", + "\n", + "What is the difference? **CNN architectures make the explicit assumption that\n", + "the inputs are images, which allows us to encode certain properties\n", + "into the architecture. These then make the forward function more\n", + "efficient to implement and vastly reduce the amount of parameters in\n", + "the network.**\n", + "\n", + "Here we provide only a superficial overview, for the more interested, we recommend highly the course\n", + "[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n", + "and the slides of [CS231](http://cs231n.github.io/convolutional-networks/).\n", + "\n", + "Another good read is the article here . \n", + "\n", + "## Regular NNs don’t scale well to full images\n", + "\n", + "As an example, consider\n", + "an image of size $32\\times 32\\times 3$ (32 wide, 32 high, 3 color channels), so a\n", + "single fully-connected neuron in a first hidden layer of a regular\n", + "Neural Network would have $32\\times 32\\times 3 = 3072$ weights. This amount still\n", + "seems manageable, but clearly this fully-connected structure does not\n", + "scale to larger images. For example, an image of more respectable\n", + "size, say $200\\times 200\\times 3$, would lead to neurons that have \n", + "$200\\times 200\\times 3 = 120,000$ weights. \n", + "\n", + "We could have\n", + "several such neurons, and the parameters would add up quickly! Clearly,\n", + "this full connectivity is wasteful and the huge number of parameters\n", + "would quickly lead to possible overfitting.\n", + "\n", + "\n", + "\n", + "\n", + "

A regular 3-layer Neural Network.

\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## 3D volumes of neurons\n", + "\n", + "Convolutional Neural Networks take advantage of the fact that the\n", + "input consists of images and they constrain the architecture in a more\n", + "sensible way. \n", + "\n", + "In particular, unlike a regular Neural Network, the\n", + "layers of a CNN have neurons arranged in 3 dimensions: width,\n", + "height, depth. (Note that the word depth here refers to the third\n", + "dimension of an activation volume, not to the depth of a full Neural\n", + "Network, which can refer to the total number of layers in a network.)\n", + "\n", + "To understand it better, the above example of an image \n", + "with an input volume of\n", + "activations has dimensions $32\\times 32\\times 3$ (width, height,\n", + "depth respectively). \n", + "\n", + "The neurons in a layer will\n", + "only be connected to a small region of the layer before it, instead of\n", + "all of the neurons in a fully-connected manner. Moreover, the final\n", + "output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n", + "because by the\n", + "end of the CNN architecture we will reduce the full image into a\n", + "single vector of class scores, arranged along the depth\n", + "dimension. \n", + "\n", + "\n", + "\n", + "\n", + "

A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Layers used to build CNNs\n", + "\n", + "\n", + "A simple CNN is a sequence of layers, and every layer of a CNN\n", + "transforms one volume of activations to another through a\n", + "differentiable function. We use three main types of layers to build\n", + "CNN architectures: Convolutional Layer, Pooling Layer, and\n", + "Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n", + "will stack these layers to form a full CNN architecture.\n", + "\n", + "A simple CNN for image classification could have the architecture:\n", + "\n", + "* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n", + "\n", + "* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n", + "\n", + "* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n", + "\n", + "* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n", + "\n", + "* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.\n", + "\n", + "## Transforming images\n", + "\n", + "CNNs transform the original image layer by layer from the original\n", + "pixel values to the final class scores. \n", + "\n", + "Observe that some layers contain\n", + "parameters and other don’t. In particular, the CNN layers perform\n", + "transformations that are a function of not only the activations in the\n", + "input volume, but also of the parameters (the weights and biases of\n", + "the neurons). On the other hand, the RELU/POOL layers will implement a\n", + "fixed function. The parameters in the CONV/FC layers will be trained\n", + "with gradient descent so that the class scores that the CNN computes\n", + "are consistent with the labels in the training set for each image.\n", + "\n", + "\n", + "## CNNs in brief\n", + "\n", + "In summary:\n", + "\n", + "* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n", + "\n", + "* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n", + "\n", + "* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n", + "\n", + "* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n", + "\n", + "* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n", + "\n", + "For more material on convolutional networks, we strongly recommend\n", + "the course\n", + "[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n", + "and the slides of [CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n", + "\n", + "\n", + "## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n", + "\n", + "\n", + "As discussed above, CNNs are neural networks built from the assumption that the inputs\n", + "to the network are 2D images. This is important because the number of features or pixels in images\n", + "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n", + "\n", + "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n", + "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n", + "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n", + "matrices, typically 1 for each color dimension (Red, Green, Blue). \n", + "\n", + "\n", + "## Setting it up\n", + "\n", + "It means that to represent the entire\n", + "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The MNIST dataset again\n", + "\n", + "The MNIST dataset consists of grayscale images with a pixel size of\n", + "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n", + "neuron in the first hidden layer.\n", + "\n", + "If we were to analyze images of size $128\\times 128$ we would require\n", + "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n", + "dealing with color images, as most images are, we have an image matrix\n", + "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n", + "meaning 3 times the number of weights $= 49152$ are required for every\n", + "single neuron in the first hidden layer.\n", + "\n", + "\n", + "## Strong correlations\n", + "Images typically have strong local correlations, meaning that a small\n", + "part of the image varies little from its neighboring regions. If for\n", + "example we have an image of a blue car, we can roughly assume that a\n", + "small blue part of the image is surrounded by other blue regions.\n", + "\n", + "Therefore, instead of connecting every single pixel to a neuron in the\n", + "first hidden layer, as we have previously done with deep neural\n", + "networks, we can instead connect each neuron to a small part of the\n", + "image (in all 3 RGB depth dimensions). The size of each small area is\n", + "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n", + "\n", + "\n", + "\n", + "## Layers of a CNN\n", + "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n", + "The input image is typically a square matrix of depth 3. \n", + "\n", + "A **convolution** is performed on the image which outputs\n", + "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n", + "\n", + "\n", + "Each filter slides along the input image, taking the dot product\n", + "between each small part of the image and the filter, in all depth\n", + "dimensions. This is then passed through a non-linear function,\n", + "typically the **Rectified Linear (ReLu)** function, which serves as the\n", + "activation of the neurons in the first convolutional layer. This is\n", + "further passed through a **pooling layer**, which reduces the size of the\n", + "convolutional layer, e.g. by taking the maximum or average across some\n", + "small regions, and this serves as input to the next convolutional\n", + "layer.\n", + "\n", + "\n", + "## Systematic reduction\n", + "\n", + "By systematically reducing the size of the input volume, through\n", + "convolution and pooling, the network should create representations of\n", + "small parts of the input, and then from them assemble representations\n", + "of larger areas. The final pooling layer is flattened to serve as\n", + "input to a hidden layer, such that each neuron in the final pooling\n", + "layer is connected to every single neuron in the hidden layer. This\n", + "then serves as input to the output layer, e.g. a softmax output for\n", + "classification.\n", + "\n", + "\n", + "## Prerequisites: Collect and pre-process data" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "# RGB images have a depth of 3\n", + "# our images are grayscale so they should have a depth of 1\n", + "inputs = inputs[:,:,:,np.newaxis]\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "n_inputs = len(inputs)\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Importing Keras and Tensorflow" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from keras.utils import to_categorical\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "# one-liner from scikit-learn library\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using TensorFlow backend\n", + "\n", + "We need to define model and architecture and choose cost function and optmizer." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\n", + "import tensorflow as tf\n", + "\n", + "class ConvolutionalNeuralNetworkTensorflow:\n", + " def __init__(\n", + " self,\n", + " X_train,\n", + " Y_train,\n", + " X_test,\n", + " Y_test,\n", + " n_filters=10,\n", + " n_neurons_connected=50,\n", + " n_categories=10,\n", + " receptive_field=3,\n", + " stride=1,\n", + " padding=1,\n", + " epochs=10,\n", + " batch_size=100,\n", + " eta=0.1,\n", + " lmbd=0.0):\n", + " \n", + " self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n", + " \n", + " self.X_train = X_train\n", + " self.Y_train = Y_train\n", + " self.X_test = X_test\n", + " self.Y_test = Y_test\n", + " \n", + " self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape\n", + " \n", + " self.n_filters = n_filters\n", + " self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)\n", + " self.n_neurons_connected = n_neurons_connected\n", + " self.n_categories = n_categories\n", + " \n", + " self.receptive_field = receptive_field\n", + " self.stride = stride\n", + " self.strides = [stride, stride, stride, stride]\n", + " self.padding = padding\n", + " \n", + " self.epochs = epochs\n", + " self.batch_size = batch_size\n", + " self.iterations = self.n_inputs // self.batch_size\n", + " self.eta = eta\n", + " self.lmbd = lmbd\n", + " \n", + " self.create_placeholders()\n", + " self.create_CNN()\n", + " self.create_loss()\n", + " self.create_optimiser()\n", + " self.create_accuracy()\n", + " \n", + " def create_placeholders(self):\n", + " with tf.name_scope('data'):\n", + " self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')\n", + " self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')\n", + " \n", + " def create_CNN(self):\n", + " with tf.name_scope('CNN'):\n", + " \n", + " # Convolutional layer\n", + " self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)\n", + " b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)\n", + " z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv\n", + " a_conv = tf.nn.relu(z_conv)\n", + " \n", + " # 2x2 max pooling\n", + " a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')\n", + " \n", + " # Fully connected layer\n", + " a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])\n", + " self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)\n", + " b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)\n", + " a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)\n", + " \n", + " # Output layer\n", + " self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)\n", + " b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)\n", + " self.z_out = tf.matmul(a_fc, self.W_out) + b_out\n", + " \n", + " def create_loss(self):\n", + " with tf.name_scope('loss'):\n", + " softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))\n", + " \n", + " regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)\n", + " regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)\n", + " regularizer_loss_out = tf.nn.l2_loss(self.W_out)\n", + " regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)\n", + " \n", + " self.loss = softmax_loss + regularizer_loss\n", + "\n", + " def create_accuracy(self):\n", + " with tf.name_scope('accuracy'):\n", + " probabilities = tf.nn.softmax(self.z_out)\n", + " predictions = tf.argmax(probabilities, 1)\n", + " labels = tf.argmax(self.Y, 1)\n", + " \n", + " correct_predictions = tf.equal(predictions, labels)\n", + " correct_predictions = tf.cast(correct_predictions, tf.float32)\n", + " self.accuracy = tf.reduce_mean(correct_predictions)\n", + " \n", + " def create_optimiser(self):\n", + " with tf.name_scope('optimizer'):\n", + " self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)\n", + " \n", + " def weight_variable(self, shape, name='', dtype=tf.float32):\n", + " initial = tf.truncated_normal(shape, stddev=0.1)\n", + " return tf.Variable(initial, name=name, dtype=dtype)\n", + " \n", + " def bias_variable(self, shape, name='', dtype=tf.float32):\n", + " initial = tf.constant(0.1, shape=shape)\n", + " return tf.Variable(initial, name=name, dtype=dtype)\n", + "\n", + " def fit(self):\n", + " data_indices = np.arange(self.n_inputs)\n", + "\n", + " with tf.Session() as sess:\n", + " sess.run(tf.global_variables_initializer())\n", + " for i in range(self.epochs):\n", + " for j in range(self.iterations):\n", + " chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)\n", + " batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]\n", + " \n", + " sess.run([CNN.loss, CNN.optimizer],\n", + " feed_dict={CNN.X: batch_X,\n", + " CNN.Y: batch_Y})\n", + " accuracy = sess.run(CNN.accuracy,\n", + " feed_dict={CNN.X: batch_X,\n", + " CNN.Y: batch_Y})\n", + " step = sess.run(CNN.global_step)\n", + " \n", + " self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],\n", + " feed_dict={CNN.X: self.X_train,\n", + " CNN.Y: self.Y_train})\n", + " \n", + " self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],\n", + " feed_dict={CNN.X: self.X_test,\n", + " CNN.Y: self.Y_test})" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Train the model\n", + "\n", + "We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "epochs = 100\n", + "batch_size = 100\n", + "n_filters = 10\n", + "n_neurons_connected = 50\n", + "n_categories = 10\n", + "\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)\n", + "CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,\n", + " n_filters=n_filters, n_neurons_connected=n_neurons_connected,\n", + " n_categories=n_categories, epochs=epochs, batch_size=batch_size,\n", + " eta=eta, lmbd=lmbd)\n", + " CNN.fit()\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % CNN.test_accuracy)\n", + " print()\n", + " \n", + " CNN_tf[i][j] = CNN" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Visualizing the results" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " CNN = CNN_tf[i][j]\n", + "\n", + " train_accuracy[i][j] = CNN.train_accuracy\n", + " test_accuracy[i][j] = CNN.test_accuracy\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "## Running with Keras" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from keras.models import Sequential\n", + "from keras.layers.convolutional import Conv2D\n", + "from keras.layers.convolutional import MaxPooling2D\n", + "from keras.layers import Flatten\n", + "from keras.layers import Dense\n", + "from keras.regularizers import l2\n", + "from keras.optimizers import SGD\n", + "\n", + "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n", + " n_filters, n_neurons_connected, n_categories,\n", + " eta, lmbd):\n", + " model = Sequential()\n", + " model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n", + " activation='relu', kernel_regularizer=l2(lmbd)))\n", + " model.add(MaxPooling2D(pool_size=(2, 2)))\n", + " model.add(Flatten())\n", + " model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))\n", + " model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))\n", + " \n", + " sgd = SGD(lr=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model\n", + "\n", + "epochs = 100\n", + "batch_size = 100\n", + "input_shape = X_train.shape[1:4]\n", + "receptive_field = 3\n", + "n_filters = 10\n", + "n_neurons_connected = 50\n", + "n_categories = 10\n", + "\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Final part" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n", + " n_filters, n_neurons_connected, n_categories,\n", + " eta, lmbd)\n", + " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = CNN.evaluate(X_test, Y_test)\n", + " \n", + " CNN_keras[i][j] = CNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Final visualization" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " # visual representation of grid search\n", + " # uses seaborn heatmap, could probably do this in matplotlib\n", + " import seaborn as sns\n", + " \n", + " sns.set()\n", + " \n", + " train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + " test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + " \n", + " for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " CNN = CNN_keras[i][j]\n", + " \n", + " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n", + " \n", + " \n", + " fig, ax = plt.subplots(figsize = (10, 10))\n", + " sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + " ax.set_title(\"Training Accuracy\")\n", + " ax.set_ylabel(\"$\\eta$\")\n", + " ax.set_xlabel(\"$\\lambda$\")\n", + " plt.show()\n", + " \n", + " fig, ax = plt.subplots(figsize = (10, 10))\n", + " sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + " ax.set_title(\"Test Accuracy\")\n", + " ax.set_ylabel(\"$\\eta$\")\n", + " ax.set_xlabel(\"$\\lambda$\")\n", + " plt.show()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Fun links\n", + "\n", + "1. [Self-Driving cars using a convolutional neural network](https://arxiv.org/abs/1604.07316)\n", + "\n", + "2. [Abstract art using convolutional neural networks](https://deepdreamgenerator.com/)" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/pub/week43/html/._week43-bs000.html b/doc/pub/week43/html/._week43-bs000.html new file mode 100644 index 000000000..f460349c9 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs000.html @@ -0,0 +1,251 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +

 

 

 

+ + + + + + +
+

Week 43: Dimensionality Reduction

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs001.html b/doc/pub/week43/html/._week43-bs001.html new file mode 100644 index 000000000..368d53b2e --- /dev/null +++ b/doc/pub/week43/html/._week43-bs001.html @@ -0,0 +1,306 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Why should we think of reducing the dimensionality

+ +

+In addition to the plot of the features, we study now also the covariance (and the correlation matrix). +We use also Pandas to compute the correlation matrix. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+import pandas as pd
+# Making a data frame
+cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+fig, axes = plt.subplots(15,2,figsize=(10,20))
+malignant = cancer.data[cancer.target == 0]
+benign = cancer.data[cancer.target == 1]
+ax = axes.ravel()
+
+for i in range(30):
+    _, bins = np.histogram(cancer.data[:,i], bins =50)
+    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
+    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
+    ax[i].set_title(cancer.feature_names[i])
+    ax[i].set_yticks(())
+ax[0].set_xlabel("Feature magnitude")
+ax[0].set_ylabel("Frequency")
+ax[0].legend(["Malignant", "Benign"], loc ="best")
+fig.tight_layout()
+plt.show()
+
+import seaborn as sns
+correlation_matrix = cancerpd.corr().round(1)
+# use the heatmap function from seaborn to plot the correlation matrix
+# annot = True to print the values inside the square
+sns.heatmap(data=correlation_matrix, annot=True)
+plt.show()
+
+#print eigvalues of correlation matrix
+EigValues, EigVectors = np.linalg.eig(correlation_matrix)
+print(EigValues)
+
+

+In the above example we note two things. In the first plot we display +the overlap of benign and malignant tumors as functions of the various +features in the Wisconsing breast cancer data set. We see that for +some of the features we can distinguish clearly the benign and +malignant cases while for other features we cannot. This can point to +us which features may be of greater interest when we wish to classify +a benign or not benign tumour. + +

+In the second figure we have computed the so-called correlation +matrix, which in our case with thirty features becomes a \( 30\times 30 \) +matrix. + +

+We constructed this matrix using pandas via the statements +

+ + +

cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+

+and then +

+ + +

correlation_matrix = cancerpd.corr().round(1)
+
+

+Diagonalizing this matrix we can in turn say something about which +features are of relevance and which are not. But before we proceed we +need to define covariance and correlation matrices. This leads us to +the classical Principal Component Analysis (PCA) theorem with +applications. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs002.html b/doc/pub/week43/html/._week43-bs002.html new file mode 100644 index 000000000..a7ede2fe0 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs002.html @@ -0,0 +1,245 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Basic ideas of the Principal Component Analysis (PCA)

+ +

+The principal component analysis deals with the problem of fitting a +low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than +the totaldimension \( D \) of the problem at hand (our data +set). Mathematically it can be formulated as a statistical problem or +a geometric problem. In our discussion of the theorem for the +classical PCA, we will stay with a statistical approach. This is also +what set the scene historically which for the PCA. + +

+We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) + +

    +
  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • +
  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • +
  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • +
+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs003.html b/doc/pub/week43/html/._week43-bs003.html new file mode 100644 index 000000000..e145fedd0 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs003.html @@ -0,0 +1,285 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Introducing the Covariance and Correlation functions

+ +

+Before we discuss the PCA theorem, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities + +

+Suppose we have defined two vectors +\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ + \end{bmatrix}, +$$ + +where for example +$$ +\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +$$ + +With this definition and recalling that the variance is defined as +$$ +\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +$$ + +we can rewrite the covariance matrix as +$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ + \end{bmatrix}. +$$ + +

+The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function + +$$ +\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. +$$ + +

+The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +\in [-1,1] \). This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) +and \( \boldsymbol{y} \) as + +$$ +\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ + \end{bmatrix}, +$$ + +

+In the above example this is the function we constructed using pandas. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs004.html b/doc/pub/week43/html/._week43-bs004.html new file mode 100644 index 000000000..9599a14a7 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs004.html @@ -0,0 +1,286 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Correlation Function and Design/Feature Matrix

+ +

+In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +we defined the design/feature matrix \( \boldsymbol{X} \) as + +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ + +with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +entries \( n \) being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as +$$ +\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, +$$ + +with a given vector +$$ +\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. +$$ + +

+With these definitions, we can now rewrite our \( 2\times 2 \) +correaltion/covariance matrix in terms of a moe general design/feature +matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) +covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) + +$$ +\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} +\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ +\end{bmatrix}, +$$ + +and the correlation matrix +$$ +\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs005.html b/doc/pub/week43/html/._week43-bs005.html new file mode 100644 index 000000000..c439a1408 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs005.html @@ -0,0 +1,269 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Covariance Matrix Examples

+ +

+The Numpy function np.cov calculates the covariance elements using +the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have +the exact mean values. The following simple function uses the +np.vstack function which takes each vector of dimension \( 1\times n \) +and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) + +$$ +\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\ + x_1 & y_1 \\ + x_2 & y_2\\ + \dots & \dots \\ + x_{n-2} & y_{n-2}\\ + x_{n-1} & y_{n-1} & + \end{bmatrix}, +$$ + +

+which in turn is converted into into the \( 2\times 2 \) covariance matrix +\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate +the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy +function np.mean(x). We can also extract the eigenvalues of the +covariance matrix through the np.linalg.eig() function. + +

+ + +

# Importing various packages
+import numpy as np
+n = 100
+x = np.random.normal(size=n)
+print(np.mean(x))
+y = 4+3*x+np.random.normal(size=n)
+print(np.mean(y))
+W = np.vstack((x, y))
+C = np.cov(W)
+print(C)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs006.html b/doc/pub/week43/html/._week43-bs006.html new file mode 100644 index 000000000..c21175195 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs006.html @@ -0,0 +1,272 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Correlation Matrix

+ +

+The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). + +

+ + +

import numpy as np
+n = 100
+# define two vectors                                                                                           
+x = np.random.random(size=n)
+y = 4+3*x+np.random.normal(size=n)
+#scaling the x and y vectors                                                                                   
+x = x - np.mean(x)
+y = y - np.mean(y)
+variance_x = np.sum(x@x)/n
+variance_y = np.sum(y@y)/n
+print(variance_x)
+print(variance_y)
+cov_xy = np.sum(x@y)/n
+cov_xx = np.sum(x@x)/n
+cov_yy = np.sum(y@y)/n
+C = np.zeros((2,2))
+C[0,0]= cov_xx/variance_x
+C[1,1]= cov_yy/variance_y
+C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
+C[1,0]= C[0,1]
+print(C)
+
+

+We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix. + +

+The above procedure with numpy can be made more compact if we use pandas. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs007.html b/doc/pub/week43/html/._week43-bs007.html new file mode 100644 index 000000000..743d1e64f --- /dev/null +++ b/doc/pub/week43/html/._week43-bs007.html @@ -0,0 +1,255 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Correlation Matrix with Pandas

+ +

+We whow here how we can set up the correlation matrix using pandas, as done in this simple code +

+ + +

import numpy as np
+import pandas as pd
+n = 10
+x = np.random.normal(size=n)
+x = x - np.mean(x)
+y = 4+3*x+np.random.normal(size=n)
+y = y - np.mean(y)
+X = (np.vstack((x, y))).T
+print(X)
+Xpd = pd.DataFrame(X)
+print(Xpd)
+correlation_matrix = Xpd.corr()
+print(correlation_matrix)
+
+

+We expand this model to the Franke function discussed above. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs008.html b/doc/pub/week43/html/._week43-bs008.html new file mode 100644 index 000000000..64b3195cf --- /dev/null +++ b/doc/pub/week43/html/._week43-bs008.html @@ -0,0 +1,292 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Correlation Matrix with Pandas and the Franke function

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+
+
+def FrankeFunction(x,y):
+	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
+	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
+	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
+	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
+	return term1 + term2 + term3 + term4
+
+
+def create_X(x, y, n ):
+	if len(x.shape) > 1:
+		x = np.ravel(x)
+		y = np.ravel(y)
+
+	N = len(x)
+	l = int((n+1)*(n+2)/2)		# Number of elements in beta
+	X = np.ones((N,l))
+
+	for i in range(1,n+1):
+		q = int((i)*(i+1)/2)
+		for k in range(i+1):
+			X[:,q+k] = (x**(i-k))*(y**k)
+
+	return X
+
+
+# Making meshgrid of datapoints and compute Franke's function
+n = 4
+N = 100
+x = np.sort(np.random.uniform(0, 1, N))
+y = np.sort(np.random.uniform(0, 1, N))
+z = FrankeFunction(x, y)
+X = create_X(x, y, n=n)    
+
+Xpd = pd.DataFrame(X)
+# subtract the mean values and set up the covariance matrix
+Xpd = Xpd - Xpd.mean()
+covariance_matrix = Xpd.cov()
+print(covariance_matrix)
+
+

+We note here that the covariance is zero for the first rows and +columns since all matrix elements in the design matrix were set to one +(we are fitting the function in terms of a polynomial of degree \( n \)). + +

+This means that the variance for these elements will be zero and will +cause problems when we set up the correlation matrix. We can simply +drop these elements and construct a correlation +matrix without these elements. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs009.html b/doc/pub/week43/html/._week43-bs009.html new file mode 100644 index 000000000..c179e48d5 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs009.html @@ -0,0 +1,273 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Rewriting the Covariance and/or Correlation Matrix

+ +

+We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ + +

+To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ +\end{bmatrix}. +$$ + +

+If we then compute the expectation value +$$ +\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\begin{bmatrix} +x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ +x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ +\end{bmatrix}, +$$ + +which is just +$$ +\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ + \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ + \end{bmatrix}, +$$ + +where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). + +

+It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs010.html b/doc/pub/week43/html/._week43-bs010.html new file mode 100644 index 000000000..9fd93c2be --- /dev/null +++ b/doc/pub/week43/html/._week43-bs010.html @@ -0,0 +1,282 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Towards the PCA theorem

+ +

+We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ + +Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). +These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \). + +

+Assume also that there is a transformation \( \boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). + +

+That is we have +$$ +\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}\boldsymbol{X}\boldsymbol{X}^T\boldsymbol{S}^T]=\boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ + +since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S}^T \) from the left we have +$$ +\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ + +and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that + +$$ +\boldsymbol{S}^T_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T_i. +$$ + +

+In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is +\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). + +

+The eigenvalues tell us then how much we need to stretch the +corresponding eigenvectors. Dimensions with large eigenvalues have +thus large variations (large variance) and define therefore useful +dimensions. The data points are more spread out in the direction of +these eigenvectors. Smaller eigenvalues mean on the other hand that +the corresponding eigenvectors are shrunk accordingly and the data +points are tightly bunched together and there is not much variation in +these specific directions. Hopefully then we could leave it out +dimensions where the eigenvalues are very small. If \( p \) is very large, +we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) +features/predictors. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs011.html b/doc/pub/week43/html/._week43-bs011.html new file mode 100644 index 000000000..99f636c41 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs011.html @@ -0,0 +1,262 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The Algorithm before theorem

+ +

+Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. + +

    +
  • Set up the datapoints for the design/feature matrix \( \boldsymbol{X} \) with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) referring to the column numbers and the entries \( n \) being the row elements.
  • +
+ +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ + + +
    +
  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • +
  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}\overline{\boldsymbol{X}}^T] \).
  • +
  • Find the eigenpairs of \( \boldsymbol{C} \) with eigenvalues \( [\lambda_0,\lambda_1,\dots,\lambda_{p-1}] \) and eigenvectors \( [\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \).
  • +
  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • +
  • Keep only those \( l \) eigenvalues larger than a selected threshold value, discarding thus \( p-l \) features since we expect small variations in the data here.
  • +
+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs012.html b/doc/pub/week43/html/._week43-bs012.html new file mode 100644 index 000000000..89443a2f8 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs012.html @@ -0,0 +1,407 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Writing our own PCA code

+ +

+We will use a simple example first with two-dimensional data +drawn from a multivariate normal distribution with the following mean and covariance matrix: +$$ +\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ +2 & 2 +\end{bmatrix} +$$ + +Note that the mean refers to each column of data. +We will generate \( n = 1000 \) points \( X = \{ x_1, \ldots, x_N \} \) from +this distribution, and store them in the \( 1000 \times 2 \) matrix \( \boldsymbol{X} \). + +

+The following Python code aids in setting up the data and writing out the design matrix. +Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). +

+ + +

import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+n = 10000
+mean = (-1, 2)
+cov = [[4, 2], [2, 2]]
+X = np.random.multivariate_normal(mean, cov, n)
+
+

+Now we are going to implement the PCA algorithm. We will break it down into various substeps. + +

Compute the sample mean and center the data

+ +

+The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is +$$ +\mu_n = \frac{1}{n} \sum_{i=1}^n x_i +$$ + +and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form +$$ +\bar{x}_i = x_i - \mu_n. +$$ + +When you are done with these steps, print out \( \mu_n \) to verify it is +close to \( \mu \) and plot your mean centered data to verify it is +centered at the origin! Compare your code with the functionality from Scikit-Learn discussed above. +The following code elements perform these operations using pandas or using our own functionality for doing so. The latter, using numpy is rather simple through the mean() function. +

+ + +

df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+
+

+Alternatively, we could use the functions we discussed +earlier for scaling the data set. That is, we could have used the +StandardScaler function in Scikit-Learn, a function which ensures +that for each feature/predictor we study the mean value is zero and +the variance is one (every column in the design/feature matrix). You +would then not get the same results, since we divide by the +variance. The diagonal covariance matrix elements will then be one, +while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our +specific case. + +

Compute the sample covariance

+ +

+Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation +$$ +\begin{equation*} +\Sigma_n = \frac{1}{n-1} \sum_{i=1}^n \bar{x}_i^T \bar{x}_i = \frac{1}{n-1} \sum_{i=1}^n (x_i - \mu_n)^T (x_i - \mu_n) +\end{equation*} +$$ + +where the data points \( x_i \in \mathbb{R}^p \) (here in this example \( p = 2 \)) are column vectors and \( x^T \) is the transpose of \( x \). +We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows +

+ + +

print(df.cov())
+print(np.cov(X_centered.T))
+
+

+Note that the way we define the covariance matrix here has a factor \( n-1 \) instead of \( n \). This is included in the cov() function by numpy and pandas. +Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. +

+ + +

# extract the relevant columns from the centered design matrix of dim n x 2
+x = X_centered[:,0]
+y = X_centered[:,1]
+Cov = np.zeros((2,2))
+Cov[0,1] = np.sum(x.T@y)/(n-1.0)
+Cov[0,0] = np.sum(x.T@x)/(n-1.0)
+Cov[1,1] = np.sum(y.T@y)/(n-1.0)
+Cov[1,0]= Cov[0,1]
+print("Centered covariance using own code")
+print(Cov)
+plt.plot(x, y, 'x')
+plt.axis('equal')
+plt.show()
+
+

+Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. +The plot shows how the data are clustered around a line with slope close to one. Is this expected? + +

Diagonalize the sample covariance matrix to obtain the principal components

+ +

+Now we are ready to solve for the principal components! To do so we +diagonalize the sample covariance matrix \( \Sigma \). We can use the +function np.linalg.eig to do so. It will return the eigenvalues and +eigenvectors of \( \Sigma \). Once we have these we can perform the +following tasks: + +

    +
  • We compute the percentage of the total variance captured by the first principal component
  • +
  • We plot the mean centered data and lines along the first and second principal components
  • +
  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • +
  • Finally, we approximate the data as
  • +
+ +$$ +\begin{equation*} +x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 +\end{equation*} +$$ + +where \( v_0 \) is the first principal component. + +

+Collecting all these steps we can write our own PCA function and +compare this with the functionality included in Scikit-Learn. + +

+The code here outlines some of the elements we could include in the +analysis. Feel free to extend upon this in order to address the above +questions. + +

+ + +

# diagonalize and obtain eigenvalues, not necessarily sorted
+EigValues, EigVectors = np.linalg.eig(Cov)
+# sort eigenvectors and eigenvalues
+#permute = EigValues.argsort()
+#EigValues = EigValues[permute]
+#EigVectors = EigVectors[:,permute]
+print("Eigenvalues of Covariance matrix")
+for i in range(2):
+    print(EigValues[i])
+FirstEigvector = EigVectors[:,0]
+SecondEigvector = EigVectors[:,1]
+print("First eigenvector")
+print(FirstEigvector)
+print("Second eigenvector")
+print(SecondEigvector)
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2Dsl = pca.fit_transform(X)
+print("Eigenvector of largest eigenvalue")
+print(pca.components_.T[:, 0])
+
+

+This code does not contain all the above elements, but it shows how we can use Scikit-Learn to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs013.html b/doc/pub/week43/html/._week43-bs013.html new file mode 100644 index 000000000..63d42f47e --- /dev/null +++ b/doc/pub/week43/html/._week43-bs013.html @@ -0,0 +1,264 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Classical PCA Theorem

+ +

+We assume now that we have a design matrix \( \boldsymbol{X} \) which has been +centered as discussed above. For the sake of simplicity we skip the +overline symbol. The matrix is defined in terms of the various column +vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension +\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). + +

+We assume also that we have an orthogonal transformation \( \boldsymbol{W}\in {\mathbb{R}}^{p\times p} \). We define the reconstruction error (which is similar to the mean squared error we have seen before) as +$$ +J(\boldsymbol{W},\boldsymbol{Z}) = \frac{1}{n}\sum_i (\boldsymbol{x}_i - \overline{\boldsymbol{x}}_i)^2, +$$ + +with \( \overline{\boldsymbol{x}}_i = \boldsymbol{W}\boldsymbol{z}_i \), where \( \boldsymbol{z}_i \) is a row vector with dimension \( {\mathbb{R}}^{n} \) of the matrix +\( \boldsymbol{Z}\in{\mathbb{R}}^{p\times n} \). When doing PCA we want to reduce this dimensionality. + +

+The PCA theorem states that minimizing the above reconstruction error +corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which +diagonalizes the empirical covariance(correlation) matrix. The optimal +low-dimensional encoding of the data is then given by a set of vectors +\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the +orthogonal projection of the data onto the columns spanned by the +eigenvectors of the covariance(correlations matrix). + +

+The proof which follows will be updated by mid January 2020. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs014.html b/doc/pub/week43/html/._week43-bs014.html new file mode 100644 index 000000000..10ff89247 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs014.html @@ -0,0 +1,254 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Proof of the PCA Theorem

+ +

+To show the PCA theorem let us start with the assumption that there is one vector \( \boldsymbol{w}_0 \) which corresponds to a solution which minimized the reconstruction error \( J \). This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of \( \boldsymbol{w}_0 \) and \( \boldsymbol{z}_0 \) as +$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)= \frac{1}{n}\sum_i (\boldsymbol{x}_i - z_{i0}\boldsymbol{w}_0)^2=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2\boldsymbol{w}_0^T\boldsymbol{w}_0), +$$ + +which we can rewrite due to the orthogonality of \( \boldsymbol{w}_i \) as +$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2). +$$ + +Minimizing \( J \) with respect to the unknown parameters \( z_{0i} \) we obtain that +$$ +z_{i0}=\boldsymbol{w}_0^T\boldsymbol{x}_i, +$$ + +where the vectors on the rhs are known. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs015.html b/doc/pub/week43/html/._week43-bs015.html new file mode 100644 index 000000000..97283a0e9 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs015.html @@ -0,0 +1,272 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

PCA Proof continued

+ +

+We have now found the unknown parameters \( z_{i0} \). These correspond to the projected coordinates and we can write +$$ +J(\boldsymbol{w}_0)= \frac{1}{p}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - z_{i0}^2)=\mathrm{const}-\frac{1}{n}\sum_i z_{i0}^2. +$$ + +

+We can show that the variance of the projected coordinates defined by \( \boldsymbol{w}_0^T\boldsymbol{x}_i \) are given by +$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2, +$$ + +since the expectation value of +$$ +\mathbb{E}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \mathbb{E}[z_{i0}]= \boldsymbol{w}_0^T\mathbb{E}[\boldsymbol{x}_i]=0, +$$ + +where we have used the fact that our data are centered. + +

+Recalling our definition of the covariance as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T], +$$ + +we have thus that +$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2=\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0. +$$ + +

+We are almost there, we have obtained a relation between minimizing +the reconstruction error and the variance and the covariance +matrix. Minimizing the error is equivalent to maximizing the variance +of the projected data. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs016.html b/doc/pub/week43/html/._week43-bs016.html new file mode 100644 index 000000000..473d9db7a --- /dev/null +++ b/doc/pub/week43/html/._week43-bs016.html @@ -0,0 +1,285 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The final step

+ +

+We could trivially maximize the variance of the projection (and +thereby minimize the error in the reconstruction function) by letting +the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we +want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by +\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a +Lagrange multiplier we can then in turn maximize + +$$ +J(\boldsymbol{w}_0)= \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0+\lambda_0(1-\boldsymbol{w}_0^T\boldsymbol{w}_0). +$$ + +Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain + +$$ +\frac{\partial J(\boldsymbol{w}_0)}{\partial \boldsymbol{w}_0}= 2\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0-2\lambda_0\boldsymbol{w}_0=0, +$$ + +meaning that +$$ +\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. +$$ + +The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix! If we left multiply with \( \boldsymbol{w}_0^T \) we have the variance of the projected data is +$$ +\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. +$$ + +

+If we want to maximize the variance (minimize the construction error) +we simply pick the eigenvector of the covariance matrix with the +largest eigenvalue. This establishes the link between the minimization +of the reconstruction function \( J \) in terms of an orthogonal matrix +and the maximization of the variance and thereby the covariance of our +observations encoded in the design/feature matrix \( \boldsymbol{X} \). + +

+The proof +for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be +established by applying the above arguments and using the fact that +our basis of eigenvectors is orthogonal, see Murphy chapter +12.2. The +discussion in chapter 12.2 of Murphy's text has also a nice link with +the Singular Value Decomposition theorem. For categorical data, see +chapter 12.4 and discussion therein. + +

+Additional part of the proof for the other eigenvectors will be added by mid January 2020. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs017.html b/doc/pub/week43/html/._week43-bs017.html new file mode 100644 index 000000000..8d4a62a82 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs017.html @@ -0,0 +1,237 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Geometric Interpretation and link with Singular Value Decomposition

+ +

+This material will be added by mid January 2020. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs018.html b/doc/pub/week43/html/._week43-bs018.html new file mode 100644 index 000000000..ea46f826c --- /dev/null +++ b/doc/pub/week43/html/._week43-bs018.html @@ -0,0 +1,283 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Principal Component Analysis

+ +

+Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. +First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. + +

+The following Python code uses NumPy’s svd() function to obtain all the principal components of the +training set, then extracts the first two principal components. First we center the data using either pandas or our own code +

+ + +

import numpy as np
+import pandas as pd
+from IPython.display import display
+np.random.seed(100)
+# setting up a 10 x 5 vanilla matrix 
+rows = 10
+cols = 5
+X = np.random.randn(rows,cols)
+df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+display(df)
+
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+# Then check the difference between pandas and our own set up
+print(X_centered-df)
+#Now we do an SVD
+U, s, V = np.linalg.svd(X_centered)
+c1 = V.T[:, 0]
+c2 = V.T[:, 1]
+W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+print(X2D)
+
+

+PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering +the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t +forget to center the data first. + +

+Once you have identified all the principal components, you can reduce the dimensionality of the dataset +down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. +Selecting this hyperplane ensures that the projection will preserve as much variance as possible. +

+ + +

W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs019.html b/doc/pub/week43/html/._week43-bs019.html new file mode 100644 index 000000000..256856d28 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs019.html @@ -0,0 +1,259 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

PCA and scikit-learn

+ +

+Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The +following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note +that it automatically takes care of centering the data): +

+ + +

#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D = pca.fit_transform(X)
+print(X2D)
+
+

+After fitting the PCA transformer to the dataset, you can access the principal components using the +components variable (note that it contains the PCs as horizontal vectors, so, for example, the first +principal component is equal to +

+ + +

pca.components_.T[:, 0].
+
+

+Another very useful piece of information is the explained variance ratio of each principal component, +available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s +variance that lies along the axis of each principal component. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs020.html b/doc/pub/week43/html/._week43-bs020.html new file mode 100644 index 000000000..07f940905 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs020.html @@ -0,0 +1,267 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Back to the Cancer Data

+We can now repeat the above but applied to real data, in this case our breast cancer data. +Here we compute performance scores on the training data using logistic regression. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
+# We scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Then perform again a log reg fit
+logreg.fit(X_train_scaled, y_train)
+print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D_train = pca.fit_transform(X_train_scaled)
+# and finally compute the log reg fit and the score on the training data	
+logreg.fit(X2D_train,y_train)
+print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
+
+

+We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs021.html b/doc/pub/week43/html/._week43-bs021.html new file mode 100644 index 000000000..7171aa518 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs021.html @@ -0,0 +1,255 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

More on the PCA

+ +

+Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to +choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). +Unless, of course, you are reducing dimensionality for data visualization — in that case you will +generally want to reduce the dimensionality down to 2 or 3. +The following code computes PCA without reducing dimensionality, then computes the minimum number +of dimensions required to preserve 95% of the training set’s variance: +

+ + +

pca = PCA()
+pca.fit(X)
+cumsum = np.cumsum(pca.explained_variance_ratio_)
+d = np.argmax(cumsum >= 0.95) + 1
+
+

+You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead +of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be +a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: +

+ + +

pca = PCA(n_components=0.95)
+X_reduced = pca.fit_transform(X)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs022.html b/doc/pub/week43/html/._week43-bs022.html new file mode 100644 index 000000000..f706c1521 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs022.html @@ -0,0 +1,236 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Incremental PCA

+ +

+One problem with the preceding implementation of PCA is that it requires the whole training set to fit in +memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have +been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch +at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new +instances arrive). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs023.html b/doc/pub/week43/html/._week43-bs023.html new file mode 100644 index 000000000..7703b15c0 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs023.html @@ -0,0 +1,234 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Randomized PCA

+ +

+Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic +algorithm that quickly finds an approximation of the first d principal components. Its computational +complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the +previous algorithms when \( d \) is much smaller than \( n \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs024.html b/doc/pub/week43/html/._week43-bs024.html new file mode 100644 index 000000000..deffe1742 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs024.html @@ -0,0 +1,252 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Kernel PCA

+
+
+

+ +

+The kernel trick is a mathematical technique that implicitly maps instances into a +very high-dimensional space (called the feature space), enabling nonlinear classification and regression +with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature +space corresponds to a complex nonlinear decision boundary in the original space. +It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear +projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at +preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a +twisted manifold. +For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an +

+ + +

from sklearn.decomposition import KernelPCA
+rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
+X_reduced = rbf_pca.fit_transform(X)
+
+

+

+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs025.html b/doc/pub/week43/html/._week43-bs025.html new file mode 100644 index 000000000..e98c5e5e1 --- /dev/null +++ b/doc/pub/week43/html/._week43-bs025.html @@ -0,0 +1,233 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

LLE

+ +

+Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction +(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous +algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its +closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where +these local relationships are best preserved (more details shortly). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/._week43-bs026.html b/doc/pub/week43/html/._week43-bs026.html new file mode 100644 index 000000000..72c4a725a --- /dev/null +++ b/doc/pub/week43/html/._week43-bs026.html @@ -0,0 +1,237 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Other techniques

+ +

+There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. + +

+Here are some of the most popular: + +

    +
  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • +
  • Isomap creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.
  • +
  • t-Distributed Stochastic Neighbor Embedding (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).
  • +
  • Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.
  • +
+ + +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week43/html/reveal.js/.gitignore b/doc/pub/week43/html/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/pub/week43/html/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/pub/week43/html/reveal.js/.travis.yml b/doc/pub/week43/html/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/pub/week43/html/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/week43/html/reveal.js/CONTRIBUTING.md b/doc/pub/week43/html/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/pub/week43/html/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/pub/week43/html/reveal.js/Gruntfile.js b/doc/pub/week43/html/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/pub/week43/html/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/pub/week43/html/reveal.js/LICENSE b/doc/pub/week43/html/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/pub/week43/html/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/pub/week43/html/reveal.js/README.md b/doc/pub/week43/html/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/pub/week43/html/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
+
+
Single Horizontal Slide
+
+
Vertical Slide 1
+
Vertical Slide 2
+
+
+
+``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` +
+``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
+
+``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
+ +
+``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. + +```html +
+ +
+``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
+``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
+

All CSS color formats are supported, like rgba() or hsl().

+
+
+

This slide will have a full-size background image.

+
+
+

This background image will be sized to 100px and repeated.

+
+
+

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

+
+
+

Embeds a web page as a background. Note that the page won't be interactive.

+
+``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
+

This slide will override the presentation transition and zoom!

+
+ +
+

Choose from three transition speeds: default, fast or slow!

+
+``` + +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
+

grow

+

shrink

+

fade-out

+

visible only once

+

blue only once

+

highlight-red

+

highlight-green

+

highlight-blue

+
+``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
+ + I'll fade in, then out + +
+``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
+

Appears last

+

Appears first

+

Appears second

+
+``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
+

+(def lazy-fib
+  (concat
+   [0 1]
+   ((fn rfib [a b]
+        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
+	
+
+``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `
+ +
+ +

 

 

 

+ + + + + + +
+

Week 43: Dimensionality Reduction

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week43/html/week43-reveal.html b/doc/pub/week43/html/week43-reveal.html new file mode 100644 index 000000000..5b6ab719e --- /dev/null +++ b/doc/pub/week43/html/week43-reveal.html @@ -0,0 +1,1490 @@ + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + + + + + + + + + + +
+ + + + +

Week 43: Dimensionality Reduction

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

 
+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

 
+

Sep 16, 2020

+
+

+ +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+
+ + +
+

Why should we think of reducing the dimensionality

+ +

+In addition to the plot of the features, we study now also the covariance (and the correlation matrix). +We use also Pandas to compute the correlation matrix. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+import pandas as pd
+# Making a data frame
+cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+fig, axes = plt.subplots(15,2,figsize=(10,20))
+malignant = cancer.data[cancer.target == 0]
+benign = cancer.data[cancer.target == 1]
+ax = axes.ravel()
+
+for i in range(30):
+    _, bins = np.histogram(cancer.data[:,i], bins =50)
+    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
+    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
+    ax[i].set_title(cancer.feature_names[i])
+    ax[i].set_yticks(())
+ax[0].set_xlabel("Feature magnitude")
+ax[0].set_ylabel("Frequency")
+ax[0].legend(["Malignant", "Benign"], loc ="best")
+fig.tight_layout()
+plt.show()
+
+import seaborn as sns
+correlation_matrix = cancerpd.corr().round(1)
+# use the heatmap function from seaborn to plot the correlation matrix
+# annot = True to print the values inside the square
+sns.heatmap(data=correlation_matrix, annot=True)
+plt.show()
+
+#print eigvalues of correlation matrix
+EigValues, EigVectors = np.linalg.eig(correlation_matrix)
+print(EigValues)
+
+

+In the above example we note two things. In the first plot we display +the overlap of benign and malignant tumors as functions of the various +features in the Wisconsing breast cancer data set. We see that for +some of the features we can distinguish clearly the benign and +malignant cases while for other features we cannot. This can point to +us which features may be of greater interest when we wish to classify +a benign or not benign tumour. + +

+In the second figure we have computed the so-called correlation +matrix, which in our case with thirty features becomes a \( 30\times 30 \) +matrix. + +

+We constructed this matrix using pandas via the statements +

+ + +

cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+

+and then +

+ + +

correlation_matrix = cancerpd.corr().round(1)
+
+

+Diagonalizing this matrix we can in turn say something about which +features are of relevance and which are not. But before we proceed we +need to define covariance and correlation matrices. This leads us to +the classical Principal Component Analysis (PCA) theorem with +applications. +

+ + +
+

Basic ideas of the Principal Component Analysis (PCA)

+ +

+The principal component analysis deals with the problem of fitting a +low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than +the totaldimension \( D \) of the problem at hand (our data +set). Mathematically it can be formulated as a statistical problem or +a geometric problem. In our discussion of the theorem for the +classical PCA, we will stay with a statistical approach. This is also +what set the scene historically which for the PCA. + +

+We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) + +

    +

  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • +

  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • +

  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • +
+
+ + +
+

Introducing the Covariance and Correlation functions

+ +

+Before we discuss the PCA theorem, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities + +

+Suppose we have defined two vectors +\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +

 
+$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ + \end{bmatrix}, +$$ +

 
+ +where for example +

 
+$$ +\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +$$ +

 
+ +With this definition and recalling that the variance is defined as +

 
+$$ +\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +$$ +

 
+ +we can rewrite the covariance matrix as +

 
+$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ + \end{bmatrix}. +$$ +

 
+ +

+The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function + +

 
+$$ +\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. +$$ +

 
+ +

+The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +\in [-1,1] \). This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) +and \( \boldsymbol{y} \) as + +

 
+$$ +\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ + \end{bmatrix}, +$$ +

 
+ +

+In the above example this is the function we constructed using pandas. +

+ + +
+

Correlation Function and Design/Feature Matrix

+ +

+In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +we defined the design/feature matrix \( \boldsymbol{X} \) as + +

 
+$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ +

 
+ +with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +entries \( n \) being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as +

 
+$$ +\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, +$$ +

 
+ +with a given vector +

 
+$$ +\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. +$$ +

 
+ +

+With these definitions, we can now rewrite our \( 2\times 2 \) +correaltion/covariance matrix in terms of a moe general design/feature +matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) +covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) + +

 
+$$ +\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} +\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ +\end{bmatrix}, +$$ +

 
+ +and the correlation matrix +

 
+$$ +\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, +$$ +

 
+

+ + +
+

Covariance Matrix Examples

+ +

+The Numpy function np.cov calculates the covariance elements using +the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have +the exact mean values. The following simple function uses the +np.vstack function which takes each vector of dimension \( 1\times n \) +and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) + +

 
+$$ +\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\ + x_1 & y_1 \\ + x_2 & y_2\\ + \dots & \dots \\ + x_{n-2} & y_{n-2}\\ + x_{n-1} & y_{n-1} & + \end{bmatrix}, +$$ +

 
+ +

+which in turn is converted into into the \( 2\times 2 \) covariance matrix +\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate +the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy +function np.mean(x). We can also extract the eigenvalues of the +covariance matrix through the np.linalg.eig() function. + +

+ + +

# Importing various packages
+import numpy as np
+n = 100
+x = np.random.normal(size=n)
+print(np.mean(x))
+y = 4+3*x+np.random.normal(size=n)
+print(np.mean(y))
+W = np.vstack((x, y))
+C = np.cov(W)
+print(C)
+
+
+ + +
+

Correlation Matrix

+ +

+The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). + +

+ + +

import numpy as np
+n = 100
+# define two vectors                                                                                           
+x = np.random.random(size=n)
+y = 4+3*x+np.random.normal(size=n)
+#scaling the x and y vectors                                                                                   
+x = x - np.mean(x)
+y = y - np.mean(y)
+variance_x = np.sum(x@x)/n
+variance_y = np.sum(y@y)/n
+print(variance_x)
+print(variance_y)
+cov_xy = np.sum(x@y)/n
+cov_xx = np.sum(x@x)/n
+cov_yy = np.sum(y@y)/n
+C = np.zeros((2,2))
+C[0,0]= cov_xx/variance_x
+C[1,1]= cov_yy/variance_y
+C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
+C[1,0]= C[0,1]
+print(C)
+
+

+We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix. + +

+The above procedure with numpy can be made more compact if we use pandas. +

+ + +
+

Correlation Matrix with Pandas

+ +

+We whow here how we can set up the correlation matrix using pandas, as done in this simple code +

+ + +

import numpy as np
+import pandas as pd
+n = 10
+x = np.random.normal(size=n)
+x = x - np.mean(x)
+y = 4+3*x+np.random.normal(size=n)
+y = y - np.mean(y)
+X = (np.vstack((x, y))).T
+print(X)
+Xpd = pd.DataFrame(X)
+print(Xpd)
+correlation_matrix = Xpd.corr()
+print(correlation_matrix)
+
+

+We expand this model to the Franke function discussed above. +

+ + +
+

Correlation Matrix with Pandas and the Franke function

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+
+
+def FrankeFunction(x,y):
+	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
+	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
+	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
+	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
+	return term1 + term2 + term3 + term4
+
+
+def create_X(x, y, n ):
+	if len(x.shape) > 1:
+		x = np.ravel(x)
+		y = np.ravel(y)
+
+	N = len(x)
+	l = int((n+1)*(n+2)/2)		# Number of elements in beta
+	X = np.ones((N,l))
+
+	for i in range(1,n+1):
+		q = int((i)*(i+1)/2)
+		for k in range(i+1):
+			X[:,q+k] = (x**(i-k))*(y**k)
+
+	return X
+
+
+# Making meshgrid of datapoints and compute Franke's function
+n = 4
+N = 100
+x = np.sort(np.random.uniform(0, 1, N))
+y = np.sort(np.random.uniform(0, 1, N))
+z = FrankeFunction(x, y)
+X = create_X(x, y, n=n)    
+
+Xpd = pd.DataFrame(X)
+# subtract the mean values and set up the covariance matrix
+Xpd = Xpd - Xpd.mean()
+covariance_matrix = Xpd.cov()
+print(covariance_matrix)
+
+

+We note here that the covariance is zero for the first rows and +columns since all matrix elements in the design matrix were set to one +(we are fitting the function in terms of a polynomial of degree \( n \)). + +

+This means that the variance for these elements will be zero and will +cause problems when we set up the correlation matrix. We can simply +drop these elements and construct a correlation +matrix without these elements. +

+ + +
+

Rewriting the Covariance and/or Correlation Matrix

+ +

+We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as +

 
+$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ +

 
+ +

+To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) +

 
+$$ +\boldsymbol{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ +\end{bmatrix}. +$$ +

 
+ +

+If we then compute the expectation value +

 
+$$ +\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\begin{bmatrix} +x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ +x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ +\end{bmatrix}, +$$ +

 
+ +which is just +

 
+$$ +\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ + \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ + \end{bmatrix}, +$$ +

 
+ +where we wrote

 
+$$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ +

 
to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). + +

+It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). +

+ + +
+

Towards the PCA theorem

+ +

+We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as +

 
+$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ +

 
+ +Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). +These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \). + +

+Assume also that there is a transformation \( \boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). + +

+That is we have +

 
+$$ +\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}\boldsymbol{X}\boldsymbol{X}^T\boldsymbol{S}^T]=\boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ +

 
+ +since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S}^T \) from the left we have +

 
+$$ +\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ +

 
+ +and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that + +

 
+$$ +\boldsymbol{S}^T_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T_i. +$$ +

 
+ +

+In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is +\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). + +

+The eigenvalues tell us then how much we need to stretch the +corresponding eigenvectors. Dimensions with large eigenvalues have +thus large variations (large variance) and define therefore useful +dimensions. The data points are more spread out in the direction of +these eigenvectors. Smaller eigenvalues mean on the other hand that +the corresponding eigenvectors are shrunk accordingly and the data +points are tightly bunched together and there is not much variation in +these specific directions. Hopefully then we could leave it out +dimensions where the eigenvalues are very small. If \( p \) is very large, +we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) +features/predictors. +

+ + +
+

The Algorithm before theorem

+ +

+Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. + +

    +

  • Set up the datapoints for the design/feature matrix \( \boldsymbol{X} \) with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) referring to the column numbers and the entries \( n \) being the row elements.
  • +
+

 
+$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ +

 
+ + +

    +

  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • +

  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}\overline{\boldsymbol{X}}^T] \).
  • +

  • Find the eigenpairs of \( \boldsymbol{C} \) with eigenvalues \( [\lambda_0,\lambda_1,\dots,\lambda_{p-1}] \) and eigenvectors \( [\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \).
  • +

  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • +

  • Keep only those \( l \) eigenvalues larger than a selected threshold value, discarding thus \( p-l \) features since we expect small variations in the data here.
  • +
+
+ + +
+

Writing our own PCA code

+ +

+We will use a simple example first with two-dimensional data +drawn from a multivariate normal distribution with the following mean and covariance matrix: +

 
+$$ +\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ +2 & 2 +\end{bmatrix} +$$ +

 
+ +Note that the mean refers to each column of data. +We will generate \( n = 1000 \) points \( X = \{ x_1, \ldots, x_N \} \) from +this distribution, and store them in the \( 1000 \times 2 \) matrix \( \boldsymbol{X} \). + +

+The following Python code aids in setting up the data and writing out the design matrix. +Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). +

+ + +

import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+n = 10000
+mean = (-1, 2)
+cov = [[4, 2], [2, 2]]
+X = np.random.multivariate_normal(mean, cov, n)
+
+

+Now we are going to implement the PCA algorithm. We will break it down into various substeps. + +

Compute the sample mean and center the data

+ +

+The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is +

 
+$$ +\mu_n = \frac{1}{n} \sum_{i=1}^n x_i +$$ +

 
+ +and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form +

 
+$$ +\bar{x}_i = x_i - \mu_n. +$$ +

 
+ +When you are done with these steps, print out \( \mu_n \) to verify it is +close to \( \mu \) and plot your mean centered data to verify it is +centered at the origin! Compare your code with the functionality from Scikit-Learn discussed above. +The following code elements perform these operations using pandas or using our own functionality for doing so. The latter, using numpy is rather simple through the mean() function. +

+ + +

df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+
+

+Alternatively, we could use the functions we discussed +earlier for scaling the data set. That is, we could have used the +StandardScaler function in Scikit-Learn, a function which ensures +that for each feature/predictor we study the mean value is zero and +the variance is one (every column in the design/feature matrix). You +would then not get the same results, since we divide by the +variance. The diagonal covariance matrix elements will then be one, +while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our +specific case. + +

Compute the sample covariance

+ +

+Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation +

 
+$$ +\begin{equation*} +\Sigma_n = \frac{1}{n-1} \sum_{i=1}^n \bar{x}_i^T \bar{x}_i = \frac{1}{n-1} \sum_{i=1}^n (x_i - \mu_n)^T (x_i - \mu_n) +\end{equation*} +$$ +

 
+ +where the data points \( x_i \in \mathbb{R}^p \) (here in this example \( p = 2 \)) are column vectors and \( x^T \) is the transpose of \( x \). +We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows +

+ + +

print(df.cov())
+print(np.cov(X_centered.T))
+
+

+Note that the way we define the covariance matrix here has a factor \( n-1 \) instead of \( n \). This is included in the cov() function by numpy and pandas. +Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. +

+ + +

# extract the relevant columns from the centered design matrix of dim n x 2
+x = X_centered[:,0]
+y = X_centered[:,1]
+Cov = np.zeros((2,2))
+Cov[0,1] = np.sum(x.T@y)/(n-1.0)
+Cov[0,0] = np.sum(x.T@x)/(n-1.0)
+Cov[1,1] = np.sum(y.T@y)/(n-1.0)
+Cov[1,0]= Cov[0,1]
+print("Centered covariance using own code")
+print(Cov)
+plt.plot(x, y, 'x')
+plt.axis('equal')
+plt.show()
+
+

+Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. +The plot shows how the data are clustered around a line with slope close to one. Is this expected? + +

Diagonalize the sample covariance matrix to obtain the principal components

+ +

+Now we are ready to solve for the principal components! To do so we +diagonalize the sample covariance matrix \( \Sigma \). We can use the +function np.linalg.eig to do so. It will return the eigenvalues and +eigenvectors of \( \Sigma \). Once we have these we can perform the +following tasks: + +

    +

  • We compute the percentage of the total variance captured by the first principal component
  • +

  • We plot the mean centered data and lines along the first and second principal components
  • +

  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • +

  • Finally, we approximate the data as
  • +
+

 
+$$ +\begin{equation*} +x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 +\end{equation*} +$$ +

 
+ +where \( v_0 \) is the first principal component. + +

+Collecting all these steps we can write our own PCA function and +compare this with the functionality included in Scikit-Learn. + +

+The code here outlines some of the elements we could include in the +analysis. Feel free to extend upon this in order to address the above +questions. + +

+ + +

# diagonalize and obtain eigenvalues, not necessarily sorted
+EigValues, EigVectors = np.linalg.eig(Cov)
+# sort eigenvectors and eigenvalues
+#permute = EigValues.argsort()
+#EigValues = EigValues[permute]
+#EigVectors = EigVectors[:,permute]
+print("Eigenvalues of Covariance matrix")
+for i in range(2):
+    print(EigValues[i])
+FirstEigvector = EigVectors[:,0]
+SecondEigvector = EigVectors[:,1]
+print("First eigenvector")
+print(FirstEigvector)
+print("Second eigenvector")
+print(SecondEigvector)
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2Dsl = pca.fit_transform(X)
+print("Eigenvector of largest eigenvalue")
+print(pca.components_.T[:, 0])
+
+

+This code does not contain all the above elements, but it shows how we can use Scikit-Learn to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? +

+ + +
+

Classical PCA Theorem

+ +

+We assume now that we have a design matrix \( \boldsymbol{X} \) which has been +centered as discussed above. For the sake of simplicity we skip the +overline symbol. The matrix is defined in terms of the various column +vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension +\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). + +

+We assume also that we have an orthogonal transformation \( \boldsymbol{W}\in {\mathbb{R}}^{p\times p} \). We define the reconstruction error (which is similar to the mean squared error we have seen before) as +

 
+$$ +J(\boldsymbol{W},\boldsymbol{Z}) = \frac{1}{n}\sum_i (\boldsymbol{x}_i - \overline{\boldsymbol{x}}_i)^2, +$$ +

 
+ +with \( \overline{\boldsymbol{x}}_i = \boldsymbol{W}\boldsymbol{z}_i \), where \( \boldsymbol{z}_i \) is a row vector with dimension \( {\mathbb{R}}^{n} \) of the matrix +\( \boldsymbol{Z}\in{\mathbb{R}}^{p\times n} \). When doing PCA we want to reduce this dimensionality. + +

+The PCA theorem states that minimizing the above reconstruction error +corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which +diagonalizes the empirical covariance(correlation) matrix. The optimal +low-dimensional encoding of the data is then given by a set of vectors +\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the +orthogonal projection of the data onto the columns spanned by the +eigenvectors of the covariance(correlations matrix). + +

+The proof which follows will be updated by mid January 2020. +

+ + +
+

Proof of the PCA Theorem

+ +

+To show the PCA theorem let us start with the assumption that there is one vector \( \boldsymbol{w}_0 \) which corresponds to a solution which minimized the reconstruction error \( J \). This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of \( \boldsymbol{w}_0 \) and \( \boldsymbol{z}_0 \) as +

 
+$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)= \frac{1}{n}\sum_i (\boldsymbol{x}_i - z_{i0}\boldsymbol{w}_0)^2=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2\boldsymbol{w}_0^T\boldsymbol{w}_0), +$$ +

 
+ +which we can rewrite due to the orthogonality of \( \boldsymbol{w}_i \) as +

 
+$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2). +$$ +

 
+ +Minimizing \( J \) with respect to the unknown parameters \( z_{0i} \) we obtain that +

 
+$$ +z_{i0}=\boldsymbol{w}_0^T\boldsymbol{x}_i, +$$ +

 
+ +where the vectors on the rhs are known. +

+ + +
+

PCA Proof continued

+ +

+We have now found the unknown parameters \( z_{i0} \). These correspond to the projected coordinates and we can write +

 
+$$ +J(\boldsymbol{w}_0)= \frac{1}{p}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - z_{i0}^2)=\mathrm{const}-\frac{1}{n}\sum_i z_{i0}^2. +$$ +

 
+ +

+We can show that the variance of the projected coordinates defined by \( \boldsymbol{w}_0^T\boldsymbol{x}_i \) are given by +

 
+$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2, +$$ +

 
+ +since the expectation value of +

 
+$$ +\mathbb{E}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \mathbb{E}[z_{i0}]= \boldsymbol{w}_0^T\mathbb{E}[\boldsymbol{x}_i]=0, +$$ +

 
+ +where we have used the fact that our data are centered. + +

+Recalling our definition of the covariance as +

 
+$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T], +$$ +

 
+ +we have thus that +

 
+$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2=\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0. +$$ +

 
+ +

+We are almost there, we have obtained a relation between minimizing +the reconstruction error and the variance and the covariance +matrix. Minimizing the error is equivalent to maximizing the variance +of the projected data. +

+ + +
+

The final step

+ +

+We could trivially maximize the variance of the projection (and +thereby minimize the error in the reconstruction function) by letting +the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we +want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by +\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a +Lagrange multiplier we can then in turn maximize + +

 
+$$ +J(\boldsymbol{w}_0)= \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0+\lambda_0(1-\boldsymbol{w}_0^T\boldsymbol{w}_0). +$$ +

 
+ +Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain + +

 
+$$ +\frac{\partial J(\boldsymbol{w}_0)}{\partial \boldsymbol{w}_0}= 2\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0-2\lambda_0\boldsymbol{w}_0=0, +$$ +

 
+ +meaning that +

 
+$$ +\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. +$$ +

 
+ +The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix! If we left multiply with \( \boldsymbol{w}_0^T \) we have the variance of the projected data is +

 
+$$ +\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. +$$ +

 
+ +

+If we want to maximize the variance (minimize the construction error) +we simply pick the eigenvector of the covariance matrix with the +largest eigenvalue. This establishes the link between the minimization +of the reconstruction function \( J \) in terms of an orthogonal matrix +and the maximization of the variance and thereby the covariance of our +observations encoded in the design/feature matrix \( \boldsymbol{X} \). + +

+The proof +for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be +established by applying the above arguments and using the fact that +our basis of eigenvectors is orthogonal, see Murphy chapter +12.2. The +discussion in chapter 12.2 of Murphy's text has also a nice link with +the Singular Value Decomposition theorem. For categorical data, see +chapter 12.4 and discussion therein. + +

+Additional part of the proof for the other eigenvectors will be added by mid January 2020. +

+ + +
+

Geometric Interpretation and link with Singular Value Decomposition

+ +

+This material will be added by mid January 2020. +

+ + +
+

Principal Component Analysis

+ +

+Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. +First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. + +

+The following Python code uses NumPy’s svd() function to obtain all the principal components of the +training set, then extracts the first two principal components. First we center the data using either pandas or our own code +

+ + +

import numpy as np
+import pandas as pd
+from IPython.display import display
+np.random.seed(100)
+# setting up a 10 x 5 vanilla matrix 
+rows = 10
+cols = 5
+X = np.random.randn(rows,cols)
+df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+display(df)
+
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+# Then check the difference between pandas and our own set up
+print(X_centered-df)
+#Now we do an SVD
+U, s, V = np.linalg.svd(X_centered)
+c1 = V.T[:, 0]
+c2 = V.T[:, 1]
+W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+print(X2D)
+
+

+PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering +the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t +forget to center the data first. + +

+Once you have identified all the principal components, you can reduce the dimensionality of the dataset +down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. +Selecting this hyperplane ensures that the projection will preserve as much variance as possible. +

+ + +

W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+
+
+ + +
+

PCA and scikit-learn

+ +

+Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The +following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note +that it automatically takes care of centering the data): +

+ + +

#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D = pca.fit_transform(X)
+print(X2D)
+
+

+After fitting the PCA transformer to the dataset, you can access the principal components using the +components variable (note that it contains the PCs as horizontal vectors, so, for example, the first +principal component is equal to +

+ + +

pca.components_.T[:, 0].
+
+

+Another very useful piece of information is the explained variance ratio of each principal component, +available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s +variance that lies along the axis of each principal component. +

+ + +
+

Back to the Cancer Data

+We can now repeat the above but applied to real data, in this case our breast cancer data. +Here we compute performance scores on the training data using logistic regression. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
+# We scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Then perform again a log reg fit
+logreg.fit(X_train_scaled, y_train)
+print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D_train = pca.fit_transform(X_train_scaled)
+# and finally compute the log reg fit and the score on the training data	
+logreg.fit(X2D_train,y_train)
+print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
+
+

+We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. +

+ + +
+

More on the PCA

+ +

+Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to +choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). +Unless, of course, you are reducing dimensionality for data visualization — in that case you will +generally want to reduce the dimensionality down to 2 or 3. +The following code computes PCA without reducing dimensionality, then computes the minimum number +of dimensions required to preserve 95% of the training set’s variance: +

+ + +

pca = PCA()
+pca.fit(X)
+cumsum = np.cumsum(pca.explained_variance_ratio_)
+d = np.argmax(cumsum >= 0.95) + 1
+
+

+You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead +of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be +a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: +

+ + +

pca = PCA(n_components=0.95)
+X_reduced = pca.fit_transform(X)
+
+
+ + +
+

Incremental PCA

+ +

+One problem with the preceding implementation of PCA is that it requires the whole training set to fit in +memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have +been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch +at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new +instances arrive). +

+ + +
+

Randomized PCA

+ +

+Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic +algorithm that quickly finds an approximation of the first d principal components. Its computational +complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the +previous algorithms when \( d \) is much smaller than \( n \). +

+ + +
+

Kernel PCA

+
+ +

+The kernel trick is a mathematical technique that implicitly maps instances into a +very high-dimensional space (called the feature space), enabling nonlinear classification and regression +with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature +space corresponds to a complex nonlinear decision boundary in the original space. +It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear +projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at +preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a +twisted manifold. +For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an +

+ + +

from sklearn.decomposition import KernelPCA
+rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
+X_reduced = rbf_pca.fit_transform(X)
+
+ +
+
+ + +
+

LLE

+ +

+Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction +(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous +algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its +closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where +these local relationships are best preserved (more details shortly). +

+ + +
+

Other techniques

+ +

+There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. + +

+Here are some of the most popular: + +

    +

  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • +

  • Isomap creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.
  • +

  • t-Distributed Stochastic Neighbor Embedding (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).
  • +

  • Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.
  • +
+
+ + + +
+
+ + + + + + + + + + + + diff --git a/doc/pub/week43/html/week43-solarized.html b/doc/pub/week43/html/week43-solarized.html new file mode 100644 index 000000000..2b2e33b7e --- /dev/null +++ b/doc/pub/week43/html/week43-solarized.html @@ -0,0 +1,1283 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Week 43: Dimensionality Reduction

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Why should we think of reducing the dimensionality

+ +

+In addition to the plot of the features, we study now also the covariance (and the correlation matrix). +We use also Pandas to compute the correlation matrix. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+import pandas as pd
+# Making a data frame
+cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+fig, axes = plt.subplots(15,2,figsize=(10,20))
+malignant = cancer.data[cancer.target == 0]
+benign = cancer.data[cancer.target == 1]
+ax = axes.ravel()
+
+for i in range(30):
+    _, bins = np.histogram(cancer.data[:,i], bins =50)
+    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
+    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
+    ax[i].set_title(cancer.feature_names[i])
+    ax[i].set_yticks(())
+ax[0].set_xlabel("Feature magnitude")
+ax[0].set_ylabel("Frequency")
+ax[0].legend(["Malignant", "Benign"], loc ="best")
+fig.tight_layout()
+plt.show()
+
+import seaborn as sns
+correlation_matrix = cancerpd.corr().round(1)
+# use the heatmap function from seaborn to plot the correlation matrix
+# annot = True to print the values inside the square
+sns.heatmap(data=correlation_matrix, annot=True)
+plt.show()
+
+#print eigvalues of correlation matrix
+EigValues, EigVectors = np.linalg.eig(correlation_matrix)
+print(EigValues)
+
+

+In the above example we note two things. In the first plot we display +the overlap of benign and malignant tumors as functions of the various +features in the Wisconsing breast cancer data set. We see that for +some of the features we can distinguish clearly the benign and +malignant cases while for other features we cannot. This can point to +us which features may be of greater interest when we wish to classify +a benign or not benign tumour. + +

+In the second figure we have computed the so-called correlation +matrix, which in our case with thirty features becomes a \( 30\times 30 \) +matrix. + +

+We constructed this matrix using pandas via the statements +

+ + +

cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+

+and then +

+ + +

correlation_matrix = cancerpd.corr().round(1)
+
+

+Diagonalizing this matrix we can in turn say something about which +features are of relevance and which are not. But before we proceed we +need to define covariance and correlation matrices. This leads us to +the classical Principal Component Analysis (PCA) theorem with +applications. + +

+









+ +

Basic ideas of the Principal Component Analysis (PCA)

+ +

+The principal component analysis deals with the problem of fitting a +low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than +the totaldimension \( D \) of the problem at hand (our data +set). Mathematically it can be formulated as a statistical problem or +a geometric problem. In our discussion of the theorem for the +classical PCA, we will stay with a statistical approach. This is also +what set the scene historically which for the PCA. + +

+We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) + +

    +
  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • +
  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • +
  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • +
+ +









+ +

Introducing the Covariance and Correlation functions

+ +

+Before we discuss the PCA theorem, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities + +

+Suppose we have defined two vectors +\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ + \end{bmatrix}, +$$ + +where for example +$$ +\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +$$ + +With this definition and recalling that the variance is defined as +$$ +\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +$$ + +we can rewrite the covariance matrix as +$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ + \end{bmatrix}. +$$ + +

+The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function + +$$ +\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. +$$ + +

+The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +\in [-1,1] \). This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) +and \( \boldsymbol{y} \) as + +$$ +\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ + \end{bmatrix}, +$$ + +

+In the above example this is the function we constructed using pandas. + +

+









+ +

Correlation Function and Design/Feature Matrix

+ +

+In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +we defined the design/feature matrix \( \boldsymbol{X} \) as + +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ + +with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +entries \( n \) being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as +$$ +\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, +$$ + +with a given vector +$$ +\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. +$$ + +

+With these definitions, we can now rewrite our \( 2\times 2 \) +correaltion/covariance matrix in terms of a moe general design/feature +matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) +covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) + +$$ +\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} +\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ +\end{bmatrix}, +$$ + +and the correlation matrix +$$ +\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, +$$ + +

+









+ +

Covariance Matrix Examples

+ +

+The Numpy function np.cov calculates the covariance elements using +the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have +the exact mean values. The following simple function uses the +np.vstack function which takes each vector of dimension \( 1\times n \) +and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) + +$$ +\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\ + x_1 & y_1 \\ + x_2 & y_2\\ + \dots & \dots \\ + x_{n-2} & y_{n-2}\\ + x_{n-1} & y_{n-1} & + \end{bmatrix}, +$$ + +

+which in turn is converted into into the \( 2\times 2 \) covariance matrix +\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate +the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy +function np.mean(x). We can also extract the eigenvalues of the +covariance matrix through the np.linalg.eig() function. + +

+ + +

# Importing various packages
+import numpy as np
+n = 100
+x = np.random.normal(size=n)
+print(np.mean(x))
+y = 4+3*x+np.random.normal(size=n)
+print(np.mean(y))
+W = np.vstack((x, y))
+C = np.cov(W)
+print(C)
+
+

+









+ +

Correlation Matrix

+ +

+The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). + +

+ + +

import numpy as np
+n = 100
+# define two vectors                                                                                           
+x = np.random.random(size=n)
+y = 4+3*x+np.random.normal(size=n)
+#scaling the x and y vectors                                                                                   
+x = x - np.mean(x)
+y = y - np.mean(y)
+variance_x = np.sum(x@x)/n
+variance_y = np.sum(y@y)/n
+print(variance_x)
+print(variance_y)
+cov_xy = np.sum(x@y)/n
+cov_xx = np.sum(x@x)/n
+cov_yy = np.sum(y@y)/n
+C = np.zeros((2,2))
+C[0,0]= cov_xx/variance_x
+C[1,1]= cov_yy/variance_y
+C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
+C[1,0]= C[0,1]
+print(C)
+
+

+We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix. + +

+The above procedure with numpy can be made more compact if we use pandas. + +

+









+ +

Correlation Matrix with Pandas

+ +

+We whow here how we can set up the correlation matrix using pandas, as done in this simple code +

+ + +

import numpy as np
+import pandas as pd
+n = 10
+x = np.random.normal(size=n)
+x = x - np.mean(x)
+y = 4+3*x+np.random.normal(size=n)
+y = y - np.mean(y)
+X = (np.vstack((x, y))).T
+print(X)
+Xpd = pd.DataFrame(X)
+print(Xpd)
+correlation_matrix = Xpd.corr()
+print(correlation_matrix)
+
+

+We expand this model to the Franke function discussed above. + +

+









+ +

Correlation Matrix with Pandas and the Franke function

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+
+
+def FrankeFunction(x,y):
+	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
+	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
+	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
+	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
+	return term1 + term2 + term3 + term4
+
+
+def create_X(x, y, n ):
+	if len(x.shape) > 1:
+		x = np.ravel(x)
+		y = np.ravel(y)
+
+	N = len(x)
+	l = int((n+1)*(n+2)/2)		# Number of elements in beta
+	X = np.ones((N,l))
+
+	for i in range(1,n+1):
+		q = int((i)*(i+1)/2)
+		for k in range(i+1):
+			X[:,q+k] = (x**(i-k))*(y**k)
+
+	return X
+
+
+# Making meshgrid of datapoints and compute Franke's function
+n = 4
+N = 100
+x = np.sort(np.random.uniform(0, 1, N))
+y = np.sort(np.random.uniform(0, 1, N))
+z = FrankeFunction(x, y)
+X = create_X(x, y, n=n)    
+
+Xpd = pd.DataFrame(X)
+# subtract the mean values and set up the covariance matrix
+Xpd = Xpd - Xpd.mean()
+covariance_matrix = Xpd.cov()
+print(covariance_matrix)
+
+

+We note here that the covariance is zero for the first rows and +columns since all matrix elements in the design matrix were set to one +(we are fitting the function in terms of a polynomial of degree \( n \)). + +

+This means that the variance for these elements will be zero and will +cause problems when we set up the correlation matrix. We can simply +drop these elements and construct a correlation +matrix without these elements. + +

+









+ +

Rewriting the Covariance and/or Correlation Matrix

+ +

+We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ + +

+To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ +\end{bmatrix}. +$$ + +

+If we then compute the expectation value +$$ +\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\begin{bmatrix} +x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ +x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ +\end{bmatrix}, +$$ + +which is just +$$ +\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ + \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ + \end{bmatrix}, +$$ + +where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). + +

+It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). + +

+









+ +

Towards the PCA theorem

+ +

+We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ + +Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). +These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \). + +

+Assume also that there is a transformation \( \boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). + +

+That is we have +$$ +\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}\boldsymbol{X}\boldsymbol{X}^T\boldsymbol{S}^T]=\boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ + +since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S}^T \) from the left we have +$$ +\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ + +and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that + +$$ +\boldsymbol{S}^T_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T_i. +$$ + +

+In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is +\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). + +

+The eigenvalues tell us then how much we need to stretch the +corresponding eigenvectors. Dimensions with large eigenvalues have +thus large variations (large variance) and define therefore useful +dimensions. The data points are more spread out in the direction of +these eigenvectors. Smaller eigenvalues mean on the other hand that +the corresponding eigenvectors are shrunk accordingly and the data +points are tightly bunched together and there is not much variation in +these specific directions. Hopefully then we could leave it out +dimensions where the eigenvalues are very small. If \( p \) is very large, +we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) +features/predictors. + +

+









+ +

The Algorithm before theorem

+ +

+Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. + +

    +
  • Set up the datapoints for the design/feature matrix \( \boldsymbol{X} \) with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) referring to the column numbers and the entries \( n \) being the row elements.
  • +
+ +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ + + +
    +
  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • +
  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}\overline{\boldsymbol{X}}^T] \).
  • +
  • Find the eigenpairs of \( \boldsymbol{C} \) with eigenvalues \( [\lambda_0,\lambda_1,\dots,\lambda_{p-1}] \) and eigenvectors \( [\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \).
  • +
  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • +
  • Keep only those \( l \) eigenvalues larger than a selected threshold value, discarding thus \( p-l \) features since we expect small variations in the data here.
  • +
+ +









+ +

Writing our own PCA code

+ +

+We will use a simple example first with two-dimensional data +drawn from a multivariate normal distribution with the following mean and covariance matrix: +$$ +\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ +2 & 2 +\end{bmatrix} +$$ + +Note that the mean refers to each column of data. +We will generate \( n = 1000 \) points \( X = \{ x_1, \ldots, x_N \} \) from +this distribution, and store them in the \( 1000 \times 2 \) matrix \( \boldsymbol{X} \). + +

+The following Python code aids in setting up the data and writing out the design matrix. +Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). +

+ + +

import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+n = 10000
+mean = (-1, 2)
+cov = [[4, 2], [2, 2]]
+X = np.random.multivariate_normal(mean, cov, n)
+
+

+Now we are going to implement the PCA algorithm. We will break it down into various substeps. + +

Compute the sample mean and center the data

+ +

+The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is +$$ +\mu_n = \frac{1}{n} \sum_{i=1}^n x_i +$$ + +and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form +$$ +\bar{x}_i = x_i - \mu_n. +$$ + +When you are done with these steps, print out \( \mu_n \) to verify it is +close to \( \mu \) and plot your mean centered data to verify it is +centered at the origin! Compare your code with the functionality from Scikit-Learn discussed above. +The following code elements perform these operations using pandas or using our own functionality for doing so. The latter, using numpy is rather simple through the mean() function. +

+ + +

df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+
+

+Alternatively, we could use the functions we discussed +earlier for scaling the data set. That is, we could have used the +StandardScaler function in Scikit-Learn, a function which ensures +that for each feature/predictor we study the mean value is zero and +the variance is one (every column in the design/feature matrix). You +would then not get the same results, since we divide by the +variance. The diagonal covariance matrix elements will then be one, +while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our +specific case. + +

Compute the sample covariance

+ +

+Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation +$$ +\begin{equation*} +\Sigma_n = \frac{1}{n-1} \sum_{i=1}^n \bar{x}_i^T \bar{x}_i = \frac{1}{n-1} \sum_{i=1}^n (x_i - \mu_n)^T (x_i - \mu_n) +\end{equation*} +$$ + +where the data points \( x_i \in \mathbb{R}^p \) (here in this example \( p = 2 \)) are column vectors and \( x^T \) is the transpose of \( x \). +We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows +

+ + +

print(df.cov())
+print(np.cov(X_centered.T))
+
+

+Note that the way we define the covariance matrix here has a factor \( n-1 \) instead of \( n \). This is included in the cov() function by numpy and pandas. +Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. +

+ + +

# extract the relevant columns from the centered design matrix of dim n x 2
+x = X_centered[:,0]
+y = X_centered[:,1]
+Cov = np.zeros((2,2))
+Cov[0,1] = np.sum(x.T@y)/(n-1.0)
+Cov[0,0] = np.sum(x.T@x)/(n-1.0)
+Cov[1,1] = np.sum(y.T@y)/(n-1.0)
+Cov[1,0]= Cov[0,1]
+print("Centered covariance using own code")
+print(Cov)
+plt.plot(x, y, 'x')
+plt.axis('equal')
+plt.show()
+
+

+Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. +The plot shows how the data are clustered around a line with slope close to one. Is this expected? + +

Diagonalize the sample covariance matrix to obtain the principal components

+ +

+Now we are ready to solve for the principal components! To do so we +diagonalize the sample covariance matrix \( \Sigma \). We can use the +function np.linalg.eig to do so. It will return the eigenvalues and +eigenvectors of \( \Sigma \). Once we have these we can perform the +following tasks: + +

    +
  • We compute the percentage of the total variance captured by the first principal component
  • +
  • We plot the mean centered data and lines along the first and second principal components
  • +
  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • +
  • Finally, we approximate the data as
  • +
+ +$$ +\begin{equation*} +x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 +\end{equation*} +$$ + +where \( v_0 \) is the first principal component. + +

+Collecting all these steps we can write our own PCA function and +compare this with the functionality included in Scikit-Learn. + +

+The code here outlines some of the elements we could include in the +analysis. Feel free to extend upon this in order to address the above +questions. + +

+ + +

# diagonalize and obtain eigenvalues, not necessarily sorted
+EigValues, EigVectors = np.linalg.eig(Cov)
+# sort eigenvectors and eigenvalues
+#permute = EigValues.argsort()
+#EigValues = EigValues[permute]
+#EigVectors = EigVectors[:,permute]
+print("Eigenvalues of Covariance matrix")
+for i in range(2):
+    print(EigValues[i])
+FirstEigvector = EigVectors[:,0]
+SecondEigvector = EigVectors[:,1]
+print("First eigenvector")
+print(FirstEigvector)
+print("Second eigenvector")
+print(SecondEigvector)
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2Dsl = pca.fit_transform(X)
+print("Eigenvector of largest eigenvalue")
+print(pca.components_.T[:, 0])
+
+

+This code does not contain all the above elements, but it shows how we can use Scikit-Learn to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? + +

+









+ +

Classical PCA Theorem

+ +

+We assume now that we have a design matrix \( \boldsymbol{X} \) which has been +centered as discussed above. For the sake of simplicity we skip the +overline symbol. The matrix is defined in terms of the various column +vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension +\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). + +

+We assume also that we have an orthogonal transformation \( \boldsymbol{W}\in {\mathbb{R}}^{p\times p} \). We define the reconstruction error (which is similar to the mean squared error we have seen before) as +$$ +J(\boldsymbol{W},\boldsymbol{Z}) = \frac{1}{n}\sum_i (\boldsymbol{x}_i - \overline{\boldsymbol{x}}_i)^2, +$$ + +with \( \overline{\boldsymbol{x}}_i = \boldsymbol{W}\boldsymbol{z}_i \), where \( \boldsymbol{z}_i \) is a row vector with dimension \( {\mathbb{R}}^{n} \) of the matrix +\( \boldsymbol{Z}\in{\mathbb{R}}^{p\times n} \). When doing PCA we want to reduce this dimensionality. + +

+The PCA theorem states that minimizing the above reconstruction error +corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which +diagonalizes the empirical covariance(correlation) matrix. The optimal +low-dimensional encoding of the data is then given by a set of vectors +\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the +orthogonal projection of the data onto the columns spanned by the +eigenvectors of the covariance(correlations matrix). + +

+The proof which follows will be updated by mid January 2020. + +

+









+ +

Proof of the PCA Theorem

+ +

+To show the PCA theorem let us start with the assumption that there is one vector \( \boldsymbol{w}_0 \) which corresponds to a solution which minimized the reconstruction error \( J \). This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of \( \boldsymbol{w}_0 \) and \( \boldsymbol{z}_0 \) as +$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)= \frac{1}{n}\sum_i (\boldsymbol{x}_i - z_{i0}\boldsymbol{w}_0)^2=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2\boldsymbol{w}_0^T\boldsymbol{w}_0), +$$ + +which we can rewrite due to the orthogonality of \( \boldsymbol{w}_i \) as +$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2). +$$ + +Minimizing \( J \) with respect to the unknown parameters \( z_{0i} \) we obtain that +$$ +z_{i0}=\boldsymbol{w}_0^T\boldsymbol{x}_i, +$$ + +where the vectors on the rhs are known. + +

+









+ +

PCA Proof continued

+ +

+We have now found the unknown parameters \( z_{i0} \). These correspond to the projected coordinates and we can write +$$ +J(\boldsymbol{w}_0)= \frac{1}{p}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - z_{i0}^2)=\mathrm{const}-\frac{1}{n}\sum_i z_{i0}^2. +$$ + +

+We can show that the variance of the projected coordinates defined by \( \boldsymbol{w}_0^T\boldsymbol{x}_i \) are given by +$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2, +$$ + +since the expectation value of +$$ +\mathbb{E}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \mathbb{E}[z_{i0}]= \boldsymbol{w}_0^T\mathbb{E}[\boldsymbol{x}_i]=0, +$$ + +where we have used the fact that our data are centered. + +

+Recalling our definition of the covariance as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T], +$$ + +we have thus that +$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2=\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0. +$$ + +

+We are almost there, we have obtained a relation between minimizing +the reconstruction error and the variance and the covariance +matrix. Minimizing the error is equivalent to maximizing the variance +of the projected data. + +

+









+ +

The final step

+ +

+We could trivially maximize the variance of the projection (and +thereby minimize the error in the reconstruction function) by letting +the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we +want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by +\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a +Lagrange multiplier we can then in turn maximize + +$$ +J(\boldsymbol{w}_0)= \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0+\lambda_0(1-\boldsymbol{w}_0^T\boldsymbol{w}_0). +$$ + +Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain + +$$ +\frac{\partial J(\boldsymbol{w}_0)}{\partial \boldsymbol{w}_0}= 2\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0-2\lambda_0\boldsymbol{w}_0=0, +$$ + +meaning that +$$ +\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. +$$ + +The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix! If we left multiply with \( \boldsymbol{w}_0^T \) we have the variance of the projected data is +$$ +\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. +$$ + +

+If we want to maximize the variance (minimize the construction error) +we simply pick the eigenvector of the covariance matrix with the +largest eigenvalue. This establishes the link between the minimization +of the reconstruction function \( J \) in terms of an orthogonal matrix +and the maximization of the variance and thereby the covariance of our +observations encoded in the design/feature matrix \( \boldsymbol{X} \). + +

+The proof +for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be +established by applying the above arguments and using the fact that +our basis of eigenvectors is orthogonal, see Murphy chapter +12.2. The +discussion in chapter 12.2 of Murphy's text has also a nice link with +the Singular Value Decomposition theorem. For categorical data, see +chapter 12.4 and discussion therein. + +

+Additional part of the proof for the other eigenvectors will be added by mid January 2020. + +

+









+ +

Geometric Interpretation and link with Singular Value Decomposition

+ +

+This material will be added by mid January 2020. + +

+









+ +

Principal Component Analysis

+ +

+Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. +First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. + +

+The following Python code uses NumPy’s svd() function to obtain all the principal components of the +training set, then extracts the first two principal components. First we center the data using either pandas or our own code +

+ + +

import numpy as np
+import pandas as pd
+from IPython.display import display
+np.random.seed(100)
+# setting up a 10 x 5 vanilla matrix 
+rows = 10
+cols = 5
+X = np.random.randn(rows,cols)
+df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+display(df)
+
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+# Then check the difference between pandas and our own set up
+print(X_centered-df)
+#Now we do an SVD
+U, s, V = np.linalg.svd(X_centered)
+c1 = V.T[:, 0]
+c2 = V.T[:, 1]
+W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+print(X2D)
+
+

+PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering +the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t +forget to center the data first. + +

+Once you have identified all the principal components, you can reduce the dimensionality of the dataset +down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. +Selecting this hyperplane ensures that the projection will preserve as much variance as possible. +

+ + +

W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+
+

+ + +

PCA and scikit-learn

+ +

+Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The +following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note +that it automatically takes care of centering the data): +

+ + +

#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D = pca.fit_transform(X)
+print(X2D)
+
+

+After fitting the PCA transformer to the dataset, you can access the principal components using the +components variable (note that it contains the PCs as horizontal vectors, so, for example, the first +principal component is equal to +

+ + +

pca.components_.T[:, 0].
+
+

+Another very useful piece of information is the explained variance ratio of each principal component, +available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s +variance that lies along the axis of each principal component. + +

+









+ +

Back to the Cancer Data

+We can now repeat the above but applied to real data, in this case our breast cancer data. +Here we compute performance scores on the training data using logistic regression. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
+# We scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Then perform again a log reg fit
+logreg.fit(X_train_scaled, y_train)
+print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D_train = pca.fit_transform(X_train_scaled)
+# and finally compute the log reg fit and the score on the training data	
+logreg.fit(X2D_train,y_train)
+print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
+
+

+We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. + +

+









+ +

More on the PCA

+ +

+Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to +choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). +Unless, of course, you are reducing dimensionality for data visualization — in that case you will +generally want to reduce the dimensionality down to 2 or 3. +The following code computes PCA without reducing dimensionality, then computes the minimum number +of dimensions required to preserve 95% of the training set’s variance: +

+ + +

pca = PCA()
+pca.fit(X)
+cumsum = np.cumsum(pca.explained_variance_ratio_)
+d = np.argmax(cumsum >= 0.95) + 1
+
+

+You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead +of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be +a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: +

+ + +

pca = PCA(n_components=0.95)
+X_reduced = pca.fit_transform(X)
+
+

+









+ +

Incremental PCA

+ +

+One problem with the preceding implementation of PCA is that it requires the whole training set to fit in +memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have +been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch +at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new +instances arrive). + +

+









+ +

Randomized PCA

+ +

+Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic +algorithm that quickly finds an approximation of the first d principal components. Its computational +complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the +previous algorithms when \( d \) is much smaller than \( n \). + +

+









+ +

Kernel PCA

+
+ +

+ +

+The kernel trick is a mathematical technique that implicitly maps instances into a +very high-dimensional space (called the feature space), enabling nonlinear classification and regression +with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature +space corresponds to a complex nonlinear decision boundary in the original space. +It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear +projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at +preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a +twisted manifold. +For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an +

+ + +

from sklearn.decomposition import KernelPCA
+rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
+X_reduced = rbf_pca.fit_transform(X)
+
+ +
+ + +

+









+ +

LLE

+ +

+Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction +(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous +algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its +closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where +these local relationships are best preserved (more details shortly). + +

+









+ +

Other techniques

+ +

+There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. + +

+Here are some of the most popular: + +

    +
  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • +
  • Isomap creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.
  • +
  • t-Distributed Stochastic Neighbor Embedding (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).
  • +
  • Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.
  • +
+ + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week43/html/week43.html b/doc/pub/week43/html/week43.html new file mode 100644 index 000000000..96f11921e --- /dev/null +++ b/doc/pub/week43/html/week43.html @@ -0,0 +1,1288 @@ + + + + + + + + +Week 43: Dimensionality Reduction + + + + + + + + + + + + + + + + + + + + + + + +

Week 43: Dimensionality Reduction

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Why should we think of reducing the dimensionality

+ +

+In addition to the plot of the features, we study now also the covariance (and the correlation matrix). +We use also Pandas to compute the correlation matrix. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+import pandas as pd
+# Making a data frame
+cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+fig, axes = plt.subplots(15,2,figsize=(10,20))
+malignant = cancer.data[cancer.target == 0]
+benign = cancer.data[cancer.target == 1]
+ax = axes.ravel()
+
+for i in range(30):
+    _, bins = np.histogram(cancer.data[:,i], bins =50)
+    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
+    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
+    ax[i].set_title(cancer.feature_names[i])
+    ax[i].set_yticks(())
+ax[0].set_xlabel("Feature magnitude")
+ax[0].set_ylabel("Frequency")
+ax[0].legend(["Malignant", "Benign"], loc ="best")
+fig.tight_layout()
+plt.show()
+
+import seaborn as sns
+correlation_matrix = cancerpd.corr().round(1)
+# use the heatmap function from seaborn to plot the correlation matrix
+# annot = True to print the values inside the square
+sns.heatmap(data=correlation_matrix, annot=True)
+plt.show()
+
+#print eigvalues of correlation matrix
+EigValues, EigVectors = np.linalg.eig(correlation_matrix)
+print(EigValues)
+
+

+In the above example we note two things. In the first plot we display +the overlap of benign and malignant tumors as functions of the various +features in the Wisconsing breast cancer data set. We see that for +some of the features we can distinguish clearly the benign and +malignant cases while for other features we cannot. This can point to +us which features may be of greater interest when we wish to classify +a benign or not benign tumour. + +

+In the second figure we have computed the so-called correlation +matrix, which in our case with thirty features becomes a \( 30\times 30 \) +matrix. + +

+We constructed this matrix using pandas via the statements +

+ + +

cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+
+

+and then +

+ + +

correlation_matrix = cancerpd.corr().round(1)
+
+

+Diagonalizing this matrix we can in turn say something about which +features are of relevance and which are not. But before we proceed we +need to define covariance and correlation matrices. This leads us to +the classical Principal Component Analysis (PCA) theorem with +applications. + +

+









+ +

Basic ideas of the Principal Component Analysis (PCA)

+ +

+The principal component analysis deals with the problem of fitting a +low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than +the totaldimension \( D \) of the problem at hand (our data +set). Mathematically it can be formulated as a statistical problem or +a geometric problem. In our discussion of the theorem for the +classical PCA, we will stay with a statistical approach. This is also +what set the scene historically which for the PCA. + +

+We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition) + +

    +
  • Each data point is determined by \( p \) extrinsic (measurement) variables
  • +
  • We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?
  • +
  • If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.
  • +
+ +









+ +

Introducing the Covariance and Correlation functions

+ +

+Before we discuss the PCA theorem, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities + +

+Suppose we have defined two vectors +\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ + \end{bmatrix}, +$$ + +where for example +$$ +\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +$$ + +With this definition and recalling that the variance is defined as +$$ +\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +$$ + +we can rewrite the covariance matrix as +$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ + \end{bmatrix}. +$$ + +

+The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function + +$$ +\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. +$$ + +

+The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +\in [-1,1] \). This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) +and \( \boldsymbol{y} \) as + +$$ +\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ + \end{bmatrix}, +$$ + +

+In the above example this is the function we constructed using pandas. + +

+









+ +

Correlation Function and Design/Feature Matrix

+ +

+In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +we defined the design/feature matrix \( \boldsymbol{X} \) as + +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ + +with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +entries \( n \) being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as +$$ +\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, +$$ + +with a given vector +$$ +\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. +$$ + +

+With these definitions, we can now rewrite our \( 2\times 2 \) +correaltion/covariance matrix in terms of a moe general design/feature +matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) +covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) + +$$ +\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} +\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ +\end{bmatrix}, +$$ + +and the correlation matrix +$$ +\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, +$$ + +

+









+ +

Covariance Matrix Examples

+ +

+The Numpy function np.cov calculates the covariance elements using +the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have +the exact mean values. The following simple function uses the +np.vstack function which takes each vector of dimension \( 1\times n \) +and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) + +$$ +\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\ + x_1 & y_1 \\ + x_2 & y_2\\ + \dots & \dots \\ + x_{n-2} & y_{n-2}\\ + x_{n-1} & y_{n-1} & + \end{bmatrix}, +$$ + +

+which in turn is converted into into the \( 2\times 2 \) covariance matrix +\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate +the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy +function np.mean(x). We can also extract the eigenvalues of the +covariance matrix through the np.linalg.eig() function. + +

+ + +

# Importing various packages
+import numpy as np
+n = 100
+x = np.random.normal(size=n)
+print(np.mean(x))
+y = 4+3*x+np.random.normal(size=n)
+print(np.mean(y))
+W = np.vstack((x, y))
+C = np.cov(W)
+print(C)
+
+

+









+ +

Correlation Matrix

+ +

+The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). + +

+ + +

import numpy as np
+n = 100
+# define two vectors                                                                                           
+x = np.random.random(size=n)
+y = 4+3*x+np.random.normal(size=n)
+#scaling the x and y vectors                                                                                   
+x = x - np.mean(x)
+y = y - np.mean(y)
+variance_x = np.sum(x@x)/n
+variance_y = np.sum(y@y)/n
+print(variance_x)
+print(variance_y)
+cov_xy = np.sum(x@y)/n
+cov_xx = np.sum(x@x)/n
+cov_yy = np.sum(y@y)/n
+C = np.zeros((2,2))
+C[0,0]= cov_xx/variance_x
+C[1,1]= cov_yy/variance_y
+C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
+C[1,0]= C[0,1]
+print(C)
+
+

+We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix. + +

+The above procedure with numpy can be made more compact if we use pandas. + +

+









+ +

Correlation Matrix with Pandas

+ +

+We whow here how we can set up the correlation matrix using pandas, as done in this simple code +

+ + +

import numpy as np
+import pandas as pd
+n = 10
+x = np.random.normal(size=n)
+x = x - np.mean(x)
+y = 4+3*x+np.random.normal(size=n)
+y = y - np.mean(y)
+X = (np.vstack((x, y))).T
+print(X)
+Xpd = pd.DataFrame(X)
+print(Xpd)
+correlation_matrix = Xpd.corr()
+print(correlation_matrix)
+
+

+We expand this model to the Franke function discussed above. + +

+









+ +

Correlation Matrix with Pandas and the Franke function

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+
+
+def FrankeFunction(x,y):
+	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
+	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
+	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
+	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
+	return term1 + term2 + term3 + term4
+
+
+def create_X(x, y, n ):
+	if len(x.shape) > 1:
+		x = np.ravel(x)
+		y = np.ravel(y)
+
+	N = len(x)
+	l = int((n+1)*(n+2)/2)		# Number of elements in beta
+	X = np.ones((N,l))
+
+	for i in range(1,n+1):
+		q = int((i)*(i+1)/2)
+		for k in range(i+1):
+			X[:,q+k] = (x**(i-k))*(y**k)
+
+	return X
+
+
+# Making meshgrid of datapoints and compute Franke's function
+n = 4
+N = 100
+x = np.sort(np.random.uniform(0, 1, N))
+y = np.sort(np.random.uniform(0, 1, N))
+z = FrankeFunction(x, y)
+X = create_X(x, y, n=n)    
+
+Xpd = pd.DataFrame(X)
+# subtract the mean values and set up the covariance matrix
+Xpd = Xpd - Xpd.mean()
+covariance_matrix = Xpd.cov()
+print(covariance_matrix)
+
+

+We note here that the covariance is zero for the first rows and +columns since all matrix elements in the design matrix were set to one +(we are fitting the function in terms of a polynomial of degree \( n \)). + +

+This means that the variance for these elements will be zero and will +cause problems when we set up the correlation matrix. We can simply +drop these elements and construct a correlation +matrix without these elements. + +

+









+ +

Rewriting the Covariance and/or Correlation Matrix

+ +

+We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ + +

+To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \) +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ +\end{bmatrix}. +$$ + +

+If we then compute the expectation value +$$ +\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\begin{bmatrix} +x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ +x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ +\end{bmatrix}, +$$ + +which is just +$$ +\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ + \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ + \end{bmatrix}, +$$ + +where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \). + +

+It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). + +

+









+ +

Towards the PCA theorem

+ +

+We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T= \mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T]. +$$ + +Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \). +These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \). + +

+Assume also that there is a transformation \( \boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \). + +

+That is we have +$$ +\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}\boldsymbol{X}\boldsymbol{X}^T\boldsymbol{S}^T]=\boldsymbol{S}\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ + +since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S}^T \) from the left we have +$$ +\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T, +$$ + +and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that + +$$ +\boldsymbol{S}^T_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}^T_i. +$$ + +

+In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is +\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \). + +

+The eigenvalues tell us then how much we need to stretch the +corresponding eigenvectors. Dimensions with large eigenvalues have +thus large variations (large variance) and define therefore useful +dimensions. The data points are more spread out in the direction of +these eigenvectors. Smaller eigenvalues mean on the other hand that +the corresponding eigenvectors are shrunk accordingly and the data +points are tightly bunched together and there is not much variation in +these specific directions. Hopefully then we could leave it out +dimensions where the eigenvalues are very small. If \( p \) is very large, +we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \) +features/predictors. + +

+









+ +

The Algorithm before theorem

+ +

+Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. + +

    +
  • Set up the datapoints for the design/feature matrix \( \boldsymbol{X} \) with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) referring to the column numbers and the entries \( n \) being the row elements.
  • +
+ +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +$$ + + +
    +
  • Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).
  • +
  • Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}\overline{\boldsymbol{X}}^T] \).
  • +
  • Find the eigenpairs of \( \boldsymbol{C} \) with eigenvalues \( [\lambda_0,\lambda_1,\dots,\lambda_{p-1}] \) and eigenvectors \( [\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \).
  • +
  • Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.
  • +
  • Keep only those \( l \) eigenvalues larger than a selected threshold value, discarding thus \( p-l \) features since we expect small variations in the data here.
  • +
+ +









+ +

Writing our own PCA code

+ +

+We will use a simple example first with two-dimensional data +drawn from a multivariate normal distribution with the following mean and covariance matrix: +$$ +\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\ +2 & 2 +\end{bmatrix} +$$ + +Note that the mean refers to each column of data. +We will generate \( n = 1000 \) points \( X = \{ x_1, \ldots, x_N \} \) from +this distribution, and store them in the \( 1000 \times 2 \) matrix \( \boldsymbol{X} \). + +

+The following Python code aids in setting up the data and writing out the design matrix. +Note that the function multivariate returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \). +

+ + +

import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from IPython.display import display
+n = 10000
+mean = (-1, 2)
+cov = [[4, 2], [2, 2]]
+X = np.random.multivariate_normal(mean, cov, n)
+
+

+Now we are going to implement the PCA algorithm. We will break it down into various substeps. + +

Compute the sample mean and center the data

+ +

+The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is +$$ +\mu_n = \frac{1}{n} \sum_{i=1}^n x_i +$$ + +and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form +$$ +\bar{x}_i = x_i - \mu_n. +$$ + +When you are done with these steps, print out \( \mu_n \) to verify it is +close to \( \mu \) and plot your mean centered data to verify it is +centered at the origin! Compare your code with the functionality from Scikit-Learn discussed above. +The following code elements perform these operations using pandas or using our own functionality for doing so. The latter, using numpy is rather simple through the mean() function. +

+ + +

df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+
+

+Alternatively, we could use the functions we discussed +earlier for scaling the data set. That is, we could have used the +StandardScaler function in Scikit-Learn, a function which ensures +that for each feature/predictor we study the mean value is zero and +the variance is one (every column in the design/feature matrix). You +would then not get the same results, since we divide by the +variance. The diagonal covariance matrix elements will then be one, +while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our +specific case. + +

Compute the sample covariance

+ +

+Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation +$$ +\begin{equation*} +\Sigma_n = \frac{1}{n-1} \sum_{i=1}^n \bar{x}_i^T \bar{x}_i = \frac{1}{n-1} \sum_{i=1}^n (x_i - \mu_n)^T (x_i - \mu_n) +\end{equation*} +$$ + +where the data points \( x_i \in \mathbb{R}^p \) (here in this example \( p = 2 \)) are column vectors and \( x^T \) is the transpose of \( x \). +We can write our own code or simply use either the functionaly of numpy or that of pandas, as follows +

+ + +

print(df.cov())
+print(np.cov(X_centered.T))
+
+

+Note that the way we define the covariance matrix here has a factor \( n-1 \) instead of \( n \). This is included in the cov() function by numpy and pandas. +Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix. +

+ + +

# extract the relevant columns from the centered design matrix of dim n x 2
+x = X_centered[:,0]
+y = X_centered[:,1]
+Cov = np.zeros((2,2))
+Cov[0,1] = np.sum(x.T@y)/(n-1.0)
+Cov[0,0] = np.sum(x.T@x)/(n-1.0)
+Cov[1,1] = np.sum(y.T@y)/(n-1.0)
+Cov[1,0]= Cov[0,1]
+print("Centered covariance using own code")
+print(Cov)
+plt.plot(x, y, 'x')
+plt.axis('equal')
+plt.show()
+
+

+Depending on the number of points \( n \), we will get results that are close to the covariance values defined above. +The plot shows how the data are clustered around a line with slope close to one. Is this expected? + +

Diagonalize the sample covariance matrix to obtain the principal components

+ +

+Now we are ready to solve for the principal components! To do so we +diagonalize the sample covariance matrix \( \Sigma \). We can use the +function np.linalg.eig to do so. It will return the eigenvalues and +eigenvectors of \( \Sigma \). Once we have these we can perform the +following tasks: + +

    +
  • We compute the percentage of the total variance captured by the first principal component
  • +
  • We plot the mean centered data and lines along the first and second principal components
  • +
  • Then we project the mean centered data onto the first and second principal components, and plot the projected data.
  • +
  • Finally, we approximate the data as
  • +
+ +$$ +\begin{equation*} +x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0 +\end{equation*} +$$ + +where \( v_0 \) is the first principal component. + +

+Collecting all these steps we can write our own PCA function and +compare this with the functionality included in Scikit-Learn. + +

+The code here outlines some of the elements we could include in the +analysis. Feel free to extend upon this in order to address the above +questions. + +

+ + +

# diagonalize and obtain eigenvalues, not necessarily sorted
+EigValues, EigVectors = np.linalg.eig(Cov)
+# sort eigenvectors and eigenvalues
+#permute = EigValues.argsort()
+#EigValues = EigValues[permute]
+#EigVectors = EigVectors[:,permute]
+print("Eigenvalues of Covariance matrix")
+for i in range(2):
+    print(EigValues[i])
+FirstEigvector = EigVectors[:,0]
+SecondEigvector = EigVectors[:,1]
+print("First eigenvector")
+print(FirstEigvector)
+print("Second eigenvector")
+print(SecondEigvector)
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2Dsl = pca.fit_transform(X)
+print("Eigenvector of largest eigenvalue")
+print(pca.components_.T[:, 0])
+
+

+This code does not contain all the above elements, but it shows how we can use Scikit-Learn to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? + +

+









+ +

Classical PCA Theorem

+ +

+We assume now that we have a design matrix \( \boldsymbol{X} \) which has been +centered as discussed above. For the sake of simplicity we skip the +overline symbol. The matrix is defined in terms of the various column +vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension +\( \boldsymbol{x}\in {\mathbb{R}}^{n} \). + +

+We assume also that we have an orthogonal transformation \( \boldsymbol{W}\in {\mathbb{R}}^{p\times p} \). We define the reconstruction error (which is similar to the mean squared error we have seen before) as +$$ +J(\boldsymbol{W},\boldsymbol{Z}) = \frac{1}{n}\sum_i (\boldsymbol{x}_i - \overline{\boldsymbol{x}}_i)^2, +$$ + +with \( \overline{\boldsymbol{x}}_i = \boldsymbol{W}\boldsymbol{z}_i \), where \( \boldsymbol{z}_i \) is a row vector with dimension \( {\mathbb{R}}^{n} \) of the matrix +\( \boldsymbol{Z}\in{\mathbb{R}}^{p\times n} \). When doing PCA we want to reduce this dimensionality. + +

+The PCA theorem states that minimizing the above reconstruction error +corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which +diagonalizes the empirical covariance(correlation) matrix. The optimal +low-dimensional encoding of the data is then given by a set of vectors +\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the +orthogonal projection of the data onto the columns spanned by the +eigenvectors of the covariance(correlations matrix). + +

+The proof which follows will be updated by mid January 2020. + +

+









+ +

Proof of the PCA Theorem

+ +

+To show the PCA theorem let us start with the assumption that there is one vector \( \boldsymbol{w}_0 \) which corresponds to a solution which minimized the reconstruction error \( J \). This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of \( \boldsymbol{w}_0 \) and \( \boldsymbol{z}_0 \) as +$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)= \frac{1}{n}\sum_i (\boldsymbol{x}_i - z_{i0}\boldsymbol{w}_0)^2=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2\boldsymbol{w}_0^T\boldsymbol{w}_0), +$$ + +which we can rewrite due to the orthogonality of \( \boldsymbol{w}_i \) as +$$ +J(\boldsymbol{w}_0,\boldsymbol{z}_0)=\frac{1}{n}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - 2z_{i0}\boldsymbol{w}_0^T\boldsymbol{x}_i+z_{i0}^2). +$$ + +Minimizing \( J \) with respect to the unknown parameters \( z_{0i} \) we obtain that +$$ +z_{i0}=\boldsymbol{w}_0^T\boldsymbol{x}_i, +$$ + +where the vectors on the rhs are known. + +

+









+ +

PCA Proof continued

+ +

+We have now found the unknown parameters \( z_{i0} \). These correspond to the projected coordinates and we can write +$$ +J(\boldsymbol{w}_0)= \frac{1}{p}\sum_i (\boldsymbol{x}_i^T\boldsymbol{x}_i - z_{i0}^2)=\mathrm{const}-\frac{1}{n}\sum_i z_{i0}^2. +$$ + +

+We can show that the variance of the projected coordinates defined by \( \boldsymbol{w}_0^T\boldsymbol{x}_i \) are given by +$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2, +$$ + +since the expectation value of +$$ +\mathbb{E}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \mathbb{E}[z_{i0}]= \boldsymbol{w}_0^T\mathbb{E}[\boldsymbol{x}_i]=0, +$$ + +where we have used the fact that our data are centered. + +

+Recalling our definition of the covariance as +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}\boldsymbol{X}^T=\mathbb{E}[\boldsymbol{X}\boldsymbol{X}^T], +$$ + +we have thus that +$$ +\mathrm{var}[\boldsymbol{w}_0^T\boldsymbol{x}_i] = \frac{1}{n}\sum_i z_{i0}^2=\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0. +$$ + +

+We are almost there, we have obtained a relation between minimizing +the reconstruction error and the variance and the covariance +matrix. Minimizing the error is equivalent to maximizing the variance +of the projected data. + +

+









+ +

The final step

+ +

+We could trivially maximize the variance of the projection (and +thereby minimize the error in the reconstruction function) by letting +the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we +want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by +\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a +Lagrange multiplier we can then in turn maximize + +$$ +J(\boldsymbol{w}_0)= \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0+\lambda_0(1-\boldsymbol{w}_0^T\boldsymbol{w}_0). +$$ + +Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain + +$$ +\frac{\partial J(\boldsymbol{w}_0)}{\partial \boldsymbol{w}_0}= 2\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0-2\lambda_0\boldsymbol{w}_0=0, +$$ + +meaning that +$$ +\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0. +$$ + +The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix! If we left multiply with \( \boldsymbol{w}_0^T \) we have the variance of the projected data is +$$ +\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0. +$$ + +

+If we want to maximize the variance (minimize the construction error) +we simply pick the eigenvector of the covariance matrix with the +largest eigenvalue. This establishes the link between the minimization +of the reconstruction function \( J \) in terms of an orthogonal matrix +and the maximization of the variance and thereby the covariance of our +observations encoded in the design/feature matrix \( \boldsymbol{X} \). + +

+The proof +for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be +established by applying the above arguments and using the fact that +our basis of eigenvectors is orthogonal, see Murphy chapter +12.2. The +discussion in chapter 12.2 of Murphy's text has also a nice link with +the Singular Value Decomposition theorem. For categorical data, see +chapter 12.4 and discussion therein. + +

+Additional part of the proof for the other eigenvectors will be added by mid January 2020. + +

+









+ +

Geometric Interpretation and link with Singular Value Decomposition

+ +

+This material will be added by mid January 2020. + +

+









+ +

Principal Component Analysis

+ +

+Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm. +First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it. + +

+The following Python code uses NumPy’s svd() function to obtain all the principal components of the +training set, then extracts the first two principal components. First we center the data using either pandas or our own code +

+ + +

import numpy as np
+import pandas as pd
+from IPython.display import display
+np.random.seed(100)
+# setting up a 10 x 5 vanilla matrix 
+rows = 10
+cols = 5
+X = np.random.randn(rows,cols)
+df = pd.DataFrame(X)
+# Pandas does the centering for us
+df = df -df.mean()
+display(df)
+
+# we center it ourselves
+X_centered = X - X.mean(axis=0)
+# Then check the difference between pandas and our own set up
+print(X_centered-df)
+#Now we do an SVD
+U, s, V = np.linalg.svd(X_centered)
+c1 = V.T[:, 0]
+c2 = V.T[:, 1]
+W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+print(X2D)
+
+

+PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering +the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t +forget to center the data first. + +

+Once you have identified all the principal components, you can reduce the dimensionality of the dataset +down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components. +Selecting this hyperplane ensures that the projection will preserve as much variance as possible. +

+ + +

W2 = V.T[:, :2]
+X2D = X_centered.dot(W2)
+
+

+ + +

PCA and scikit-learn

+ +

+Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The +following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note +that it automatically takes care of centering the data): +

+ + +

#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D = pca.fit_transform(X)
+print(X2D)
+
+

+After fitting the PCA transformer to the dataset, you can access the principal components using the +components variable (note that it contains the PCs as horizontal vectors, so, for example, the first +principal component is equal to +

+ + +

pca.components_.T[:, 0].
+
+

+Another very useful piece of information is the explained variance ratio of each principal component, +available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s +variance that lies along the axis of each principal component. + +

+









+ +

Back to the Cancer Data

+We can now repeat the above but applied to real data, in this case our breast cancer data. +Here we compute performance scores on the training data using logistic regression. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.linear_model import LogisticRegression
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+
+logreg = LogisticRegression()
+logreg.fit(X_train, y_train)
+print("Train set accuracy from Logistic Regression: {:.2f}".format(logreg.score(X_train,y_train)))
+# We scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Then perform again a log reg fit
+logreg.fit(X_train_scaled, y_train)
+print("Train set accuracy scaled data: {:.2f}".format(logreg.score(X_train_scaled,y_train)))
+#thereafter we do a PCA with Scikit-learn
+from sklearn.decomposition import PCA
+pca = PCA(n_components = 2)
+X2D_train = pca.fit_transform(X_train_scaled)
+# and finally compute the log reg fit and the score on the training data	
+logreg.fit(X2D_train,y_train)
+print("Train set accuracy scaled and PCA data: {:.2f}".format(logreg.score(X2D_train,y_train)))
+
+

+We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. + +

+









+ +

More on the PCA

+ +

+Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to +choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%). +Unless, of course, you are reducing dimensionality for data visualization — in that case you will +generally want to reduce the dimensionality down to 2 or 3. +The following code computes PCA without reducing dimensionality, then computes the minimum number +of dimensions required to preserve 95% of the training set’s variance: +

+ + +

pca = PCA()
+pca.fit(X)
+cumsum = np.cumsum(pca.explained_variance_ratio_)
+d = np.argmax(cumsum >= 0.95) + 1
+
+

+You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead +of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be +a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve: +

+ + +

pca = PCA(n_components=0.95)
+X_reduced = pca.fit_transform(X)
+
+

+









+ +

Incremental PCA

+ +

+One problem with the preceding implementation of PCA is that it requires the whole training set to fit in +memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have +been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch +at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new +instances arrive). + +

+









+ +

Randomized PCA

+ +

+Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic +algorithm that quickly finds an approximation of the first d principal components. Its computational +complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the +previous algorithms when \( d \) is much smaller than \( n \). + +

+









+ +

Kernel PCA

+
+ +

+ +

+The kernel trick is a mathematical technique that implicitly maps instances into a +very high-dimensional space (called the feature space), enabling nonlinear classification and regression +with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature +space corresponds to a complex nonlinear decision boundary in the original space. +It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear +projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at +preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a +twisted manifold. +For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an +

+ + +

from sklearn.decomposition import KernelPCA
+rbf_pca = KernelPCA(n_components = 2, kernel="rbf", gamma=0.04)
+X_reduced = rbf_pca.fit_transform(X)
+
+ +
+ + +

+









+ +

LLE

+ +

+Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction +(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous +algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its +closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where +these local relationships are best preserved (more details shortly). + +

+









+ +

Other techniques

+ +

+There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn. + +

+Here are some of the most popular: + +

    +
  • Multidimensional Scaling (MDS) reduces dimensionality while trying to preserve the distances between the instances.
  • +
  • Isomap creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.
  • +
  • t-Distributed Stochastic Neighbor Embedding (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).
  • +
  • Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.
  • +
+ + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz new file mode 100644 index 000000000..13c88c0a1 Binary files /dev/null and b/doc/pub/week43/ipynb/ipynb-week43-src.tar.gz differ diff --git a/doc/pub/week43/ipynb/week43.ipynb b/doc/pub/week43/ipynb/week43.ipynb new file mode 100644 index 000000000..3f627f4af --- /dev/null +++ b/doc/pub/week43/ipynb/week43.ipynb @@ -0,0 +1,1638 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Week 43: Dimensionality Reduction\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "\n", + "## Why should we think of reducing the dimensionality\n", + "\n", + "In addition to the plot of the features, we study now also the covariance (and the correlation matrix).\n", + "We use also **Pandas** to compute the correlation matrix." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.linear_model import LogisticRegression\n", + "cancer = load_breast_cancer()\n", + "import pandas as pd\n", + "# Making a data frame\n", + "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n", + "\n", + "fig, axes = plt.subplots(15,2,figsize=(10,20))\n", + "malignant = cancer.data[cancer.target == 0]\n", + "benign = cancer.data[cancer.target == 1]\n", + "ax = axes.ravel()\n", + "\n", + "for i in range(30):\n", + " _, bins = np.histogram(cancer.data[:,i], bins =50)\n", + " ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)\n", + " ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)\n", + " ax[i].set_title(cancer.feature_names[i])\n", + " ax[i].set_yticks(())\n", + "ax[0].set_xlabel(\"Feature magnitude\")\n", + "ax[0].set_ylabel(\"Frequency\")\n", + "ax[0].legend([\"Malignant\", \"Benign\"], loc =\"best\")\n", + "fig.tight_layout()\n", + "plt.show()\n", + "\n", + "import seaborn as sns\n", + "correlation_matrix = cancerpd.corr().round(1)\n", + "# use the heatmap function from seaborn to plot the correlation matrix\n", + "# annot = True to print the values inside the square\n", + "sns.heatmap(data=correlation_matrix, annot=True)\n", + "plt.show()\n", + "\n", + "#print eigvalues of correlation matrix\n", + "EigValues, EigVectors = np.linalg.eig(correlation_matrix)\n", + "print(EigValues)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the above example we note two things. In the first plot we display\n", + "the overlap of benign and malignant tumors as functions of the various\n", + "features in the Wisconsing breast cancer data set. We see that for\n", + "some of the features we can distinguish clearly the benign and\n", + "malignant cases while for other features we cannot. This can point to\n", + "us which features may be of greater interest when we wish to classify\n", + "a benign or not benign tumour.\n", + "\n", + "In the second figure we have computed the so-called correlation\n", + "matrix, which in our case with thirty features becomes a $30\\times 30$\n", + "matrix.\n", + "\n", + "We constructed this matrix using **pandas** via the statements" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and then" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "correlation_matrix = cancerpd.corr().round(1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Diagonalizing this matrix we can in turn say something about which\n", + "features are of relevance and which are not. But before we proceed we\n", + "need to define covariance and correlation matrices. This leads us to\n", + "the classical Principal Component Analysis (PCA) theorem with\n", + "applications.\n", + "\n", + "\n", + "\n", + "## Basic ideas of the Principal Component Analysis (PCA)\n", + "\n", + "The principal component analysis deals with the problem of fitting a\n", + "low-dimensional affine subspace $S$ of dimension $d$ much smaller than\n", + "the totaldimension $D$ of the problem at hand (our data\n", + "set). Mathematically it can be formulated as a statistical problem or\n", + "a geometric problem. In our discussion of the theorem for the\n", + "classical PCA, we will stay with a statistical approach. This is also\n", + "what set the scene historically which for the PCA.\n", + "\n", + "We have a data set defined by a design/feature matrix $\\boldsymbol{X}$ (see below for its definition) \n", + "* Each data point is determined by $p$ extrinsic (measurement) variables\n", + "\n", + "* We may want to ask the following question: Are there fewer intrinsic variables (say $d << p$) that still approximately describe the data?\n", + "\n", + "* If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do. \n", + "\n", + "## Introducing the Covariance and Correlation functions\n", + "\n", + "Before we discuss the PCA theorem, we need to remind ourselves about\n", + "the definition of the covariance and the correlation function. These are quantities \n", + "\n", + "Suppose we have defined two vectors\n", + "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", + " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n", + " \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where for example" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With this definition and recalling that the variance is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "we can rewrite the covariance matrix as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", + " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n", + " \\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The covariance takes values between zero and infinity and may thus\n", + "lead to problems with loss of numerical precision for particularly\n", + "large values. It is common to scale the covariance matrix by\n", + "introducing instead the correlation matrix defined via the so-called\n", + "correlation function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n", + "\\in [-1,1]$. This avoids eventual problems with too large values. We\n", + "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n", + "and $\\boldsymbol{y}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", + " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n", + " \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the above example this is the function we constructed using **pandas**.\n", + "\n", + "## Correlation Function and Design/Feature Matrix\n", + "\n", + "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n", + "we defined the design/feature matrix $\\boldsymbol{X}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}=\\begin{bmatrix}\n", + "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", + "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", + "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", + "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", + "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", + "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", + "\\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n", + "entries $n$ being the row elements.\n", + "We can rewrite the design/feature matrix in terms of its column vectors as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with a given vector" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With these definitions, we can now rewrite our $2\\times 2$\n", + "correaltion/covariance matrix in terms of a moe general design/feature\n", + "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n", + "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n", + "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", + "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", + "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n", + "\\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the correlation matrix" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n", + "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", + "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", + "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n", + "\\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Covariance Matrix Examples\n", + "\n", + "\n", + "The Numpy function **np.cov** calculates the covariance elements using\n", + "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n", + "the exact mean values. The following simple function uses the\n", + "**np.vstack** function which takes each vector of dimension $1\\times n$\n", + "and produces a $2\\times n$ matrix $\\boldsymbol{W}$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{W} = \\begin{bmatrix} x_0 & y_0 \\\\\n", + " x_1 & y_1 \\\\\n", + " x_2 & y_2\\\\\n", + " \\dots & \\dots \\\\\n", + " x_{n-2} & y_{n-2}\\\\\n", + " x_{n-1} & y_{n-1} & \n", + " \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which in turn is converted into into the $2\\times 2$ covariance matrix\n", + "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", + "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n", + "function **np.mean(x)**. We can also extract the eigenvalues of the\n", + "covariance matrix through the **np.linalg.eig()** function." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "import numpy as np\n", + "n = 100\n", + "x = np.random.normal(size=n)\n", + "print(np.mean(x))\n", + "y = 4+3*x+np.random.normal(size=n)\n", + "print(np.mean(y))\n", + "W = np.vstack((x, y))\n", + "C = np.cov(W)\n", + "print(C)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Correlation Matrix\n", + "\n", + "The previous example can be converted into the correlation matrix by\n", + "simply scaling the matrix elements with the variances. We should also\n", + "subtract the mean values for each column. This leads to the following\n", + "code which sets up the correlations matrix for the previous example in\n", + "a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "n = 100\n", + "# define two vectors \n", + "x = np.random.random(size=n)\n", + "y = 4+3*x+np.random.normal(size=n)\n", + "#scaling the x and y vectors \n", + "x = x - np.mean(x)\n", + "y = y - np.mean(y)\n", + "variance_x = np.sum(x@x)/n\n", + "variance_y = np.sum(y@y)/n\n", + "print(variance_x)\n", + "print(variance_y)\n", + "cov_xy = np.sum(x@y)/n\n", + "cov_xx = np.sum(x@x)/n\n", + "cov_yy = np.sum(y@y)/n\n", + "C = np.zeros((2,2))\n", + "C[0,0]= cov_xx/variance_x\n", + "C[1,1]= cov_yy/variance_y\n", + "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n", + "C[1,0]= C[0,1]\n", + "print(C)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We see that the matrix elements along the diagonal are one as they\n", + "should be and that the matrix is symmetric. Furthermore, diagonalizing\n", + "this matrix we easily see that it is a positive definite matrix.\n", + "\n", + "The above procedure with **numpy** can be made more compact if we use **pandas**.\n", + "\n", + "## Correlation Matrix with Pandas\n", + "\n", + "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "n = 10\n", + "x = np.random.normal(size=n)\n", + "x = x - np.mean(x)\n", + "y = 4+3*x+np.random.normal(size=n)\n", + "y = y - np.mean(y)\n", + "X = (np.vstack((x, y))).T\n", + "print(X)\n", + "Xpd = pd.DataFrame(X)\n", + "print(Xpd)\n", + "correlation_matrix = Xpd.corr()\n", + "print(correlation_matrix)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We expand this model to the Franke function discussed above.\n", + "\n", + "## Correlation Matrix with Pandas and the Franke function" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Common imports\n", + "import numpy as np\n", + "import pandas as pd\n", + "\n", + "\n", + "def FrankeFunction(x,y):\n", + "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", + "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", + "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", + "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", + "\treturn term1 + term2 + term3 + term4\n", + "\n", + "\n", + "def create_X(x, y, n ):\n", + "\tif len(x.shape) > 1:\n", + "\t\tx = np.ravel(x)\n", + "\t\ty = np.ravel(y)\n", + "\n", + "\tN = len(x)\n", + "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", + "\tX = np.ones((N,l))\n", + "\n", + "\tfor i in range(1,n+1):\n", + "\t\tq = int((i)*(i+1)/2)\n", + "\t\tfor k in range(i+1):\n", + "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", + "\n", + "\treturn X\n", + "\n", + "\n", + "# Making meshgrid of datapoints and compute Franke's function\n", + "n = 4\n", + "N = 100\n", + "x = np.sort(np.random.uniform(0, 1, N))\n", + "y = np.sort(np.random.uniform(0, 1, N))\n", + "z = FrankeFunction(x, y)\n", + "X = create_X(x, y, n=n) \n", + "\n", + "Xpd = pd.DataFrame(X)\n", + "# subtract the mean values and set up the covariance matrix\n", + "Xpd = Xpd - Xpd.mean()\n", + "covariance_matrix = Xpd.cov()\n", + "print(covariance_matrix)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We note here that the covariance is zero for the first rows and\n", + "columns since all matrix elements in the design matrix were set to one\n", + "(we are fitting the function in terms of a polynomial of degree $n$).\n", + "\n", + "This means that the variance for these elements will be zero and will\n", + "cause problems when we set up the correlation matrix. We can simply\n", + "drop these elements and construct a correlation\n", + "matrix without these elements. \n", + "\n", + "\n", + "## Rewriting the Covariance and/or Correlation Matrix\n", + "\n", + "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T= \\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T].\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}=\\begin{bmatrix}\n", + "x_{00} & x_{01}\\\\\n", + "x_{10} & x_{11}\\\\\n", + "\\end{bmatrix}=\\begin{bmatrix}\n", + "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n", + "\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we then compute the expectation value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T=\\begin{bmatrix}\n", + "x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\\\\n", + "x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\\\\n", + "\\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which is just" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n", + " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n", + " \\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n", + "\n", + "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$.\n", + "\n", + "\n", + "## Towards the PCA theorem\n", + "\n", + "We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T= \\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T].\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices $\\boldsymbol{S}$.\n", + "These matrices are defined as $\\boldsymbol{S}\\in {\\mathbb{R}}^{p\\times p}$ and obey the orthogonality requirements $\\boldsymbol{S}\\boldsymbol{S}^T=\\boldsymbol{S}^T\\boldsymbol{S}=\\boldsymbol{I}$. The matrix can be written out in terms of the column vectors $\\boldsymbol{s}_i$ as $\\boldsymbol{S}=[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$ and $\\boldsymbol{s}_i \\in {\\mathbb{R}}^{p}$.\n", + "\n", + "Assume also that there is a transformation $\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T=\\boldsymbol{C}[\\boldsymbol{y}]$ such that the new matrix $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal with elements $[\\lambda_0,\\lambda_1,\\lambda_2,\\dots,\\lambda_{p-1}]$. \n", + "\n", + "That is we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{y}] = \\mathbb{E}[\\boldsymbol{S}\\boldsymbol{X}\\boldsymbol{X}^T\\boldsymbol{S}^T]=\\boldsymbol{S}\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "since the matrix $\\boldsymbol{S}$ is not a data dependent matrix. Multiplying with $\\boldsymbol{S}^T$ from the left we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{S}^T\\boldsymbol{C}[\\boldsymbol{y}] = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and since $\\boldsymbol{C}[\\boldsymbol{y}]$ is diagonal we have for a given eigenvalue $i$ of the covariance matrix that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{S}^T_i\\lambda_i = \\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{S}^T_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is\n", + "$\\lambda_0 > \\lambda_1 > \\dots > \\lambda_{p-1}$. \n", + "\n", + "\n", + "The eigenvalues tell us then how much we need to stretch the\n", + "corresponding eigenvectors. Dimensions with large eigenvalues have\n", + "thus large variations (large variance) and define therefore useful\n", + "dimensions. The data points are more spread out in the direction of\n", + "these eigenvectors. Smaller eigenvalues mean on the other hand that\n", + "the corresponding eigenvectors are shrunk accordingly and the data\n", + "points are tightly bunched together and there is not much variation in\n", + "these specific directions. Hopefully then we could leave it out\n", + "dimensions where the eigenvalues are very small. If $p$ is very large,\n", + "we could then aim at reducing $p$ to $l << p$ and handle only $l$\n", + "features/predictors.\n", + "\n", + "## The Algorithm before theorem\n", + "\n", + "Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here. \n", + "* Set up the datapoints for the design/feature matrix $\\boldsymbol{X}$ with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ referring to the column numbers and the entries $n$ being the row elements." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}=\\begin{bmatrix}\n", + "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", + "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", + "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", + "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", + "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", + "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", + "\\end{bmatrix},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Center the data by subtracting the mean value for each column. This leads to a new matrix $\\boldsymbol{X}\\rightarrow \\overline{\\boldsymbol{X}}$.\n", + "\n", + "* Compute then the covariance/correlation matrix $\\mathbb{E}[\\overline{\\boldsymbol{X}}\\overline{\\boldsymbol{X}}^T]$.\n", + "\n", + "* Find the eigenpairs of $\\boldsymbol{C}$ with eigenvalues $[\\lambda_0,\\lambda_1,\\dots,\\lambda_{p-1}]$ and eigenvectors $[\\boldsymbol{s}_0,\\boldsymbol{s}_1,\\dots,\\boldsymbol{s}_{p-1}]$.\n", + "\n", + "* Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.\n", + "\n", + "* Keep only those $l$ eigenvalues larger than a selected threshold value, discarding thus $p-l$ features since we expect small variations in the data here.\n", + "\n", + "## Writing our own PCA code\n", + "\n", + "We will use a simple example first with two-dimensional data\n", + "drawn from a multivariate normal distribution with the following mean and covariance matrix:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mu = (-1,2) \\qquad \\Sigma = \\begin{bmatrix} 4 & 2 \\\\\n", + "2 & 2\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the mean refers to each column of data. \n", + "We will generate $n = 1000$ points $X = \\{ x_1, \\ldots, x_N \\}$ from\n", + "this distribution, and store them in the $1000 \\times 2$ matrix $\\boldsymbol{X}$.\n", + "\n", + "The following Python code aids in setting up the data and writing out the design matrix.\n", + "Note that the function **multivariate** returns also the covariance discussed above and that it is defined by dividing by $n-1$ instead of $n$." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from IPython.display import display\n", + "n = 10000\n", + "mean = (-1, 2)\n", + "cov = [[4, 2], [2, 2]]\n", + "X = np.random.multivariate_normal(mean, cov, n)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we are going to implement the PCA algorithm. We will break it down into various substeps.\n", + "\n", + "### Compute the sample mean and center the data\n", + "\n", + "The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mu_n = \\frac{1}{n} \\sum_{i=1}^n x_i\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the mean-centered data $\\bar{X} = \\{ \\bar{x}_1, \\ldots, \\bar{x}_n \\}$ takes the form" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{x}_i = x_i - \\mu_n.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When you are done with these steps, print out $\\mu_n$ to verify it is\n", + "close to $\\mu$ and plot your mean centered data to verify it is\n", + "centered at the origin! Compare your code with the functionality from **Scikit-Learn** discussed above.\n", + "The following code elements perform these operations using **pandas** or using our own functionality for doing so. The latter, using **numpy** is rather simple through the **mean()** function." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df = pd.DataFrame(X)\n", + "# Pandas does the centering for us\n", + "df = df -df.mean()\n", + "# we center it ourselves\n", + "X_centered = X - X.mean(axis=0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Alternatively, we could use the functions we discussed\n", + "earlier for scaling the data set. That is, we could have used the\n", + "**StandardScaler** function in **Scikit-Learn**, a function which ensures\n", + "that for each feature/predictor we study the mean value is zero and\n", + "the variance is one (every column in the design/feature matrix). You\n", + "would then not get the same results, since we divide by the\n", + "variance. The diagonal covariance matrix elements will then be one,\n", + "while the non-diagonal ones need to be divided by $2\\sqrt{2}$ for our\n", + "specific case.\n", + "\n", + "### Compute the sample covariance\n", + "\n", + "Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\Sigma_n = \\frac{1}{n-1} \\sum_{i=1}^n \\bar{x}_i^T \\bar{x}_i = \\frac{1}{n-1} \\sum_{i=1}^n (x_i - \\mu_n)^T (x_i - \\mu_n)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the data points $x_i \\in \\mathbb{R}^p$ (here in this example $p = 2$) are column vectors and $x^T$ is the transpose of $x$.\n", + "We can write our own code or simply use either the functionaly of **numpy** or that of **pandas**, as follows" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "print(df.cov())\n", + "print(np.cov(X_centered.T))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the way we define the covariance matrix here has a factor $n-1$ instead of $n$. This is included in the **cov()** function by **numpy** and **pandas**. \n", + "Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific $2\\times 2$ covariance matrix." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# extract the relevant columns from the centered design matrix of dim n x 2\n", + "x = X_centered[:,0]\n", + "y = X_centered[:,1]\n", + "Cov = np.zeros((2,2))\n", + "Cov[0,1] = np.sum(x.T@y)/(n-1.0)\n", + "Cov[0,0] = np.sum(x.T@x)/(n-1.0)\n", + "Cov[1,1] = np.sum(y.T@y)/(n-1.0)\n", + "Cov[1,0]= Cov[0,1]\n", + "print(\"Centered covariance using own code\")\n", + "print(Cov)\n", + "plt.plot(x, y, 'x')\n", + "plt.axis('equal')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Depending on the number of points $n$, we will get results that are close to the covariance values defined above.\n", + "The plot shows how the data are clustered around a line with slope close to one. Is this expected?\n", + "\n", + "### Diagonalize the sample covariance matrix to obtain the principal components\n", + "\n", + "Now we are ready to solve for the principal components! To do so we\n", + "diagonalize the sample covariance matrix $\\Sigma$. We can use the\n", + "function **np.linalg.eig** to do so. It will return the eigenvalues and\n", + "eigenvectors of $\\Sigma$. Once we have these we can perform the \n", + "following tasks:\n", + "\n", + "* We compute the percentage of the total variance captured by the first principal component\n", + "\n", + "* We plot the mean centered data and lines along the first and second principal components\n", + "\n", + "* Then we project the mean centered data onto the first and second principal components, and plot the projected data. \n", + "\n", + "* Finally, we approximate the data as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "x_i \\approx \\tilde{x}_i = \\mu_n + \\langle x_i, v_0 \\rangle v_0\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $v_0$ is the first principal component. \n", + "\n", + "Collecting all these steps we can write our own PCA function and\n", + "compare this with the functionality included in **Scikit-Learn**. \n", + "\n", + "The code here outlines some of the elements we could include in the\n", + "analysis. Feel free to extend upon this in order to address the above\n", + "questions." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# diagonalize and obtain eigenvalues, not necessarily sorted\n", + "EigValues, EigVectors = np.linalg.eig(Cov)\n", + "# sort eigenvectors and eigenvalues\n", + "#permute = EigValues.argsort()\n", + "#EigValues = EigValues[permute]\n", + "#EigVectors = EigVectors[:,permute]\n", + "print(\"Eigenvalues of Covariance matrix\")\n", + "for i in range(2):\n", + " print(EigValues[i])\n", + "FirstEigvector = EigVectors[:,0]\n", + "SecondEigvector = EigVectors[:,1]\n", + "print(\"First eigenvector\")\n", + "print(FirstEigvector)\n", + "print(\"Second eigenvector\")\n", + "print(SecondEigvector)\n", + "#thereafter we do a PCA with Scikit-learn\n", + "from sklearn.decomposition import PCA\n", + "pca = PCA(n_components = 2)\n", + "X2Dsl = pca.fit_transform(X)\n", + "print(\"Eigenvector of largest eigenvalue\")\n", + "print(pca.components_.T[:, 0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This code does not contain all the above elements, but it shows how we can use **Scikit-Learn** to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then? \n", + "\n", + "## Classical PCA Theorem\n", + "\n", + "We assume now that we have a design matrix $\\boldsymbol{X}$ which has been\n", + "centered as discussed above. For the sake of simplicity we skip the\n", + "overline symbol. The matrix is defined in terms of the various column\n", + "vectors $[\\boldsymbol{x}_0,\\boldsymbol{x}_1,\\dots, \\boldsymbol{x}_{p-1}]$ each with dimension\n", + "$\\boldsymbol{x}\\in {\\mathbb{R}}^{n}$.\n", + "\n", + "We assume also that we have an orthogonal transformation $\\boldsymbol{W}\\in {\\mathbb{R}}^{p\\times p}$. We define the reconstruction error (which is similar to the mean squared error we have seen before) as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "J(\\boldsymbol{W},\\boldsymbol{Z}) = \\frac{1}{n}\\sum_i (\\boldsymbol{x}_i - \\overline{\\boldsymbol{x}}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $\\overline{\\boldsymbol{x}}_i = \\boldsymbol{W}\\boldsymbol{z}_i$, where $\\boldsymbol{z}_i$ is a row vector with dimension ${\\mathbb{R}}^{n}$ of the matrix\n", + "$\\boldsymbol{Z}\\in{\\mathbb{R}}^{p\\times n}$. When doing PCA we want to reduce this dimensionality. \n", + "\n", + "The PCA theorem states that minimizing the above reconstruction error\n", + "corresponds to setting $\\boldsymbol{W}=\\boldsymbol{S}$, the orthogonal matrix which\n", + "diagonalizes the empirical covariance(correlation) matrix. The optimal\n", + "low-dimensional encoding of the data is then given by a set of vectors\n", + "$\\boldsymbol{z}_i$ with at most $l$ vectors, with $l << p$, defined by the\n", + "orthogonal projection of the data onto the columns spanned by the\n", + "eigenvectors of the covariance(correlations matrix).\n", + "\n", + "The proof which follows will be updated by mid January 2020.\n", + "\n", + "## Proof of the PCA Theorem\n", + "\n", + "To show the PCA theorem let us start with the assumption that there is one vector $\\boldsymbol{w}_0$ which corresponds to a solution which minimized the reconstruction error $J$. This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of $\\boldsymbol{w}_0$ and $\\boldsymbol{z}_0$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "J(\\boldsymbol{w}_0,\\boldsymbol{z}_0)= \\frac{1}{n}\\sum_i (\\boldsymbol{x}_i - z_{i0}\\boldsymbol{w}_0)^2=\\frac{1}{n}\\sum_i (\\boldsymbol{x}_i^T\\boldsymbol{x}_i - 2z_{i0}\\boldsymbol{w}_0^T\\boldsymbol{x}_i+z_{i0}^2\\boldsymbol{w}_0^T\\boldsymbol{w}_0),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which we can rewrite due to the orthogonality of $\\boldsymbol{w}_i$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "J(\\boldsymbol{w}_0,\\boldsymbol{z}_0)=\\frac{1}{n}\\sum_i (\\boldsymbol{x}_i^T\\boldsymbol{x}_i - 2z_{i0}\\boldsymbol{w}_0^T\\boldsymbol{x}_i+z_{i0}^2).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Minimizing $J$ with respect to the unknown parameters $z_{0i}$ we obtain that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "z_{i0}=\\boldsymbol{w}_0^T\\boldsymbol{x}_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the vectors on the rhs are known. \n", + "\n", + "\n", + "## PCA Proof continued\n", + "\n", + "We have now found the unknown parameters $z_{i0}$. These correspond to the projected coordinates and we can write" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "J(\\boldsymbol{w}_0)= \\frac{1}{p}\\sum_i (\\boldsymbol{x}_i^T\\boldsymbol{x}_i - z_{i0}^2)=\\mathrm{const}-\\frac{1}{n}\\sum_i z_{i0}^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can show that the variance of the projected coordinates defined by $\\boldsymbol{w}_0^T\\boldsymbol{x}_i$ are given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{var}[\\boldsymbol{w}_0^T\\boldsymbol{x}_i] = \\frac{1}{n}\\sum_i z_{i0}^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "since the expectation value of" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}[\\boldsymbol{w}_0^T\\boldsymbol{x}_i] = \\mathbb{E}[z_{i0}]= \\boldsymbol{w}_0^T\\mathbb{E}[\\boldsymbol{x}_i]=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have used the fact that our data are centered.\n", + "\n", + "Recalling our definition of the covariance as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}\\boldsymbol{X}^T=\\mathbb{E}[\\boldsymbol{X}\\boldsymbol{X}^T],\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "we have thus that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{var}[\\boldsymbol{w}_0^T\\boldsymbol{x}_i] = \\frac{1}{n}\\sum_i z_{i0}^2=\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We are almost there, we have obtained a relation between minimizing\n", + "the reconstruction error and the variance and the covariance\n", + "matrix. Minimizing the error is equivalent to maximizing the variance\n", + "of the projected data.\n", + "\n", + "## The final step\n", + "\n", + "We could trivially maximize the variance of the projection (and\n", + "thereby minimize the error in the reconstruction function) by letting\n", + "the norm-2 of $\\boldsymbol{w}_0$ go to infinity. However, this norm since we\n", + "want the matrix $\\boldsymbol{W}$ to be an orthogonal matrix, is constrained by\n", + "$\\vert\\vert \\boldsymbol{w}_0 \\vert\\vert_2^2=1$. Imposing this condition via a\n", + "Lagrange multiplier we can then in turn maximize" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "J(\\boldsymbol{w}_0)= \\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0+\\lambda_0(1-\\boldsymbol{w}_0^T\\boldsymbol{w}_0).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Taking the derivative with respect to $\\boldsymbol{w}_0$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial J(\\boldsymbol{w}_0)}{\\partial \\boldsymbol{w}_0}= 2\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0-2\\lambda_0\\boldsymbol{w}_0=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "meaning that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0\\boldsymbol{w}_0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix**! If we left multiply with $\\boldsymbol{w}_0^T$ we have the variance of the projected data is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{w}_0^T\\boldsymbol{C}[\\boldsymbol{x}]\\boldsymbol{w}_0=\\lambda_0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we want to maximize the variance (minimize the construction error)\n", + "we simply pick the eigenvector of the covariance matrix with the\n", + "largest eigenvalue. This establishes the link between the minimization\n", + "of the reconstruction function $J$ in terms of an orthogonal matrix\n", + "and the maximization of the variance and thereby the covariance of our\n", + "observations encoded in the design/feature matrix $\\boldsymbol{X}$.\n", + "\n", + "The proof\n", + "for the other eigenvectors $\\boldsymbol{w}_1,\\boldsymbol{w}_2,\\dots$ can be\n", + "established by applying the above arguments and using the fact that\n", + "our basis of eigenvectors is orthogonal, see [Murphy chapter\n", + "12.2](https://mitpress.mit.edu/books/machine-learning-1). The\n", + "discussion in chapter 12.2 of Murphy's text has also a nice link with\n", + "the Singular Value Decomposition theorem. For categorical data, see\n", + "chapter 12.4 and discussion therein.\n", + "\n", + "Additional part of the proof for the other eigenvectors will be added by mid January 2020.\n", + "\n", + "## Geometric Interpretation and link with Singular Value Decomposition\n", + "\n", + "This material will be added by mid January 2020.\n", + "\n", + "\n", + "## Principal Component Analysis\n", + "\n", + "Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.\n", + "First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.\n", + "\n", + "The following Python code uses NumPy’s **svd()** function to obtain all the principal components of the\n", + "training set, then extracts the first two principal components. First we center the data using either **pandas** or our own code" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "from IPython.display import display\n", + "np.random.seed(100)\n", + "# setting up a 10 x 5 vanilla matrix \n", + "rows = 10\n", + "cols = 5\n", + "X = np.random.randn(rows,cols)\n", + "df = pd.DataFrame(X)\n", + "# Pandas does the centering for us\n", + "df = df -df.mean()\n", + "display(df)\n", + "\n", + "# we center it ourselves\n", + "X_centered = X - X.mean(axis=0)\n", + "# Then check the difference between pandas and our own set up\n", + "print(X_centered-df)\n", + "#Now we do an SVD\n", + "U, s, V = np.linalg.svd(X_centered)\n", + "c1 = V.T[:, 0]\n", + "c2 = V.T[:, 1]\n", + "W2 = V.T[:, :2]\n", + "X2D = X_centered.dot(W2)\n", + "print(X2D)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering\n", + "the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t\n", + "forget to center the data first.\n", + "\n", + "Once you have identified all the principal components, you can reduce the dimensionality of the dataset\n", + "down to $d$ dimensions by projecting it onto the hyperplane defined by the first $d$ principal components.\n", + "Selecting this hyperplane ensures that the projection will preserve as much variance as possible." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "W2 = V.T[:, :2]\n", + "X2D = X_centered.dot(W2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "## PCA and scikit-learn\n", + "\n", + "Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The\n", + "following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note\n", + "that it automatically takes care of centering the data):" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "#thereafter we do a PCA with Scikit-learn\n", + "from sklearn.decomposition import PCA\n", + "pca = PCA(n_components = 2)\n", + "X2D = pca.fit_transform(X)\n", + "print(X2D)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "After fitting the PCA transformer to the dataset, you can access the principal components using the\n", + "components variable (note that it contains the PCs as horizontal vectors, so, for example, the first\n", + "principal component is equal to" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pca.components_.T[:, 0]." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another very useful piece of information is the explained variance ratio of each principal component,\n", + "available via the $explained\\_variance\\_ratio$ variable. It indicates the proportion of the dataset’s\n", + "variance that lies along the axis of each principal component. \n", + "\n", + "## Back to the Cancer Data\n", + "We can now repeat the above but applied to real data, in this case our breast cancer data.\n", + "Here we compute performance scores on the training data using logistic regression." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.linear_model import LogisticRegression\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "\n", + "logreg = LogisticRegression()\n", + "logreg.fit(X_train, y_train)\n", + "print(\"Train set accuracy from Logistic Regression: {:.2f}\".format(logreg.score(X_train,y_train)))\n", + "# We scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "# Then perform again a log reg fit\n", + "logreg.fit(X_train_scaled, y_train)\n", + "print(\"Train set accuracy scaled data: {:.2f}\".format(logreg.score(X_train_scaled,y_train)))\n", + "#thereafter we do a PCA with Scikit-learn\n", + "from sklearn.decomposition import PCA\n", + "pca = PCA(n_components = 2)\n", + "X2D_train = pca.fit_transform(X_train_scaled)\n", + "# and finally compute the log reg fit and the score on the training data\t\n", + "logreg.fit(X2D_train,y_train)\n", + "print(\"Train set accuracy scaled and PCA data: {:.2f}\".format(logreg.score(X2D_train,y_train)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We see that our training data after the PCA decomposition has a performance similar to the non-scaled data. \n", + "\n", + "## More on the PCA\n", + "\n", + "Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to\n", + "choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).\n", + "Unless, of course, you are reducing dimensionality for data visualization — in that case you will\n", + "generally want to reduce the dimensionality down to 2 or 3.\n", + "The following code computes PCA without reducing dimensionality, then computes the minimum number\n", + "of dimensions required to preserve 95% of the training set’s variance:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pca = PCA()\n", + "pca.fit(X)\n", + "cumsum = np.cumsum(pca.explained_variance_ratio_)\n", + "d = np.argmax(cumsum >= 0.95) + 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You could then set $n\\_components=d$ and run PCA again. However, there is a much better option: instead\n", + "of specifying the number of principal components you want to preserve, you can set $n\\_components$ to be\n", + "a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pca = PCA(n_components=0.95)\n", + "X_reduced = pca.fit_transform(X)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Incremental PCA\n", + "\n", + "One problem with the preceding implementation of PCA is that it requires the whole training set to fit in\n", + "memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have\n", + "been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch\n", + "at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new\n", + "instances arrive).\n", + "\n", + "## Randomized PCA\n", + "\n", + "Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic\n", + "algorithm that quickly finds an approximation of the first d principal components. Its computational\n", + "complexity is $O(m \\times d^2)+O(d^3)$, instead of $O(m \\times n^2) + O(n^3)$, so it is dramatically faster than the\n", + "previous algorithms when $d$ is much smaller than $n$.\n", + "\n", + "\n", + "\n", + "\n", + "## Kernel PCA\n", + "\n", + "The kernel trick is a mathematical technique that implicitly maps instances into a\n", + "very high-dimensional space (called the feature space), enabling nonlinear classification and regression\n", + "with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature\n", + "space corresponds to a complex nonlinear decision boundary in the original space.\n", + "It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear\n", + "projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at\n", + "preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a\n", + "twisted manifold.\n", + "For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.decomposition import KernelPCA\n", + "rbf_pca = KernelPCA(n_components = 2, kernel=\"rbf\", gamma=0.04)\n", + "X_reduced = rbf_pca.fit_transform(X)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## LLE\n", + "\n", + "Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction\n", + "(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous\n", + "algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its\n", + "closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where\n", + "these local relationships are best preserved (more details shortly). \n", + "\n", + "\n", + "\n", + "## Other techniques\n", + "\n", + "\n", + "There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.\n", + "\n", + "Here are some of the most popular:\n", + "* **Multidimensional Scaling (MDS)** reduces dimensionality while trying to preserve the distances between the instances.\n", + "\n", + "* **Isomap** creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.\n", + "\n", + "* **t-Distributed Stochastic Neighbor Embedding** (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).\n", + "\n", + "* Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures." + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/pub/week44/html/._week44-bs000.html b/doc/pub/week44/html/._week44-bs000.html new file mode 100644 index 000000000..73fecd50a --- /dev/null +++ b/doc/pub/week44/html/._week44-bs000.html @@ -0,0 +1,268 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +

 

 

 

+ + + + + + +
+

week 44: From Decision Trees to Bagging methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs001.html b/doc/pub/week44/html/._week44-bs001.html new file mode 100644 index 000000000..157460043 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs001.html @@ -0,0 +1,281 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Decision trees, overarching aims

+ +

+We start here with the most basic algorithm, the so-called decision +tree. With this basic algorithm we can in turn build more complex +networks, spanning from homogeneous and heterogenous forests (bagging, +random forests and more) to one of the most popular supervised +algorithms nowadays, the extreme gradient boosting, or just +XGBoost. But let us start with the simplest possible ingredient. + +

+Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + +

+The main idea of decision trees +is to find those descriptive features which contain the most +information regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +

+The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the most +informative feature is done until we accomplish a stopping criteria +where we then finally end up in so called leaf nodes. + +

+A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. + +

+The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs002.html b/doc/pub/week44/html/._week44-bs002.html new file mode 100644 index 000000000..69bbcecb1 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs002.html @@ -0,0 +1,251 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A typical Decision Tree with its pertinent Jargon, Classification Problem

+ +

+



+ +

+This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs003.html b/doc/pub/week44/html/._week44-bs003.html new file mode 100644 index 000000000..997e091c8 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs003.html @@ -0,0 +1,259 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

General Features

+ +

+The overarching approach to decision trees is a top-down approach. + +

    +
  • A leaf provides the classification of a given instance.
  • +
  • A node specifies a test of some attribute of the instance.
  • +
  • A branch corresponds to a possible values of an attribute.
  • +
  • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
  • +
+ +This process is then repeated for the subtree rooted at the new +node. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs004.html b/doc/pub/week44/html/._week44-bs004.html new file mode 100644 index 000000000..775878e49 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs004.html @@ -0,0 +1,260 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

How do we set it up?

+ +

+In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +

    +
  1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
  2. +
  3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
  4. +
  5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
  6. +
  7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
  8. +
+ +Then we are essentially done! + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs005.html b/doc/pub/week44/html/._week44-bs005.html new file mode 100644 index 000000000..2bfa524ea --- /dev/null +++ b/doc/pub/week44/html/._week44-bs005.html @@ -0,0 +1,339 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Decision trees and Regression

+

+ + +

import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x<steps:
+    distance+=np.random.randint(-1,2)
+    distance_list.append(distance)
+    x+=1
+    steps_list.append(x)
+plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
+
+steps_list=np.asarray(steps_list)
+distance_list=np.asarray(distance_list)
+
+X=steps_list[:,np.newaxis]
+
+#Polynomial fits
+
+#Degree 2
+poly_features=PolynomialFeatures(degree=2, include_bias=False)
+X_poly=poly_features.fit_transform(X)
+
+lin_reg=LinearRegression()
+poly_fit=lin_reg.fit(X_poly,distance_list)
+b=lin_reg.coef_
+c=lin_reg.intercept_
+print ("2nd degree coefficients:")
+print ("zero power: ",c)
+print ("first power: ", b[0])
+print ("second power: ",b[1])
+
+z = np.arange(0, steps, .01)
+z_mod=b[1]*z**2+b[0]*z+c
+
+fit_mod=b[1]*X**2+b[0]*X+c
+plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
+plt.title("Polynomial Regression")
+
+plt.xlabel("Steps")
+plt.ylabel("Distance")
+
+#Degree 10
+poly_features10=PolynomialFeatures(degree=10, include_bias=False)
+X_poly10=poly_features10.fit_transform(X)
+
+poly_fit10=lin_reg.fit(X_poly10,distance_list)
+
+y_plot=poly_fit10.predict(X_poly10)
+plt.plot(X, y_plot, color='black', label="10th Degree Fit")
+
+plt.legend()
+plt.show()
+
+
+#Decision Tree Regression
+from sklearn.tree import DecisionTreeRegressor
+regr_1=DecisionTreeRegressor(max_depth=2)
+regr_2=DecisionTreeRegressor(max_depth=5)
+regr_3=DecisionTreeRegressor(max_depth=7)
+regr_1.fit(X, distance_list)
+regr_2.fit(X, distance_list)
+regr_3.fit(X, distance_list)
+
+X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
+y_1 = regr_1.predict(X_test)
+y_2 = regr_2.predict(X_test)
+y_3=regr_3.predict(X_test)
+
+# Plot the results
+plt.figure()
+plt.scatter(X, distance_list, s=2.5, c="black", label="data")
+plt.plot(X_test, y_1, color="red",
+         label="max_depth=2", linewidth=2)
+plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
+plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
+
+plt.xlabel("Data")
+plt.ylabel("Darget")
+plt.title("Decision Tree Regression")
+plt.legend()
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs006.html b/doc/pub/week44/html/._week44-bs006.html new file mode 100644 index 000000000..8f3d7657a --- /dev/null +++ b/doc/pub/week44/html/._week44-bs006.html @@ -0,0 +1,272 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Building a tree, regression

+ +

+There are mainly two steps + +

    +
  1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
  2. +
  3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
  4. +
+ +How do we construct the regions \( R_1,\dots,R_J \)? In theory, the +regions could have any shape. However, we choose to divide the +predictor space into high-dimensional rectangles, or boxes, for +simplicity and for ease of interpretation of the resulting predictive +model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the +MSE, given by + +$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ + +

+where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs007.html b/doc/pub/week44/html/._week44-bs007.html new file mode 100644 index 000000000..3d8674b4c --- /dev/null +++ b/doc/pub/week44/html/._week44-bs007.html @@ -0,0 +1,264 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A top-down approach, recursive binary splitting

+ +

+Unfortunately, it is computationally infeasible to consider every +possible partition of the feature space into \( J \) boxes. The common +strategy is to take a top-down approach + +

+The approach is top-down because it begins at the top of the tree (all +observations belong to a single region) and then successively splits +the predictor space; each split is indicated via two new branches +further down on the tree. It is greedy because at each step of the +tree-building process, the best split is made at that particular step, +rather than looking ahead and picking a split that will lead to a +better tree in some future step. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs008.html b/doc/pub/week44/html/._week44-bs008.html new file mode 100644 index 000000000..f871379ab --- /dev/null +++ b/doc/pub/week44/html/._week44-bs008.html @@ -0,0 +1,297 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Making a tree

+ +

+In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +$$ +\left\{X\vert x_j < s\right\}, +$$ + +and +$$ +\left\{X\vert x_j \geq s\right\}, +$$ + +so that we obtain the lowest MSE, that is +$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ + +

+which we want to minimize by considering all predictors +\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for +each predictor. These values could be determined by randomly assigned +numbers or by starting at the midpoint and then proceed till we find +an optimal value. + +

+For any \( j \) and \( s \), we define the pair of half-planes where +\( \overline{y}_{R_1} \) is the mean response for the training +observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean +response for the training observations in \( R_2(j,s) \). + +

+Finding the values of \( j \) and \( s \) that minimize the above equation can be +done quite quickly, especially when the number of features \( p \) is not +too large. + +

+Next, we repeat the process, looking +for the best predictor and best cutpoint in order to split the data +further so as to minimize the MSE within each of the resulting +regions. However, this time, instead of splitting the entire predictor +space, we split one of the two previously identified regions. We now +have three regions. Again, we look to split one of these three regions +further, so as to minimize the MSE. The process continues until a +stopping criterion is reached; for instance, we may continue until no +region contains more than five observations. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs009.html b/doc/pub/week44/html/._week44-bs009.html new file mode 100644 index 000000000..7376658fd --- /dev/null +++ b/doc/pub/week44/html/._week44-bs009.html @@ -0,0 +1,266 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Pruning the tree

+ +

+The above procedure is rather straightforward, but leads often to +overfitting and unnecessarily large and complicated trees. The basic +idea is to grow a large tree \( T_0 \) and then prune it back in order to +obtain a subtree. A smaller tree with fewer splits (fewer regions) can +lead to smaller variance and better interpretation at the cost of a +little more bias. + +

+The so-called Cost complexity pruning algorithm gives us a +way to do just this. Rather than considering every possible subtree, +we consider a sequence of trees indexed by a nonnegative tuning +parameter \( \alpha \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs010.html b/doc/pub/week44/html/._week44-bs010.html new file mode 100644 index 000000000..a17d6e093 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs010.html @@ -0,0 +1,279 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Cost complexity pruning

+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ + +is as small as possible. Here \( \overline{T} \) is +the number of terminal nodes of the tree \( T \) , \( R_m \) is the +rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. + +

+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. + +

+It turns out that as we increase \( \alpha \) from zero +branches get pruned from the tree in a nested and predictable fashion, +so obtaining the whole sequence of subtrees as a function of \( \alpha \) is +easy. We can select a value of \( \alpha \) using a validation set or using +cross-validation. We then return to the full data set and obtain the +subtree corresponding to \( \alpha \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs011.html b/doc/pub/week44/html/._week44-bs011.html new file mode 100644 index 000000000..e52a09b2e --- /dev/null +++ b/doc/pub/week44/html/._week44-bs011.html @@ -0,0 +1,275 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Schematic Regression Procedure

+ +

+

+
+

+ +

    +
  1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
  2. +
  3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
  4. +
  5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
  6. + +
      +
    • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
    • +
    • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
    • +
    • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
    • +
    + +
  7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
  8. +
+
+
+ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs012.html b/doc/pub/week44/html/._week44-bs012.html new file mode 100644 index 000000000..a2ae790de --- /dev/null +++ b/doc/pub/week44/html/._week44-bs012.html @@ -0,0 +1,267 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A Classification Tree

+ +

+A classification tree is very similar to a regression tree, except +that it is used to predict a qualitative response rather than a +quantitative one. Recall that for a regression tree, the predicted +response for an observation is given by the mean response of the +training observations that belong to the same terminal node. In +contrast, for a classification tree, we predict that each observation +belongs to the most commonly occurring class of training observations +in the region to which it belongs. In interpreting the results of a +classification tree, we are often interested not only in the class +prediction corresponding to a particular terminal node region, but +also in the class proportions among the training observations that +fall into that region. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs013.html b/doc/pub/week44/html/._week44-bs013.html new file mode 100644 index 000000000..32c16a245 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs013.html @@ -0,0 +1,272 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Growing a classification tree

+ +

+The task of growing a +classification tree is quite similar to the task of growing a +regression tree. Just as in the regression setting, we use recursive +binary splitting to grow a classification tree. However, in the +classification setting, the MSE cannot be used as a criterion for making +the binary splits. A natural alternative to MSE is the classification +error rate. Since we plan to assign an observation in a given region +to the most commonly occurring error rate class of training +observations in that region, the classification error rate is simply +the fraction of the training observations in that region that do not +belong to the most common class. + +

+When building a classification tree, either the Gini index or the +entropy are typically used to evaluate the quality of a particular +split, since these two approaches are more sensitive to node purity +than is the classification error rate. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs014.html b/doc/pub/week44/html/._week44-bs014.html new file mode 100644 index 000000000..c237431d1 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs014.html @@ -0,0 +1,298 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Classification tree, how to split nodes

+ +

+If our targets are the outcome of a classification process that takes +for example \( k=1,2,\dots,K \) values, the only thing we need to think of +is to set up the splitting criteria for each node. + +

+We define a PDF \( p_{mk} \) that represents the number of observations of +a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent +this likelihood function in terms of the proportion \( I(y_i=k) \) of +observations of this class in the region \( R_m \) as + +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). +$$ + +

+We let \( p_{mk} \) represent the majority class of observations in region +\( m \). The three most common ways of splitting a node are given by + +

    +
  • Misclassification error
  • +
+ +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +$$ + + +
    +
  • Gini index \( g \)
  • +
+ +$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ + + +
    +
  • Information entropy or just entropy \( s \)
  • +
+ +$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs015.html b/doc/pub/week44/html/._week44-bs015.html new file mode 100644 index 000000000..f5de61b17 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs015.html @@ -0,0 +1,289 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Visualizing the Tree, Classification

+

+ + +

import os
+from sklearn.datasets import load_breast_cancer
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.metrics import confusion_matrix
+from sklearn.tree import export_graphviz
+
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import pandas as pd
+import numpy as np
+
+
+cancer = load_breast_cancer()
+X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+print(X)
+y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
+y = pd.get_dummies(y)
+print(y)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/cancer.dot",
+    feature_names=cancer.feature_names,
+    class_names=cancer.target_names,
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs016.html b/doc/pub/week44/html/._week44-bs016.html new file mode 100644 index 000000000..110b65071 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs016.html @@ -0,0 +1,280 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Visualizing the Tree, The Moons

+

+ + +

# Common imports
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+from pydot import graph_from_dot_data
+import pandas as pd
+import os
+
+np.random.seed(42)
+X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
+X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/moons.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
+os.system(cmd)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs017.html b/doc/pub/week44/html/._week44-bs017.html new file mode 100644 index 000000000..dadda5c73 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs017.html @@ -0,0 +1,266 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Algorithms for Setting up Decision Trees

+ +

+Two algorithms stand out in the set up of decision trees: + +

    +
  1. The CART (Classification And Regression Tree) algorithm for both classification and regression
  2. +
  3. The ID3 algorithm based on the computation of the information gain for classification
  4. +
+ +We discuss both algorithms with applications here. The popular library +Scikit-Learn uses the CART algorithm. For classification problems +you can use either the gini index or the entropy to split a tree +in two branches. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs018.html b/doc/pub/week44/html/._week44-bs018.html new file mode 100644 index 000000000..325440ac4 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs018.html @@ -0,0 +1,275 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The CART algorithm for Classification

+ +

+For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +This could be for example a threshold set by a number below a certain circumference of a malign tumor. + +

+How do we find these two quantities? +We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). +The cost function it tries to minimize is then +$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, +$$ + +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) + is the number of instances in the left/right subset + +

+Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the +\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other +hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), +\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs019.html b/doc/pub/week44/html/._week44-bs019.html new file mode 100644 index 000000000..6a8c3a635 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs019.html @@ -0,0 +1,276 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The CART algorithm for Regression

+ +

+The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now +$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. +$$ + +Here the MSE for a specific node is defined as +$$ +\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, +$$ + +with +$$ +\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, +$$ + +the mean value of all observations in a specific node. + +

+Without any regularization, the regression task for decision trees, +just like for classification tasks, is prone to overfitting. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs020.html b/doc/pub/week44/html/._week44-bs020.html new file mode 100644 index 000000000..c345bc151 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs020.html @@ -0,0 +1,293 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Computing the Gini index

+ +

+The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. + +

+The table here summarizes the various attributes and + +

+
+ + + + + + + + + + + + + + + + + + + + +
Day Outlook Temperature Humidity Wind Ride
1 Sunny Hot High Weak 0
2 Sunny Hot High Strong 1
3 Overcast Hot High Weak 1
4 Rain Mild High Weak 1
5 Rain Cool Normal Weak 1
6 Rain Cool Normal Strong 0
7 Overcast Cool Normal Strong 1
8 Sunny Mild High Weak 0
9 Sunny Cool Normal Weak 1
10 Rain Mild Normal Weak 1
11 Sunny Mild Normal Strong 1
12 Overcast Mild High Strong 1
13 Overcast Hot Normal Weak 1
14 Rain Mild High Strong 0
+
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs021.html b/doc/pub/week44/html/._week44-bs021.html new file mode 100644 index 000000000..31eb96df5 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs021.html @@ -0,0 +1,324 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Simple Python Code to read in Data and perform Classification

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+    os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+    os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+    os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+    return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+    return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+    plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("rideclass.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
+ridedata = pd.DataFrame(ridedata)
+
+# Features and targets
+X = ridedata.loc[:, ridedata.columns != 'Ride'].values
+y = ridedata.loc[:, ridedata.columns == 'Ride'].values
+
+# Create the encoder.
+encoder = OneHotEncoder(handle_unknown="ignore")
+# Assume for simplicity all features are categorical.
+encoder.fit(X)    
+# Apply the encoder.
+X = encoder.transform(X)
+print(X)
+# Then do a Classification tree
+tree_clf = DecisionTreeClassifier(max_depth=2)
+tree_clf.fit(X, y)
+print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
+#transfer to a decision tree graph
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/ride.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs022.html b/doc/pub/week44/html/._week44-bs022.html new file mode 100644 index 000000000..181265337 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs022.html @@ -0,0 +1,326 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Computing the Gini Factor

+ +

+The above functions (gini, entropy and misclassification error) are +important components of the so-called CART algorithm. We will discuss +this algorithm below after we have discussed the information gain +algorithm ID3. + +

+In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. + +

+ + +

# Split a dataset based on an attribute and an attribute value
+def test_split(index, value, dataset):
+	left, right = list(), list()
+	for row in dataset:
+		if row[index] < value:
+			left.append(row)
+		else:
+			right.append(row)
+	return left, right
+ 
+# Calculate the Gini index for a split dataset
+def gini_index(groups, classes):
+	# count all samples at split point
+	n_instances = float(sum([len(group) for group in groups]))
+	# sum weighted Gini index for each group
+	gini = 0.0
+	for group in groups:
+		size = float(len(group))
+		# avoid divide by zero
+		if size == 0:
+			continue
+		score = 0.0
+		# score the group based on the score for each class
+		for class_val in classes:
+			p = [row[-1] for row in group].count(class_val) / size
+			score += p * p
+		# weight the group score by its relative size
+		gini += (1.0 - score) * (size / n_instances)
+	return gini
+
+# Select the best split point for a dataset
+def get_split(dataset):
+	class_values = list(set(row[-1] for row in dataset))
+	b_index, b_value, b_score, b_groups = 999, 999, 999, None
+	for index in range(len(dataset[0])-1):
+		for row in dataset:
+			groups = test_split(index, row[index], dataset)
+			gini = gini_index(groups, class_values)
+			print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
+			if gini < b_score:
+				b_index, b_value, b_score, b_groups = index, row[index], gini, groups
+	return {'index':b_index, 'value':b_value, 'groups':b_groups}
+ 
+dataset = [[0,0,0,0,0],
+            [0,0,0,1,1],
+            [1,0,0,0,1],
+            [2,1,0,0,1],
+            [2,2,1,0,1],
+            [2,2,1,1,0],
+            [1,2,1,1,1],
+            [0,1,0,0,0],
+            [0,2,1,0,1],
+            [2,1,1,0,1],
+            [0,1,1,1,1],
+            [1,1,0,1,1],
+            [1,0,1,0,1],
+            [2,1,0,1,0]]
+
+split = get_split(dataset)
+print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs023.html b/doc/pub/week44/html/._week44-bs023.html new file mode 100644 index 000000000..345fa0cd6 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs023.html @@ -0,0 +1,284 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Entropy and the ID3 algorithm

+ +

+ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

    +
  1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
  2. +
  3. The best attribute is selected and used as the test at the root node of the tree.
  4. +
  5. A descendant of the root node is then created for each possible value of this attribute.
  6. +
  7. Training examples are sorted to the appropriate descendant node.
  8. +
  9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
  10. +
  11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
  12. +
+ +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

+We would like to select the attribute that is most useful for classifying +examples. + +

+What is a good quantitative measure of the worth of an attribute? + +

+Information gain measures how well a given attribute separates the +training examples according to their target classification. + +

+The ID3 algorithm uses this information gain measure to select among the candidate +attributes at each step while growing the tree. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs024.html b/doc/pub/week44/html/._week44-bs024.html new file mode 100644 index 000000000..dbfa49563 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs024.html @@ -0,0 +1,444 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Implementing the ID3 Algorithm

+ +

+ + +

import re
+import math
+from collections import deque
+
+# x is examples in training set
+# y is set of targets
+# label is target attributes
+# Node is a class which has properties values, childs, and next
+# root is top node in the decision tree
+
+class Node(object):
+	def __init__(self):
+		self.value = None
+		self.next = None
+		self.childs = None
+
+# Simple class of Decision Tree
+# Aimed for who want to learn Decision Tree, so it is not optimized
+class DecisionTree(object):
+	def __init__(self, sample, attributes, labels):
+		self.sample = sample
+		self.attributes = attributes
+		self.labels = labels
+		self.labelCodes = None
+		self.labelCodesCount = None
+		self.initLabelCodes()
+		# print(self.labelCodes)
+		self.root = None
+		self.entropy = self.getEntropy([x for x in range(len(self.labels))])
+
+	def initLabelCodes(self):
+		self.labelCodes = []
+		self.labelCodesCount = []
+		for l in self.labels:
+			if l not in self.labelCodes:
+				self.labelCodes.append(l)
+				self.labelCodesCount.append(0)
+			self.labelCodesCount[self.labelCodes.index(l)] += 1
+
+	def getLabelCodeId(self, sampleId):
+		return self.labelCodes.index(self.labels[sampleId])
+
+	def getAttributeValues(self, sampleIds, attributeId):
+		vals = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in vals:
+				vals.append(val)
+		# print(vals)
+		return vals
+
+	def getEntropy(self, sampleIds):
+		entropy = 0
+		labelCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCount[self.getLabelCodeId(sid)] += 1
+		# print("-ge", labelCount)
+		for lv in labelCount:
+			# print(lv)
+			if lv != 0:
+				entropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)
+			else:
+				entropy += 0
+		return entropy
+
+	def getDominantLabel(self, sampleIds):
+		labelCodesCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCodesCount[self.labelCodes.index(self.labels[sid])] += 1
+		return self.labelCodes[labelCodesCount.index(max(labelCodesCount))]
+
+	def getInformationGain(self, sampleIds, attributeId):
+		gain = self.getEntropy(sampleIds)
+		attributeVals = []
+		attributeValsCount = []
+		attributeValsIds = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in attributeVals:
+				attributeVals.append(val)
+				attributeValsCount.append(0)
+				attributeValsIds.append([])
+			vid = attributeVals.index(val)
+			attributeValsCount[vid] += 1
+			attributeValsIds[vid].append(sid)
+		# print("-gig", self.attributes[attributeId])
+		for vc, vids in zip(attributeValsCount, attributeValsIds):
+			# print("-gig", vids)
+			gain -= vc/len(sampleIds) * self.getEntropy(vids)
+		return gain
+
+	def getAttributeMaxInformationGain(self, sampleIds, attributeIds):
+		attributesEntropy = [0] * len(attributeIds)
+		for i, attId in zip(range(len(attributeIds)), attributeIds):
+			attributesEntropy[i] = self.getInformationGain(sampleIds, attId)
+		maxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]
+		return self.attributes[maxId], maxId
+
+	def isSingleLabeled(self, sampleIds):
+		label = self.labels[sampleIds[0]]
+		for sid in sampleIds:
+			if self.labels[sid] != label:
+				return False
+		return True
+
+	def getLabel(self, sampleId):
+		return self.labels[sampleId]
+
+	def id3(self):
+		sampleIds = [x for x in range(len(self.sample))]
+		attributeIds = [x for x in range(len(self.attributes))]
+		self.root = self.id3Recv(sampleIds, attributeIds, self.root)
+
+	def id3Recv(self, sampleIds, attributeIds, root):
+		root = Node() # Initialize current root
+		if self.isSingleLabeled(sampleIds):
+			root.value = self.labels[sampleIds[0]]
+			return root
+		# print(attributeIds)
+		if len(attributeIds) == 0:
+			root.value = self.getDominantLabel(sampleIds)
+			return root
+		bestAttrName, bestAttrId = self.getAttributeMaxInformationGain(
+			sampleIds, attributeIds)
+		# print(bestAttrName)
+		root.value = bestAttrName
+		root.childs = []  # Create list of children
+		for value in self.getAttributeValues(sampleIds, bestAttrId):
+			# print(value)
+			child = Node()
+			child.value = value
+			root.childs.append(child)  # Append new child node to current
+									   # root
+			childSampleIds = []
+			for sid in sampleIds:
+				if self.sample[sid][bestAttrId] == value:
+					childSampleIds.append(sid)
+			if len(childSampleIds) == 0:
+				child.next = self.getDominantLabel(sampleIds)
+			else:
+				# print(bestAttrName, bestAttrId)
+				# print(attributeIds)
+				if len(attributeIds) > 0 and bestAttrId in attributeIds:
+					toRemove = attributeIds.index(bestAttrId)
+					attributeIds.pop(toRemove)
+				child.next = self.id3Recv(
+					childSampleIds, attributeIds, child.next)
+		return root
+
+	def printTree(self):
+		if self.root:
+			roots = deque()
+			roots.append(self.root)
+			while len(roots) > 0:
+				root = roots.popleft()
+				print(root.value)
+				if root.childs:
+					for child in root.childs:
+						print('({})'.format(child.value))
+						roots.append(child.next)
+				elif root.next:
+					print(root.next)
+
+
+def test():
+	f = open('DataFiles/rideclass.csv')
+	attributes = f.readline().split(',')
+	attributes = attributes[1:len(attributes)-1]
+	print(attributes)
+	sample = f.readlines()
+	f.close()
+	for i in range(len(sample)):
+		sample[i] = re.sub('\d+,', '', sample[i])
+		sample[i] = sample[i].strip().split(',')
+	labels = []
+	for s in sample:
+		labels.append(s.pop())
+	# print(sample)
+	# print(labels)
+	decisionTree = DecisionTree(sample, attributes, labels)
+	print("System entropy {}".format(decisionTree.entropy))
+	decisionTree.id3()
+	decisionTree.printTree()
+
+
+if __name__ == '__main__':
+	test()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs025.html b/doc/pub/week44/html/._week44-bs025.html new file mode 100644 index 000000000..4c30c4e9d --- /dev/null +++ b/doc/pub/week44/html/._week44-bs025.html @@ -0,0 +1,297 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Cancer Data again now with Decision Trees and other Methods

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs026.html b/doc/pub/week44/html/._week44-bs026.html new file mode 100644 index 000000000..e50d7c888 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs026.html @@ -0,0 +1,320 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Another example, the moons again

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if not iris:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    if plot_training:
+        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+        plt.axis(axes)
+    if iris:
+        plt.xlabel("Petal length", fontsize=14)
+        plt.ylabel("Petal width", fontsize=14)
+    else:
+        plt.xlabel(r"$x_1$", fontsize=18)
+        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+    if legend:
+        plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs027.html b/doc/pub/week44/html/._week44-bs027.html new file mode 100644 index 000000000..22e1b312d --- /dev/null +++ b/doc/pub/week44/html/._week44-bs027.html @@ -0,0 +1,276 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Playing around with regions

+

+ + +

np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs028.html b/doc/pub/week44/html/._week44-bs028.html new file mode 100644 index 000000000..030073d03 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs028.html @@ -0,0 +1,270 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Regression trees

+

+ + +

# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+
+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs029.html b/doc/pub/week44/html/._week44-bs029.html new file mode 100644 index 000000000..804c6cd0a --- /dev/null +++ b/doc/pub/week44/html/._week44-bs029.html @@ -0,0 +1,326 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Final regressor code

+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+    y_pred = tree_reg.predict(x1)
+    plt.axis(axes)
+    plt.xlabel("$x_1$", fontsize=18)
+    if ylabel:
+        plt.ylabel(ylabel, fontsize=18, rotation=0)
+    plt.plot(X, y, "b.")
+    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+

+ + +

tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs030.html b/doc/pub/week44/html/._week44-bs030.html new file mode 100644 index 000000000..25c77f8e5 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs030.html @@ -0,0 +1,262 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Pros and cons of trees, pros

+ +
    +
  • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
  • +
  • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
  • +
  • No feature normalization needed
  • +
  • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
  • +
  • Can model nonlinear relationships
  • +
  • Can model interactions between the different descriptive features
  • +
  • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
  • +
+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs031.html b/doc/pub/week44/html/._week44-bs031.html new file mode 100644 index 000000000..d9eb5b881 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs031.html @@ -0,0 +1,265 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Disadvantages

+ +
    +
  • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
  • +
  • If continuous features are used the tree may become quite large and hence less interpretable
  • +
  • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
  • +
  • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
  • +
  • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
  • +
  • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
  • +
  • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
  • +
+ +However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs032.html b/doc/pub/week44/html/._week44-bs032.html new file mode 100644 index 000000000..ca05b421f --- /dev/null +++ b/doc/pub/week44/html/._week44-bs032.html @@ -0,0 +1,272 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

+ +

+As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +

+This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct +forests and jungles of trees, homogeneous ones or heterogenous +ones. These methods are recognized by different names which we will +try to explain here. These are + +

    +
  1. Voting classifiers
  2. +
  3. Bagging and Pasting
  4. +
  5. Random forests
  6. +
  7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
  8. +
+ +We discuss these methods here. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs033.html b/doc/pub/week44/html/._week44-bs033.html new file mode 100644 index 000000000..aff8b6070 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs033.html @@ -0,0 +1,252 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

An Overview of Ensemble Methods

+ +

+



+ +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs034.html b/doc/pub/week44/html/._week44-bs034.html new file mode 100644 index 000000000..094616fd3 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs034.html @@ -0,0 +1,262 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Bagging

+ +

+The plain decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of \( n \) to \( p \) is moderately large. + +

+Bootstrap aggregation, or just bagging, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs035.html b/doc/pub/week44/html/._week44-bs035.html new file mode 100644 index 000000000..5b19ed079 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs035.html @@ -0,0 +1,271 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

More bagging

+ +

+Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +

+However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all \( B \) possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all \( B \) trees. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs036.html b/doc/pub/week44/html/._week44-bs036.html new file mode 100644 index 000000000..951944fda --- /dev/null +++ b/doc/pub/week44/html/._week44-bs036.html @@ -0,0 +1,262 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Simple Voting Example, head or tail

+

+ + +

heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs037.html b/doc/pub/week44/html/._week44-bs037.html new file mode 100644 index 000000000..f489f7235 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs037.html @@ -0,0 +1,291 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Using the Voting Classifier

+

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs038.html b/doc/pub/week44/html/._week44-bs038.html new file mode 100644 index 000000000..730fd4892 --- /dev/null +++ b/doc/pub/week44/html/._week44-bs038.html @@ -0,0 +1,298 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Please, not the moons again! Voting and Bagging

+ +

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+ + +

log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs039.html b/doc/pub/week44/html/._week44-bs039.html new file mode 100644 index 000000000..0c6863adc --- /dev/null +++ b/doc/pub/week44/html/._week44-bs039.html @@ -0,0 +1,300 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Bagging Examples

+ +

+ + +

from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(random_state=42), n_estimators=500,
+    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+
+

+ + +

from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+
+

+ + +

tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+
+

+ + +

from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if contour:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+    plt.axis(axes)
+    plt.xlabel(r"$x_1$", fontsize=18)
+    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/._week44-bs040.html b/doc/pub/week44/html/._week44-bs040.html new file mode 100644 index 000000000..3eb6916ab --- /dev/null +++ b/doc/pub/week44/html/._week44-bs040.html @@ -0,0 +1,306 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Making your own Bootstrap: Changing the Level of the Decision Tree

+ +

+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3) 
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+    model = DecisionTreeRegressor(max_depth=degree) 
+    y_pred = np.empty((y_test.shape[0], n_boostraps))
+    for i in range(n_boostraps):
+        x_, y_ = resample(X_train_scaled, y_train)
+        model.fit(x_, y_)
+        y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+    print('Polynomial degree:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE simple tree')
+plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+

+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week44/html/reveal.js/.gitignore b/doc/pub/week44/html/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/pub/week44/html/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/pub/week44/html/reveal.js/.travis.yml b/doc/pub/week44/html/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/pub/week44/html/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/week44/html/reveal.js/CONTRIBUTING.md b/doc/pub/week44/html/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/pub/week44/html/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/pub/week44/html/reveal.js/Gruntfile.js b/doc/pub/week44/html/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/pub/week44/html/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/pub/week44/html/reveal.js/LICENSE b/doc/pub/week44/html/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/pub/week44/html/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/pub/week44/html/reveal.js/README.md b/doc/pub/week44/html/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/pub/week44/html/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
+
+
Single Horizontal Slide
+
+
Vertical Slide 1
+
Vertical Slide 2
+
+
+
+``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` +
+``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
+
+``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
+ +
+``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. + +```html +
+ +
+``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
+``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
+

All CSS color formats are supported, like rgba() or hsl().

+
+
+

This slide will have a full-size background image.

+
+
+

This background image will be sized to 100px and repeated.

+
+
+

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

+
+
+

Embeds a web page as a background. Note that the page won't be interactive.

+
+``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
+

This slide will override the presentation transition and zoom!

+
+ +
+

Choose from three transition speeds: default, fast or slow!

+
+``` + +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
+

grow

+

shrink

+

fade-out

+

visible only once

+

blue only once

+

highlight-red

+

highlight-green

+

highlight-blue

+
+``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
+ + I'll fade in, then out + +
+``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
+

Appears last

+

Appears first

+

Appears second

+
+``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
+

+(def lazy-fib
+  (concat
+   [0 1]
+   ((fn rfib [a b]
+        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
+	
+
+``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `
+ +
+ +

 

 

 

+ + + + + + +
+

week 44: From Decision Trees to Bagging methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week44/html/week44-reveal.html b/doc/pub/week44/html/week44-reveal.html new file mode 100644 index 000000000..a45f94925 --- /dev/null +++ b/doc/pub/week44/html/week44-reveal.html @@ -0,0 +1,2003 @@ + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + + + + + + + + + + +
+ + + + +

week 44: From Decision Trees to Bagging methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

 
+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

 
+

Sep 16, 2020

+
+

+ +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+
+ + +
+

Decision trees, overarching aims

+ +

+We start here with the most basic algorithm, the so-called decision +tree. With this basic algorithm we can in turn build more complex +networks, spanning from homogeneous and heterogenous forests (bagging, +random forests and more) to one of the most popular supervised +algorithms nowadays, the extreme gradient boosting, or just +XGBoost. But let us start with the simplest possible ingredient. + +

+Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + +

+The main idea of decision trees +is to find those descriptive features which contain the most +information regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +

+The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the most +informative feature is done until we accomplish a stopping criteria +where we then finally end up in so called leaf nodes. + +

+A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. + +

+The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. +

+ + +
+

A typical Decision Tree with its pertinent Jargon, Classification Problem

+ +

+



+ +

+This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches. +

+ + +
+

General Features

+ +

+The overarching approach to decision trees is a top-down approach. + +

    +

  • A leaf provides the classification of a given instance.
  • +

  • A node specifies a test of some attribute of the instance.
  • +

  • A branch corresponds to a possible values of an attribute.
  • +

  • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
  • +
+

+ +This process is then repeated for the subtree rooted at the new +node. +

+ + +
+

How do we set it up?

+ +

+In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +

    +

  1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
  2. +

  3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
  4. +

  5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
  6. +

  7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
  8. +
+

+ +Then we are essentially done! +

+ + +
+

Decision trees and Regression

+

+ + +

import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x<steps:
+    distance+=np.random.randint(-1,2)
+    distance_list.append(distance)
+    x+=1
+    steps_list.append(x)
+plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
+
+steps_list=np.asarray(steps_list)
+distance_list=np.asarray(distance_list)
+
+X=steps_list[:,np.newaxis]
+
+#Polynomial fits
+
+#Degree 2
+poly_features=PolynomialFeatures(degree=2, include_bias=False)
+X_poly=poly_features.fit_transform(X)
+
+lin_reg=LinearRegression()
+poly_fit=lin_reg.fit(X_poly,distance_list)
+b=lin_reg.coef_
+c=lin_reg.intercept_
+print ("2nd degree coefficients:")
+print ("zero power: ",c)
+print ("first power: ", b[0])
+print ("second power: ",b[1])
+
+z = np.arange(0, steps, .01)
+z_mod=b[1]*z**2+b[0]*z+c
+
+fit_mod=b[1]*X**2+b[0]*X+c
+plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
+plt.title("Polynomial Regression")
+
+plt.xlabel("Steps")
+plt.ylabel("Distance")
+
+#Degree 10
+poly_features10=PolynomialFeatures(degree=10, include_bias=False)
+X_poly10=poly_features10.fit_transform(X)
+
+poly_fit10=lin_reg.fit(X_poly10,distance_list)
+
+y_plot=poly_fit10.predict(X_poly10)
+plt.plot(X, y_plot, color='black', label="10th Degree Fit")
+
+plt.legend()
+plt.show()
+
+
+#Decision Tree Regression
+from sklearn.tree import DecisionTreeRegressor
+regr_1=DecisionTreeRegressor(max_depth=2)
+regr_2=DecisionTreeRegressor(max_depth=5)
+regr_3=DecisionTreeRegressor(max_depth=7)
+regr_1.fit(X, distance_list)
+regr_2.fit(X, distance_list)
+regr_3.fit(X, distance_list)
+
+X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
+y_1 = regr_1.predict(X_test)
+y_2 = regr_2.predict(X_test)
+y_3=regr_3.predict(X_test)
+
+# Plot the results
+plt.figure()
+plt.scatter(X, distance_list, s=2.5, c="black", label="data")
+plt.plot(X_test, y_1, color="red",
+         label="max_depth=2", linewidth=2)
+plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
+plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
+
+plt.xlabel("Data")
+plt.ylabel("Darget")
+plt.title("Decision Tree Regression")
+plt.legend()
+plt.show()
+
+
+ + +
+

Building a tree, regression

+ +

+There are mainly two steps + +

    +

  1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
  2. + +

  3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
  4. +
+

+ +How do we construct the regions \( R_1,\dots,R_J \)? In theory, the +regions could have any shape. However, we choose to divide the +predictor space into high-dimensional rectangles, or boxes, for +simplicity and for ease of interpretation of the resulting predictive +model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the +MSE, given by + +

 
+$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ +

 
+ +

+where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). +

+ + +
+

A top-down approach, recursive binary splitting

+ +

+Unfortunately, it is computationally infeasible to consider every +possible partition of the feature space into \( J \) boxes. The common +strategy is to take a top-down approach + +

+The approach is top-down because it begins at the top of the tree (all +observations belong to a single region) and then successively splits +the predictor space; each split is indicated via two new branches +further down on the tree. It is greedy because at each step of the +tree-building process, the best split is made at that particular step, +rather than looking ahead and picking a split that will lead to a +better tree in some future step. +

+ + +
+

Making a tree

+ +

+In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +

 
+$$ +\left\{X\vert x_j < s\right\}, +$$ +

 
+ +and +

 
+$$ +\left\{X\vert x_j \geq s\right\}, +$$ +

 
+ +so that we obtain the lowest MSE, that is +

 
+$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ +

 
+ +

+which we want to minimize by considering all predictors +\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for +each predictor. These values could be determined by randomly assigned +numbers or by starting at the midpoint and then proceed till we find +an optimal value. + +

+For any \( j \) and \( s \), we define the pair of half-planes where +\( \overline{y}_{R_1} \) is the mean response for the training +observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean +response for the training observations in \( R_2(j,s) \). + +

+Finding the values of \( j \) and \( s \) that minimize the above equation can be +done quite quickly, especially when the number of features \( p \) is not +too large. + +

+Next, we repeat the process, looking +for the best predictor and best cutpoint in order to split the data +further so as to minimize the MSE within each of the resulting +regions. However, this time, instead of splitting the entire predictor +space, we split one of the two previously identified regions. We now +have three regions. Again, we look to split one of these three regions +further, so as to minimize the MSE. The process continues until a +stopping criterion is reached; for instance, we may continue until no +region contains more than five observations. +

+ + +
+

Pruning the tree

+ +

+The above procedure is rather straightforward, but leads often to +overfitting and unnecessarily large and complicated trees. The basic +idea is to grow a large tree \( T_0 \) and then prune it back in order to +obtain a subtree. A smaller tree with fewer splits (fewer regions) can +lead to smaller variance and better interpretation at the cost of a +little more bias. + +

+The so-called Cost complexity pruning algorithm gives us a +way to do just this. Rather than considering every possible subtree, +we consider a sequence of trees indexed by a nonnegative tuning +parameter \( \alpha \). +

+ + +
+

Cost complexity pruning

+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +

 
+$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ +

 
+ +is as small as possible. Here \( \overline{T} \) is +the number of terminal nodes of the tree \( T \) , \( R_m \) is the +rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. + +

+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. + +

+It turns out that as we increase \( \alpha \) from zero +branches get pruned from the tree in a nested and predictable fashion, +so obtaining the whole sequence of subtrees as a function of \( \alpha \) is +easy. We can select a value of \( \alpha \) using a validation set or using +cross-validation. We then return to the full data set and obtain the +subtree corresponding to \( \alpha \). +

+ + +
+

Schematic Regression Procedure

+ +

+

+Building a Regression Tree. +
    +

  1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
  2. +

  3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
  4. +

  5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
  6. + +
      + +

    • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
    • + +

    • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
    • + +

    • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
    • +
    +

  7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
  8. +
+
+
+ + +
+

A Classification Tree

+ +

+A classification tree is very similar to a regression tree, except +that it is used to predict a qualitative response rather than a +quantitative one. Recall that for a regression tree, the predicted +response for an observation is given by the mean response of the +training observations that belong to the same terminal node. In +contrast, for a classification tree, we predict that each observation +belongs to the most commonly occurring class of training observations +in the region to which it belongs. In interpreting the results of a +classification tree, we are often interested not only in the class +prediction corresponding to a particular terminal node region, but +also in the class proportions among the training observations that +fall into that region. +

+ + +
+

Growing a classification tree

+ +

+The task of growing a +classification tree is quite similar to the task of growing a +regression tree. Just as in the regression setting, we use recursive +binary splitting to grow a classification tree. However, in the +classification setting, the MSE cannot be used as a criterion for making +the binary splits. A natural alternative to MSE is the classification +error rate. Since we plan to assign an observation in a given region +to the most commonly occurring error rate class of training +observations in that region, the classification error rate is simply +the fraction of the training observations in that region that do not +belong to the most common class. + +

+When building a classification tree, either the Gini index or the +entropy are typically used to evaluate the quality of a particular +split, since these two approaches are more sensitive to node purity +than is the classification error rate. +

+ + +
+

Classification tree, how to split nodes

+ +

+If our targets are the outcome of a classification process that takes +for example \( k=1,2,\dots,K \) values, the only thing we need to think of +is to set up the splitting criteria for each node. + +

+We define a PDF \( p_{mk} \) that represents the number of observations of +a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent +this likelihood function in terms of the proportion \( I(y_i=k) \) of +observations of this class in the region \( R_m \) as + +

 
+$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). +$$ +

 
+ +

+We let \( p_{mk} \) represent the majority class of observations in region +\( m \). The three most common ways of splitting a node are given by + +

    +

  • Misclassification error
  • +
+

 
+$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +$$ +

 
+ + +

    +

  • Gini index \( g \)
  • +
+

 
+$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ +

 
+ + +

    +

  • Information entropy or just entropy \( s \)
  • +
+

 
+$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ +

 
+

+ + +
+

Visualizing the Tree, Classification

+

+ + +

import os
+from sklearn.datasets import load_breast_cancer
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.metrics import confusion_matrix
+from sklearn.tree import export_graphviz
+
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import pandas as pd
+import numpy as np
+
+
+cancer = load_breast_cancer()
+X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+print(X)
+y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
+y = pd.get_dummies(y)
+print(y)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/cancer.dot",
+    feature_names=cancer.feature_names,
+    class_names=cancer.target_names,
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+
+ + +
+

Visualizing the Tree, The Moons

+

+ + +

# Common imports
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+from pydot import graph_from_dot_data
+import pandas as pd
+import os
+
+np.random.seed(42)
+X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
+X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/moons.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
+os.system(cmd)
+
+
+ + +
+

Algorithms for Setting up Decision Trees

+ +

+Two algorithms stand out in the set up of decision trees: + +

    +

  1. The CART (Classification And Regression Tree) algorithm for both classification and regression
  2. +

  3. The ID3 algorithm based on the computation of the information gain for classification
  4. +
+

+ +We discuss both algorithms with applications here. The popular library +Scikit-Learn uses the CART algorithm. For classification problems +you can use either the gini index or the entropy to split a tree +in two branches. +

+ + +
+

The CART algorithm for Classification

+ +

+For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +This could be for example a threshold set by a number below a certain circumference of a malign tumor. + +

+How do we find these two quantities? +We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). +The cost function it tries to minimize is then +

 
+$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, +$$ +

 
+ +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) + is the number of instances in the left/right subset + +

+Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the +\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other +hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), +\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). +

+ + +
+

The CART algorithm for Regression

+ +

+The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now +

 
+$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. +$$ +

 
+ +Here the MSE for a specific node is defined as +

 
+$$ +\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, +$$ +

 
+ +with +

 
+$$ +\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, +$$ +

 
+ +the mean value of all observations in a specific node. + +

+Without any regularization, the regression task for decision trees, +just like for classification tasks, is prone to overfitting. +

+ + +
+

Computing the Gini index

+ +

+The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. + +

+The table here summarizes the various attributes and + + + + + + + + + + + + + + + + + + + + +
Day Outlook Temperature Humidity Wind Ride
1 Sunny Hot High Weak 0
2 Sunny Hot High Strong 1
3 Overcast Hot High Weak 1
4 Rain Mild High Weak 1
5 Rain Cool Normal Weak 1
6 Rain Cool Normal Strong 0
7 Overcast Cool Normal Strong 1
8 Sunny Mild High Weak 0
9 Sunny Cool Normal Weak 1
10 Rain Mild Normal Weak 1
11 Sunny Mild Normal Strong 1
12 Overcast Mild High Strong 1
13 Overcast Hot Normal Weak 1
14 Rain Mild High Strong 0
+

+ + +
+

Simple Python Code to read in Data and perform Classification

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+    os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+    os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+    os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+    return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+    return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+    plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("rideclass.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
+ridedata = pd.DataFrame(ridedata)
+
+# Features and targets
+X = ridedata.loc[:, ridedata.columns != 'Ride'].values
+y = ridedata.loc[:, ridedata.columns == 'Ride'].values
+
+# Create the encoder.
+encoder = OneHotEncoder(handle_unknown="ignore")
+# Assume for simplicity all features are categorical.
+encoder.fit(X)    
+# Apply the encoder.
+X = encoder.transform(X)
+print(X)
+# Then do a Classification tree
+tree_clf = DecisionTreeClassifier(max_depth=2)
+tree_clf.fit(X, y)
+print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
+#transfer to a decision tree graph
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/ride.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+
+ + +
+

Computing the Gini Factor

+ +

+The above functions (gini, entropy and misclassification error) are +important components of the so-called CART algorithm. We will discuss +this algorithm below after we have discussed the information gain +algorithm ID3. + +

+In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. + +

+ + +

# Split a dataset based on an attribute and an attribute value
+def test_split(index, value, dataset):
+	left, right = list(), list()
+	for row in dataset:
+		if row[index] < value:
+			left.append(row)
+		else:
+			right.append(row)
+	return left, right
+ 
+# Calculate the Gini index for a split dataset
+def gini_index(groups, classes):
+	# count all samples at split point
+	n_instances = float(sum([len(group) for group in groups]))
+	# sum weighted Gini index for each group
+	gini = 0.0
+	for group in groups:
+		size = float(len(group))
+		# avoid divide by zero
+		if size == 0:
+			continue
+		score = 0.0
+		# score the group based on the score for each class
+		for class_val in classes:
+			p = [row[-1] for row in group].count(class_val) / size
+			score += p * p
+		# weight the group score by its relative size
+		gini += (1.0 - score) * (size / n_instances)
+	return gini
+
+# Select the best split point for a dataset
+def get_split(dataset):
+	class_values = list(set(row[-1] for row in dataset))
+	b_index, b_value, b_score, b_groups = 999, 999, 999, None
+	for index in range(len(dataset[0])-1):
+		for row in dataset:
+			groups = test_split(index, row[index], dataset)
+			gini = gini_index(groups, class_values)
+			print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
+			if gini < b_score:
+				b_index, b_value, b_score, b_groups = index, row[index], gini, groups
+	return {'index':b_index, 'value':b_value, 'groups':b_groups}
+ 
+dataset = [[0,0,0,0,0],
+            [0,0,0,1,1],
+            [1,0,0,0,1],
+            [2,1,0,0,1],
+            [2,2,1,0,1],
+            [2,2,1,1,0],
+            [1,2,1,1,1],
+            [0,1,0,0,0],
+            [0,2,1,0,1],
+            [2,1,1,0,1],
+            [0,1,1,1,1],
+            [1,1,0,1,1],
+            [1,0,1,0,1],
+            [2,1,0,1,0]]
+
+split = get_split(dataset)
+print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
+
+
+ + +
+

Entropy and the ID3 algorithm

+ +

+ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

    +

  1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
  2. +

  3. The best attribute is selected and used as the test at the root node of the tree.
  4. +

  5. A descendant of the root node is then created for each possible value of this attribute.
  6. +

  7. Training examples are sorted to the appropriate descendant node.
  8. +

  9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
  10. +

  11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
  12. +
+

+ +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

+We would like to select the attribute that is most useful for classifying +examples. + +

+What is a good quantitative measure of the worth of an attribute? + +

+Information gain measures how well a given attribute separates the +training examples according to their target classification. + +

+The ID3 algorithm uses this information gain measure to select among the candidate +attributes at each step while growing the tree. +

+ + +
+

Implementing the ID3 Algorithm

+ +

+ + +

import re
+import math
+from collections import deque
+
+# x is examples in training set
+# y is set of targets
+# label is target attributes
+# Node is a class which has properties values, childs, and next
+# root is top node in the decision tree
+
+class Node(object):
+	def __init__(self):
+		self.value = None
+		self.next = None
+		self.childs = None
+
+# Simple class of Decision Tree
+# Aimed for who want to learn Decision Tree, so it is not optimized
+class DecisionTree(object):
+	def __init__(self, sample, attributes, labels):
+		self.sample = sample
+		self.attributes = attributes
+		self.labels = labels
+		self.labelCodes = None
+		self.labelCodesCount = None
+		self.initLabelCodes()
+		# print(self.labelCodes)
+		self.root = None
+		self.entropy = self.getEntropy([x for x in range(len(self.labels))])
+
+	def initLabelCodes(self):
+		self.labelCodes = []
+		self.labelCodesCount = []
+		for l in self.labels:
+			if l not in self.labelCodes:
+				self.labelCodes.append(l)
+				self.labelCodesCount.append(0)
+			self.labelCodesCount[self.labelCodes.index(l)] += 1
+
+	def getLabelCodeId(self, sampleId):
+		return self.labelCodes.index(self.labels[sampleId])
+
+	def getAttributeValues(self, sampleIds, attributeId):
+		vals = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in vals:
+				vals.append(val)
+		# print(vals)
+		return vals
+
+	def getEntropy(self, sampleIds):
+		entropy = 0
+		labelCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCount[self.getLabelCodeId(sid)] += 1
+		# print("-ge", labelCount)
+		for lv in labelCount:
+			# print(lv)
+			if lv != 0:
+				entropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)
+			else:
+				entropy += 0
+		return entropy
+
+	def getDominantLabel(self, sampleIds):
+		labelCodesCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCodesCount[self.labelCodes.index(self.labels[sid])] += 1
+		return self.labelCodes[labelCodesCount.index(max(labelCodesCount))]
+
+	def getInformationGain(self, sampleIds, attributeId):
+		gain = self.getEntropy(sampleIds)
+		attributeVals = []
+		attributeValsCount = []
+		attributeValsIds = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in attributeVals:
+				attributeVals.append(val)
+				attributeValsCount.append(0)
+				attributeValsIds.append([])
+			vid = attributeVals.index(val)
+			attributeValsCount[vid] += 1
+			attributeValsIds[vid].append(sid)
+		# print("-gig", self.attributes[attributeId])
+		for vc, vids in zip(attributeValsCount, attributeValsIds):
+			# print("-gig", vids)
+			gain -= vc/len(sampleIds) * self.getEntropy(vids)
+		return gain
+
+	def getAttributeMaxInformationGain(self, sampleIds, attributeIds):
+		attributesEntropy = [0] * len(attributeIds)
+		for i, attId in zip(range(len(attributeIds)), attributeIds):
+			attributesEntropy[i] = self.getInformationGain(sampleIds, attId)
+		maxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]
+		return self.attributes[maxId], maxId
+
+	def isSingleLabeled(self, sampleIds):
+		label = self.labels[sampleIds[0]]
+		for sid in sampleIds:
+			if self.labels[sid] != label:
+				return False
+		return True
+
+	def getLabel(self, sampleId):
+		return self.labels[sampleId]
+
+	def id3(self):
+		sampleIds = [x for x in range(len(self.sample))]
+		attributeIds = [x for x in range(len(self.attributes))]
+		self.root = self.id3Recv(sampleIds, attributeIds, self.root)
+
+	def id3Recv(self, sampleIds, attributeIds, root):
+		root = Node() # Initialize current root
+		if self.isSingleLabeled(sampleIds):
+			root.value = self.labels[sampleIds[0]]
+			return root
+		# print(attributeIds)
+		if len(attributeIds) == 0:
+			root.value = self.getDominantLabel(sampleIds)
+			return root
+		bestAttrName, bestAttrId = self.getAttributeMaxInformationGain(
+			sampleIds, attributeIds)
+		# print(bestAttrName)
+		root.value = bestAttrName
+		root.childs = []  # Create list of children
+		for value in self.getAttributeValues(sampleIds, bestAttrId):
+			# print(value)
+			child = Node()
+			child.value = value
+			root.childs.append(child)  # Append new child node to current
+									   # root
+			childSampleIds = []
+			for sid in sampleIds:
+				if self.sample[sid][bestAttrId] == value:
+					childSampleIds.append(sid)
+			if len(childSampleIds) == 0:
+				child.next = self.getDominantLabel(sampleIds)
+			else:
+				# print(bestAttrName, bestAttrId)
+				# print(attributeIds)
+				if len(attributeIds) > 0 and bestAttrId in attributeIds:
+					toRemove = attributeIds.index(bestAttrId)
+					attributeIds.pop(toRemove)
+				child.next = self.id3Recv(
+					childSampleIds, attributeIds, child.next)
+		return root
+
+	def printTree(self):
+		if self.root:
+			roots = deque()
+			roots.append(self.root)
+			while len(roots) > 0:
+				root = roots.popleft()
+				print(root.value)
+				if root.childs:
+					for child in root.childs:
+						print('({})'.format(child.value))
+						roots.append(child.next)
+				elif root.next:
+					print(root.next)
+
+
+def test():
+	f = open('DataFiles/rideclass.csv')
+	attributes = f.readline().split(',')
+	attributes = attributes[1:len(attributes)-1]
+	print(attributes)
+	sample = f.readlines()
+	f.close()
+	for i in range(len(sample)):
+		sample[i] = re.sub('\d+,', '', sample[i])
+		sample[i] = sample[i].strip().split(',')
+	labels = []
+	for s in sample:
+		labels.append(s.pop())
+	# print(sample)
+	# print(labels)
+	decisionTree = DecisionTree(sample, attributes, labels)
+	print("System entropy {}".format(decisionTree.entropy))
+	decisionTree.id3()
+	decisionTree.printTree()
+
+
+if __name__ == '__main__':
+	test()
+
+
+ + +
+

Cancer Data again now with Decision Trees and other Methods

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+ + +
+

Another example, the moons again

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if not iris:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    if plot_training:
+        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+        plt.axis(axes)
+    if iris:
+        plt.xlabel("Petal length", fontsize=14)
+        plt.ylabel("Petal width", fontsize=14)
+    else:
+        plt.xlabel(r"$x_1$", fontsize=18)
+        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+    if legend:
+        plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+
+ + +
+

Playing around with regions

+

+ + +

np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+
+
+ + +
+

Regression trees

+

+ + +

# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+
+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+
+
+ + +
+

Final regressor code

+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+    y_pred = tree_reg.predict(x1)
+    plt.axis(axes)
+    plt.xlabel("$x_1$", fontsize=18)
+    if ylabel:
+        plt.ylabel(ylabel, fontsize=18, rotation=0)
+    plt.plot(X, y, "b.")
+    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+

+ + +

tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+
+
+ + +
+

Pros and cons of trees, pros

+ +
    +

  • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
  • +

  • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
  • +

  • No feature normalization needed
  • +

  • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
  • +

  • Can model nonlinear relationships
  • +

  • Can model interactions between the different descriptive features
  • +

  • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
  • +
+
+ + +
+

Disadvantages

+ +
    +

  • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
  • +

  • If continuous features are used the tree may become quite large and hence less interpretable
  • +

  • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
  • +

  • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
  • +

  • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
  • +

  • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
  • +

  • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
  • +
+

+ +However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. +

+ + +
+

Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

+ +

+As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +

+This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct +forests and jungles of trees, homogeneous ones or heterogenous +ones. These methods are recognized by different names which we will +try to explain here. These are + +

    +

  1. Voting classifiers
  2. +

  3. Bagging and Pasting
  4. +

  5. Random forests
  6. +

  7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
  8. +
+

+ +We discuss these methods here. +

+ + +
+

An Overview of Ensemble Methods

+ +

+



+
+ + +
+

Bagging

+ +

+The plain decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of \( n \) to \( p \) is moderately large. + +

+Bootstrap aggregation, or just bagging, is a +general-purpose procedure for reducing the variance of a statistical +learning method. +

+ + +
+

More bagging

+ +

+Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +

+However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all \( B \) possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all \( B \) trees. +

+ + +
+

Simple Voting Example, head or tail

+

+ + +

heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+
+ + +
+

Using the Voting Classifier

+

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
+ + +
+

Please, not the moons again! Voting and Bagging

+ +

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+ + +

log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+
+ + +
+

Bagging Examples

+ +

+ + +

from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(random_state=42), n_estimators=500,
+    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+
+

+ + +

from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+
+

+ + +

tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+
+

+ + +

from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if contour:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+    plt.axis(axes)
+    plt.xlabel(r"$x_1$", fontsize=18)
+    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+
+
+ + +
+

Making your own Bootstrap: Changing the Level of the Decision Tree

+ +

+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3) 
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+    model = DecisionTreeRegressor(max_depth=degree) 
+    y_pred = np.empty((y_test.shape[0], n_boostraps))
+    for i in range(n_boostraps):
+        x_, y_ = resample(X_train_scaled, y_train)
+        model.fit(x_, y_)
+        y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+    print('Polynomial degree:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE simple tree')
+plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+
+ + + +
+
+ + + + + + + + + + + + diff --git a/doc/pub/week44/html/week44-solarized.html b/doc/pub/week44/html/week44-solarized.html new file mode 100644 index 000000000..ef27ff6c0 --- /dev/null +++ b/doc/pub/week44/html/week44-solarized.html @@ -0,0 +1,1835 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

week 44: From Decision Trees to Bagging methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Decision trees, overarching aims

+ +

+We start here with the most basic algorithm, the so-called decision +tree. With this basic algorithm we can in turn build more complex +networks, spanning from homogeneous and heterogenous forests (bagging, +random forests and more) to one of the most popular supervised +algorithms nowadays, the extreme gradient boosting, or just +XGBoost. But let us start with the simplest possible ingredient. + +

+Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + +

+The main idea of decision trees +is to find those descriptive features which contain the most +information regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +

+The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the most +informative feature is done until we accomplish a stopping criteria +where we then finally end up in so called leaf nodes. + +

+A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. + +

+The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +

+









+ +

A typical Decision Tree with its pertinent Jargon, Classification Problem

+ +

+



+ +

+This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches. + +

+









+ +

General Features

+ +

+The overarching approach to decision trees is a top-down approach. + +

    +
  • A leaf provides the classification of a given instance.
  • +
  • A node specifies a test of some attribute of the instance.
  • +
  • A branch corresponds to a possible values of an attribute.
  • +
  • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
  • +
+ +This process is then repeated for the subtree rooted at the new +node. + +

+









+ +

How do we set it up?

+ +

+In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +

    +
  1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
  2. +
  3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
  4. +
  5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
  6. +
  7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
  8. +
+ +Then we are essentially done! + +

+









+ +

Decision trees and Regression

+

+ + +

import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x<steps:
+    distance+=np.random.randint(-1,2)
+    distance_list.append(distance)
+    x+=1
+    steps_list.append(x)
+plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
+
+steps_list=np.asarray(steps_list)
+distance_list=np.asarray(distance_list)
+
+X=steps_list[:,np.newaxis]
+
+#Polynomial fits
+
+#Degree 2
+poly_features=PolynomialFeatures(degree=2, include_bias=False)
+X_poly=poly_features.fit_transform(X)
+
+lin_reg=LinearRegression()
+poly_fit=lin_reg.fit(X_poly,distance_list)
+b=lin_reg.coef_
+c=lin_reg.intercept_
+print ("2nd degree coefficients:")
+print ("zero power: ",c)
+print ("first power: ", b[0])
+print ("second power: ",b[1])
+
+z = np.arange(0, steps, .01)
+z_mod=b[1]*z**2+b[0]*z+c
+
+fit_mod=b[1]*X**2+b[0]*X+c
+plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
+plt.title("Polynomial Regression")
+
+plt.xlabel("Steps")
+plt.ylabel("Distance")
+
+#Degree 10
+poly_features10=PolynomialFeatures(degree=10, include_bias=False)
+X_poly10=poly_features10.fit_transform(X)
+
+poly_fit10=lin_reg.fit(X_poly10,distance_list)
+
+y_plot=poly_fit10.predict(X_poly10)
+plt.plot(X, y_plot, color='black', label="10th Degree Fit")
+
+plt.legend()
+plt.show()
+
+
+#Decision Tree Regression
+from sklearn.tree import DecisionTreeRegressor
+regr_1=DecisionTreeRegressor(max_depth=2)
+regr_2=DecisionTreeRegressor(max_depth=5)
+regr_3=DecisionTreeRegressor(max_depth=7)
+regr_1.fit(X, distance_list)
+regr_2.fit(X, distance_list)
+regr_3.fit(X, distance_list)
+
+X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
+y_1 = regr_1.predict(X_test)
+y_2 = regr_2.predict(X_test)
+y_3=regr_3.predict(X_test)
+
+# Plot the results
+plt.figure()
+plt.scatter(X, distance_list, s=2.5, c="black", label="data")
+plt.plot(X_test, y_1, color="red",
+         label="max_depth=2", linewidth=2)
+plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
+plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
+
+plt.xlabel("Data")
+plt.ylabel("Darget")
+plt.title("Decision Tree Regression")
+plt.legend()
+plt.show()
+
+

+









+ +

Building a tree, regression

+ +

+There are mainly two steps + +

    +
  1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
  2. +
  3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
  4. +
+ +How do we construct the regions \( R_1,\dots,R_J \)? In theory, the +regions could have any shape. However, we choose to divide the +predictor space into high-dimensional rectangles, or boxes, for +simplicity and for ease of interpretation of the resulting predictive +model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the +MSE, given by + +$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ + +

+where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). + +

+









+ +

A top-down approach, recursive binary splitting

+ +

+Unfortunately, it is computationally infeasible to consider every +possible partition of the feature space into \( J \) boxes. The common +strategy is to take a top-down approach + +

+The approach is top-down because it begins at the top of the tree (all +observations belong to a single region) and then successively splits +the predictor space; each split is indicated via two new branches +further down on the tree. It is greedy because at each step of the +tree-building process, the best split is made at that particular step, +rather than looking ahead and picking a split that will lead to a +better tree in some future step. + +

+









+ +

Making a tree

+ +

+In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +$$ +\left\{X\vert x_j < s\right\}, +$$ + +and +$$ +\left\{X\vert x_j \geq s\right\}, +$$ + +so that we obtain the lowest MSE, that is +$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ + +

+which we want to minimize by considering all predictors +\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for +each predictor. These values could be determined by randomly assigned +numbers or by starting at the midpoint and then proceed till we find +an optimal value. + +

+For any \( j \) and \( s \), we define the pair of half-planes where +\( \overline{y}_{R_1} \) is the mean response for the training +observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean +response for the training observations in \( R_2(j,s) \). + +

+Finding the values of \( j \) and \( s \) that minimize the above equation can be +done quite quickly, especially when the number of features \( p \) is not +too large. + +

+Next, we repeat the process, looking +for the best predictor and best cutpoint in order to split the data +further so as to minimize the MSE within each of the resulting +regions. However, this time, instead of splitting the entire predictor +space, we split one of the two previously identified regions. We now +have three regions. Again, we look to split one of these three regions +further, so as to minimize the MSE. The process continues until a +stopping criterion is reached; for instance, we may continue until no +region contains more than five observations. + +

+ + +

Pruning the tree

+ +

+The above procedure is rather straightforward, but leads often to +overfitting and unnecessarily large and complicated trees. The basic +idea is to grow a large tree \( T_0 \) and then prune it back in order to +obtain a subtree. A smaller tree with fewer splits (fewer regions) can +lead to smaller variance and better interpretation at the cost of a +little more bias. + +

+The so-called Cost complexity pruning algorithm gives us a +way to do just this. Rather than considering every possible subtree, +we consider a sequence of trees indexed by a nonnegative tuning +parameter \( \alpha \). + +

+









+ +

Cost complexity pruning

+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ + +is as small as possible. Here \( \overline{T} \) is +the number of terminal nodes of the tree \( T \) , \( R_m \) is the +rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. + +

+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. + +

+It turns out that as we increase \( \alpha \) from zero +branches get pruned from the tree in a nested and predictable fashion, +so obtaining the whole sequence of subtrees as a function of \( \alpha \) is +easy. We can select a value of \( \alpha \) using a validation set or using +cross-validation. We then return to the full data set and obtain the +subtree corresponding to \( \alpha \). + +

+









+ +

Schematic Regression Procedure

+ +

+

+Building a Regression Tree. +

+ +

    +
  1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
  2. +
  3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
  4. +
  5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
  6. + +
      +
    • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
    • +
    • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
    • +
    • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
    • +
    + +
  7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
  8. +
+
+ + +

+









+ +

A Classification Tree

+ +

+A classification tree is very similar to a regression tree, except +that it is used to predict a qualitative response rather than a +quantitative one. Recall that for a regression tree, the predicted +response for an observation is given by the mean response of the +training observations that belong to the same terminal node. In +contrast, for a classification tree, we predict that each observation +belongs to the most commonly occurring class of training observations +in the region to which it belongs. In interpreting the results of a +classification tree, we are often interested not only in the class +prediction corresponding to a particular terminal node region, but +also in the class proportions among the training observations that +fall into that region. + +

+









+ +

Growing a classification tree

+ +

+The task of growing a +classification tree is quite similar to the task of growing a +regression tree. Just as in the regression setting, we use recursive +binary splitting to grow a classification tree. However, in the +classification setting, the MSE cannot be used as a criterion for making +the binary splits. A natural alternative to MSE is the classification +error rate. Since we plan to assign an observation in a given region +to the most commonly occurring error rate class of training +observations in that region, the classification error rate is simply +the fraction of the training observations in that region that do not +belong to the most common class. + +

+When building a classification tree, either the Gini index or the +entropy are typically used to evaluate the quality of a particular +split, since these two approaches are more sensitive to node purity +than is the classification error rate. + +

+









+ +

Classification tree, how to split nodes

+ +

+If our targets are the outcome of a classification process that takes +for example \( k=1,2,\dots,K \) values, the only thing we need to think of +is to set up the splitting criteria for each node. + +

+We define a PDF \( p_{mk} \) that represents the number of observations of +a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent +this likelihood function in terms of the proportion \( I(y_i=k) \) of +observations of this class in the region \( R_m \) as + +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). +$$ + +

+We let \( p_{mk} \) represent the majority class of observations in region +\( m \). The three most common ways of splitting a node are given by + +

    +
  • Misclassification error
  • +
+ +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +$$ + + +
    +
  • Gini index \( g \)
  • +
+ +$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ + + +
    +
  • Information entropy or just entropy \( s \)
  • +
+ +$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ + +

+









+ +

Visualizing the Tree, Classification

+

+ + +

import os
+from sklearn.datasets import load_breast_cancer
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.metrics import confusion_matrix
+from sklearn.tree import export_graphviz
+
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import pandas as pd
+import numpy as np
+
+
+cancer = load_breast_cancer()
+X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+print(X)
+y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
+y = pd.get_dummies(y)
+print(y)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/cancer.dot",
+    feature_names=cancer.feature_names,
+    class_names=cancer.target_names,
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+

+









+ +

Visualizing the Tree, The Moons

+

+ + +

# Common imports
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+from pydot import graph_from_dot_data
+import pandas as pd
+import os
+
+np.random.seed(42)
+X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
+X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/moons.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
+os.system(cmd)
+
+

+









+ +

Algorithms for Setting up Decision Trees

+ +

+Two algorithms stand out in the set up of decision trees: + +

    +
  1. The CART (Classification And Regression Tree) algorithm for both classification and regression
  2. +
  3. The ID3 algorithm based on the computation of the information gain for classification
  4. +
+ +We discuss both algorithms with applications here. The popular library +Scikit-Learn uses the CART algorithm. For classification problems +you can use either the gini index or the entropy to split a tree +in two branches. + +

+









+ +

The CART algorithm for Classification

+ +

+For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +This could be for example a threshold set by a number below a certain circumference of a malign tumor. + +

+How do we find these two quantities? +We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). +The cost function it tries to minimize is then +$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, +$$ + +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) + is the number of instances in the left/right subset + +

+Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the +\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other +hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), +\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). + +

+









+ +

The CART algorithm for Regression

+ +

+The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now +$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. +$$ + +Here the MSE for a specific node is defined as +$$ +\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, +$$ + +with +$$ +\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, +$$ + +the mean value of all observations in a specific node. + +

+Without any regularization, the regression task for decision trees, +just like for classification tasks, is prone to overfitting. + +

+









+ +

Computing the Gini index

+ +

+The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. + +

+The table here summarizes the various attributes and + + + + + + + + + + + + + + + + + + + + +
Day Outlook Temperature Humidity Wind Ride
1 Sunny Hot High Weak 0
2 Sunny Hot High Strong 1
3 Overcast Hot High Weak 1
4 Rain Mild High Weak 1
5 Rain Cool Normal Weak 1
6 Rain Cool Normal Strong 0
7 Overcast Cool Normal Strong 1
8 Sunny Mild High Weak 0
9 Sunny Cool Normal Weak 1
10 Rain Mild Normal Weak 1
11 Sunny Mild Normal Strong 1
12 Overcast Mild High Strong 1
13 Overcast Hot Normal Weak 1
14 Rain Mild High Strong 0
+

+









+ +

Simple Python Code to read in Data and perform Classification

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+    os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+    os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+    os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+    return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+    return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+    plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("rideclass.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
+ridedata = pd.DataFrame(ridedata)
+
+# Features and targets
+X = ridedata.loc[:, ridedata.columns != 'Ride'].values
+y = ridedata.loc[:, ridedata.columns == 'Ride'].values
+
+# Create the encoder.
+encoder = OneHotEncoder(handle_unknown="ignore")
+# Assume for simplicity all features are categorical.
+encoder.fit(X)    
+# Apply the encoder.
+X = encoder.transform(X)
+print(X)
+# Then do a Classification tree
+tree_clf = DecisionTreeClassifier(max_depth=2)
+tree_clf.fit(X, y)
+print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
+#transfer to a decision tree graph
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/ride.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+

+









+ +

Computing the Gini Factor

+ +

+The above functions (gini, entropy and misclassification error) are +important components of the so-called CART algorithm. We will discuss +this algorithm below after we have discussed the information gain +algorithm ID3. + +

+In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. + +

+ + +

# Split a dataset based on an attribute and an attribute value
+def test_split(index, value, dataset):
+	left, right = list(), list()
+	for row in dataset:
+		if row[index] < value:
+			left.append(row)
+		else:
+			right.append(row)
+	return left, right
+ 
+# Calculate the Gini index for a split dataset
+def gini_index(groups, classes):
+	# count all samples at split point
+	n_instances = float(sum([len(group) for group in groups]))
+	# sum weighted Gini index for each group
+	gini = 0.0
+	for group in groups:
+		size = float(len(group))
+		# avoid divide by zero
+		if size == 0:
+			continue
+		score = 0.0
+		# score the group based on the score for each class
+		for class_val in classes:
+			p = [row[-1] for row in group].count(class_val) / size
+			score += p * p
+		# weight the group score by its relative size
+		gini += (1.0 - score) * (size / n_instances)
+	return gini
+
+# Select the best split point for a dataset
+def get_split(dataset):
+	class_values = list(set(row[-1] for row in dataset))
+	b_index, b_value, b_score, b_groups = 999, 999, 999, None
+	for index in range(len(dataset[0])-1):
+		for row in dataset:
+			groups = test_split(index, row[index], dataset)
+			gini = gini_index(groups, class_values)
+			print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
+			if gini < b_score:
+				b_index, b_value, b_score, b_groups = index, row[index], gini, groups
+	return {'index':b_index, 'value':b_value, 'groups':b_groups}
+ 
+dataset = [[0,0,0,0,0],
+            [0,0,0,1,1],
+            [1,0,0,0,1],
+            [2,1,0,0,1],
+            [2,2,1,0,1],
+            [2,2,1,1,0],
+            [1,2,1,1,1],
+            [0,1,0,0,0],
+            [0,2,1,0,1],
+            [2,1,1,0,1],
+            [0,1,1,1,1],
+            [1,1,0,1,1],
+            [1,0,1,0,1],
+            [2,1,0,1,0]]
+
+split = get_split(dataset)
+print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
+
+

+









+ +

Entropy and the ID3 algorithm

+ +

+ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

    +
  1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
  2. +
  3. The best attribute is selected and used as the test at the root node of the tree.
  4. +
  5. A descendant of the root node is then created for each possible value of this attribute.
  6. +
  7. Training examples are sorted to the appropriate descendant node.
  8. +
  9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
  10. +
  11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
  12. +
+ +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

+We would like to select the attribute that is most useful for classifying +examples. + +

+What is a good quantitative measure of the worth of an attribute? + +

+Information gain measures how well a given attribute separates the +training examples according to their target classification. + +

+The ID3 algorithm uses this information gain measure to select among the candidate +attributes at each step while growing the tree. + +

+









+ +

Implementing the ID3 Algorithm

+ +

+ + +

import re
+import math
+from collections import deque
+
+# x is examples in training set
+# y is set of targets
+# label is target attributes
+# Node is a class which has properties values, childs, and next
+# root is top node in the decision tree
+
+class Node(object):
+	def __init__(self):
+		self.value = None
+		self.next = None
+		self.childs = None
+
+# Simple class of Decision Tree
+# Aimed for who want to learn Decision Tree, so it is not optimized
+class DecisionTree(object):
+	def __init__(self, sample, attributes, labels):
+		self.sample = sample
+		self.attributes = attributes
+		self.labels = labels
+		self.labelCodes = None
+		self.labelCodesCount = None
+		self.initLabelCodes()
+		# print(self.labelCodes)
+		self.root = None
+		self.entropy = self.getEntropy([x for x in range(len(self.labels))])
+
+	def initLabelCodes(self):
+		self.labelCodes = []
+		self.labelCodesCount = []
+		for l in self.labels:
+			if l not in self.labelCodes:
+				self.labelCodes.append(l)
+				self.labelCodesCount.append(0)
+			self.labelCodesCount[self.labelCodes.index(l)] += 1
+
+	def getLabelCodeId(self, sampleId):
+		return self.labelCodes.index(self.labels[sampleId])
+
+	def getAttributeValues(self, sampleIds, attributeId):
+		vals = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in vals:
+				vals.append(val)
+		# print(vals)
+		return vals
+
+	def getEntropy(self, sampleIds):
+		entropy = 0
+		labelCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCount[self.getLabelCodeId(sid)] += 1
+		# print("-ge", labelCount)
+		for lv in labelCount:
+			# print(lv)
+			if lv != 0:
+				entropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)
+			else:
+				entropy += 0
+		return entropy
+
+	def getDominantLabel(self, sampleIds):
+		labelCodesCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCodesCount[self.labelCodes.index(self.labels[sid])] += 1
+		return self.labelCodes[labelCodesCount.index(max(labelCodesCount))]
+
+	def getInformationGain(self, sampleIds, attributeId):
+		gain = self.getEntropy(sampleIds)
+		attributeVals = []
+		attributeValsCount = []
+		attributeValsIds = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in attributeVals:
+				attributeVals.append(val)
+				attributeValsCount.append(0)
+				attributeValsIds.append([])
+			vid = attributeVals.index(val)
+			attributeValsCount[vid] += 1
+			attributeValsIds[vid].append(sid)
+		# print("-gig", self.attributes[attributeId])
+		for vc, vids in zip(attributeValsCount, attributeValsIds):
+			# print("-gig", vids)
+			gain -= vc/len(sampleIds) * self.getEntropy(vids)
+		return gain
+
+	def getAttributeMaxInformationGain(self, sampleIds, attributeIds):
+		attributesEntropy = [0] * len(attributeIds)
+		for i, attId in zip(range(len(attributeIds)), attributeIds):
+			attributesEntropy[i] = self.getInformationGain(sampleIds, attId)
+		maxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]
+		return self.attributes[maxId], maxId
+
+	def isSingleLabeled(self, sampleIds):
+		label = self.labels[sampleIds[0]]
+		for sid in sampleIds:
+			if self.labels[sid] != label:
+				return False
+		return True
+
+	def getLabel(self, sampleId):
+		return self.labels[sampleId]
+
+	def id3(self):
+		sampleIds = [x for x in range(len(self.sample))]
+		attributeIds = [x for x in range(len(self.attributes))]
+		self.root = self.id3Recv(sampleIds, attributeIds, self.root)
+
+	def id3Recv(self, sampleIds, attributeIds, root):
+		root = Node() # Initialize current root
+		if self.isSingleLabeled(sampleIds):
+			root.value = self.labels[sampleIds[0]]
+			return root
+		# print(attributeIds)
+		if len(attributeIds) == 0:
+			root.value = self.getDominantLabel(sampleIds)
+			return root
+		bestAttrName, bestAttrId = self.getAttributeMaxInformationGain(
+			sampleIds, attributeIds)
+		# print(bestAttrName)
+		root.value = bestAttrName
+		root.childs = []  # Create list of children
+		for value in self.getAttributeValues(sampleIds, bestAttrId):
+			# print(value)
+			child = Node()
+			child.value = value
+			root.childs.append(child)  # Append new child node to current
+									   # root
+			childSampleIds = []
+			for sid in sampleIds:
+				if self.sample[sid][bestAttrId] == value:
+					childSampleIds.append(sid)
+			if len(childSampleIds) == 0:
+				child.next = self.getDominantLabel(sampleIds)
+			else:
+				# print(bestAttrName, bestAttrId)
+				# print(attributeIds)
+				if len(attributeIds) > 0 and bestAttrId in attributeIds:
+					toRemove = attributeIds.index(bestAttrId)
+					attributeIds.pop(toRemove)
+				child.next = self.id3Recv(
+					childSampleIds, attributeIds, child.next)
+		return root
+
+	def printTree(self):
+		if self.root:
+			roots = deque()
+			roots.append(self.root)
+			while len(roots) > 0:
+				root = roots.popleft()
+				print(root.value)
+				if root.childs:
+					for child in root.childs:
+						print('({})'.format(child.value))
+						roots.append(child.next)
+				elif root.next:
+					print(root.next)
+
+
+def test():
+	f = open('DataFiles/rideclass.csv')
+	attributes = f.readline().split(',')
+	attributes = attributes[1:len(attributes)-1]
+	print(attributes)
+	sample = f.readlines()
+	f.close()
+	for i in range(len(sample)):
+		sample[i] = re.sub('\d+,', '', sample[i])
+		sample[i] = sample[i].strip().split(',')
+	labels = []
+	for s in sample:
+		labels.append(s.pop())
+	# print(sample)
+	# print(labels)
+	decisionTree = DecisionTree(sample, attributes, labels)
+	print("System entropy {}".format(decisionTree.entropy))
+	decisionTree.id3()
+	decisionTree.printTree()
+
+
+if __name__ == '__main__':
+	test()
+
+

+









+ +

Cancer Data again now with Decision Trees and other Methods

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+

+









+ +

Another example, the moons again

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if not iris:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    if plot_training:
+        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+        plt.axis(axes)
+    if iris:
+        plt.xlabel("Petal length", fontsize=14)
+        plt.ylabel("Petal width", fontsize=14)
+    else:
+        plt.xlabel(r"$x_1$", fontsize=18)
+        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+    if legend:
+        plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+

+









+ +

Playing around with regions

+

+ + +

np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+
+

+









+ +

Regression trees

+

+ + +

# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+
+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+
+

+









+ +

Final regressor code

+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+    y_pred = tree_reg.predict(x1)
+    plt.axis(axes)
+    plt.xlabel("$x_1$", fontsize=18)
+    if ylabel:
+        plt.ylabel(ylabel, fontsize=18, rotation=0)
+    plt.plot(X, y, "b.")
+    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+

+ + +

tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+
+

+









+ +

Pros and cons of trees, pros

+ +
    +
  • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
  • +
  • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
  • +
  • No feature normalization needed
  • +
  • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
  • +
  • Can model nonlinear relationships
  • +
  • Can model interactions between the different descriptive features
  • +
  • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
  • +
+ +









+ +

Disadvantages

+ +
    +
  • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
  • +
  • If continuous features are used the tree may become quite large and hence less interpretable
  • +
  • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
  • +
  • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
  • +
  • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
  • +
  • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
  • +
  • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
  • +
+ +However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. + +

+









+ +

Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

+ +

+As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +

+This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct +forests and jungles of trees, homogeneous ones or heterogenous +ones. These methods are recognized by different names which we will +try to explain here. These are + +

    +
  1. Voting classifiers
  2. +
  3. Bagging and Pasting
  4. +
  5. Random forests
  6. +
  7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
  8. +
+ +We discuss these methods here. + +

+









+ +

An Overview of Ensemble Methods

+ +

+



+ +

+









+ +

Bagging

+ +

+The plain decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of \( n \) to \( p \) is moderately large. + +

+Bootstrap aggregation, or just bagging, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + +

+









+ +

More bagging

+ +

+Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +

+However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all \( B \) possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all \( B \) trees. + +

+









+ +

Simple Voting Example, head or tail

+

+ + +

heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+

+









+ +

Using the Voting Classifier

+

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+









+ +

Please, not the moons again! Voting and Bagging

+ +

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+ + +

log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+









+ +

Bagging Examples

+ +

+ + +

from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(random_state=42), n_estimators=500,
+    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+
+

+ + +

from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+
+

+ + +

tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+
+

+ + +

from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if contour:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+    plt.axis(axes)
+    plt.xlabel(r"$x_1$", fontsize=18)
+    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+
+

+









+ +

Making your own Bootstrap: Changing the Level of the Decision Tree

+ +

+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3) 
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+    model = DecisionTreeRegressor(max_depth=degree) 
+    y_pred = np.empty((y_test.shape[0], n_boostraps))
+    for i in range(n_boostraps):
+        x_, y_ = resample(X_train_scaled, y_train)
+        model.fit(x_, y_)
+        y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+    print('Polynomial degree:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE simple tree')
+plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week44/html/week44.html b/doc/pub/week44/html/week44.html new file mode 100644 index 000000000..033d19aa1 --- /dev/null +++ b/doc/pub/week44/html/week44.html @@ -0,0 +1,1840 @@ + + + + + + + + +week 44: From Decision Trees to Bagging methods + + + + + + + + + + + + + + + + + + + + + + + +

week 44: From Decision Trees to Bagging methods

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Decision trees, overarching aims

+ +

+We start here with the most basic algorithm, the so-called decision +tree. With this basic algorithm we can in turn build more complex +networks, spanning from homogeneous and heterogenous forests (bagging, +random forests and more) to one of the most popular supervised +algorithms nowadays, the extreme gradient boosting, or just +XGBoost. But let us start with the simplest possible ingredient. + +

+Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + +

+The main idea of decision trees +is to find those descriptive features which contain the most +information regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +

+The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the most +informative feature is done until we accomplish a stopping criteria +where we then finally end up in so called leaf nodes. + +

+A decision tree is typically divided into a root node, the interior nodes, +and the final leaf nodes or just leaves. These entities are then connected by so-called branches. + +

+The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +

+









+ +

A typical Decision Tree with its pertinent Jargon, Classification Problem

+ +

+



+ +

+This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using Scikit-Learn's decision tree classifier. Here we have used the so-called gini index (see below) to split the various branches. + +

+









+ +

General Features

+ +

+The overarching approach to decision trees is a top-down approach. + +

    +
  • A leaf provides the classification of a given instance.
  • +
  • A node specifies a test of some attribute of the instance.
  • +
  • A branch corresponds to a possible values of an attribute.
  • +
  • An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.
  • +
+ +This process is then repeated for the subtree rooted at the new +node. + +

+









+ +

How do we set it up?

+ +

+In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +

    +
  1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature
  2. +
  3. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process
  4. +
  5. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the predictions we want to make for new query instances
  6. +
  7. Show query instances to the tree and run down the tree until we arrive at leaf nodes
  8. +
+ +Then we are essentially done! + +

+









+ +

Decision trees and Regression

+

+ + +

import numpy as np
+import matplotlib.pyplot as plt
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.linear_model import LinearRegression
+
+steps=250
+
+distance=0
+x=0
+distance_list=[]
+steps_list=[]
+while x<steps:
+    distance+=np.random.randint(-1,2)
+    distance_list.append(distance)
+    x+=1
+    steps_list.append(x)
+plt.plot(steps_list,distance_list, color='green', label="Random Walk Data")
+
+steps_list=np.asarray(steps_list)
+distance_list=np.asarray(distance_list)
+
+X=steps_list[:,np.newaxis]
+
+#Polynomial fits
+
+#Degree 2
+poly_features=PolynomialFeatures(degree=2, include_bias=False)
+X_poly=poly_features.fit_transform(X)
+
+lin_reg=LinearRegression()
+poly_fit=lin_reg.fit(X_poly,distance_list)
+b=lin_reg.coef_
+c=lin_reg.intercept_
+print ("2nd degree coefficients:")
+print ("zero power: ",c)
+print ("first power: ", b[0])
+print ("second power: ",b[1])
+
+z = np.arange(0, steps, .01)
+z_mod=b[1]*z**2+b[0]*z+c
+
+fit_mod=b[1]*X**2+b[0]*X+c
+plt.plot(z, z_mod, color='r', label="2nd Degree Fit")
+plt.title("Polynomial Regression")
+
+plt.xlabel("Steps")
+plt.ylabel("Distance")
+
+#Degree 10
+poly_features10=PolynomialFeatures(degree=10, include_bias=False)
+X_poly10=poly_features10.fit_transform(X)
+
+poly_fit10=lin_reg.fit(X_poly10,distance_list)
+
+y_plot=poly_fit10.predict(X_poly10)
+plt.plot(X, y_plot, color='black', label="10th Degree Fit")
+
+plt.legend()
+plt.show()
+
+
+#Decision Tree Regression
+from sklearn.tree import DecisionTreeRegressor
+regr_1=DecisionTreeRegressor(max_depth=2)
+regr_2=DecisionTreeRegressor(max_depth=5)
+regr_3=DecisionTreeRegressor(max_depth=7)
+regr_1.fit(X, distance_list)
+regr_2.fit(X, distance_list)
+regr_3.fit(X, distance_list)
+
+X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]
+y_1 = regr_1.predict(X_test)
+y_2 = regr_2.predict(X_test)
+y_3=regr_3.predict(X_test)
+
+# Plot the results
+plt.figure()
+plt.scatter(X, distance_list, s=2.5, c="black", label="data")
+plt.plot(X_test, y_1, color="red",
+         label="max_depth=2", linewidth=2)
+plt.plot(X_test, y_2, color="green", label="max_depth=5", linewidth=2)
+plt.plot(X_test, y_3, color="m", label="max_depth=7", linewidth=2)
+
+plt.xlabel("Data")
+plt.ylabel("Darget")
+plt.title("Decision Tree Regression")
+plt.legend()
+plt.show()
+
+

+









+ +

Building a tree, regression

+ +

+There are mainly two steps + +

    +
  1. We split the predictor space (the set of possible values \( x_1,x_2,\dots, x_p \)) into \( J \) distinct and non-non-overlapping regions, \( R_1,R_2,\dots,R_J \).
  2. +
  3. For every observation that falls into the region \( R_j \) , we make the same prediction, which is simply the mean of the response values for the training observations in \( R_j \).
  4. +
+ +How do we construct the regions \( R_1,\dots,R_J \)? In theory, the +regions could have any shape. However, we choose to divide the +predictor space into high-dimensional rectangles, or boxes, for +simplicity and for ease of interpretation of the resulting predictive +model. The goal is to find boxes \( R_1,\dots,R_J \) that minimize the +MSE, given by + +$$ +\sum_{j=1}^J\sum_{i\in R_j}(y_i-\overline{y}_{R_j})^2, +$$ + +

+where \( \overline{y}_{R_j} \) is the mean response for the training observations +within box \( j \). + +

+









+ +

A top-down approach, recursive binary splitting

+ +

+Unfortunately, it is computationally infeasible to consider every +possible partition of the feature space into \( J \) boxes. The common +strategy is to take a top-down approach + +

+The approach is top-down because it begins at the top of the tree (all +observations belong to a single region) and then successively splits +the predictor space; each split is indicated via two new branches +further down on the tree. It is greedy because at each step of the +tree-building process, the best split is made at that particular step, +rather than looking ahead and picking a split that will lead to a +better tree in some future step. + +

+









+ +

Making a tree

+ +

+In order to implement the recursive binary splitting we start by selecting +the predictor \( x_j \) and a cutpoint \( s \) that splits the predictor space into two regions \( R_1 \) and \( R_2 \) +$$ +\left\{X\vert x_j < s\right\}, +$$ + +and +$$ +\left\{X\vert x_j \geq s\right\}, +$$ + +so that we obtain the lowest MSE, that is +$$ +\sum_{i:x_i\in R_j}(y_i-\overline{y}_{R_1})^2+\sum_{i:x_i\in R_2}(y_i-\overline{y}_{R_2})^2, +$$ + +

+which we want to minimize by considering all predictors +\( x_1,x_2,\dots,x_p \). We consider also all possible values of \( s \) for +each predictor. These values could be determined by randomly assigned +numbers or by starting at the midpoint and then proceed till we find +an optimal value. + +

+For any \( j \) and \( s \), we define the pair of half-planes where +\( \overline{y}_{R_1} \) is the mean response for the training +observations in \( R_1(j,s) \), and \( \overline{y}_{R_2} \) is the mean +response for the training observations in \( R_2(j,s) \). + +

+Finding the values of \( j \) and \( s \) that minimize the above equation can be +done quite quickly, especially when the number of features \( p \) is not +too large. + +

+Next, we repeat the process, looking +for the best predictor and best cutpoint in order to split the data +further so as to minimize the MSE within each of the resulting +regions. However, this time, instead of splitting the entire predictor +space, we split one of the two previously identified regions. We now +have three regions. Again, we look to split one of these three regions +further, so as to minimize the MSE. The process continues until a +stopping criterion is reached; for instance, we may continue until no +region contains more than five observations. + +

+ + +

Pruning the tree

+ +

+The above procedure is rather straightforward, but leads often to +overfitting and unnecessarily large and complicated trees. The basic +idea is to grow a large tree \( T_0 \) and then prune it back in order to +obtain a subtree. A smaller tree with fewer splits (fewer regions) can +lead to smaller variance and better interpretation at the cost of a +little more bias. + +

+The so-called Cost complexity pruning algorithm gives us a +way to do just this. Rather than considering every possible subtree, +we consider a sequence of trees indexed by a nonnegative tuning +parameter \( \alpha \). + +

+









+ +

Cost complexity pruning

+For each value of \( \alpha \) there corresponds a subtree \( T \in T_0 \) such that +$$ +\sum_{m=1}^{\overline{T}}\sum_{i:x_i\in R_m}(y_i-\overline{y}_{R_m})^2+\alpha\overline{T}, +$$ + +is as small as possible. Here \( \overline{T} \) is +the number of terminal nodes of the tree \( T \) , \( R_m \) is the +rectangle (i.e. the subset of predictor space) corresponding to the \( m \)-th terminal node. + +

+The tuning parameter \( \alpha \) controls a trade-off between the subtree’s +com- plexity and its fit to the training data. When \( \alpha = 0 \), then the +subtree \( T \) will simply equal \( T_0 \), +because then the above equation just measures the +training error. +However, as \( \alpha \) increases, there is a price to pay for +having a tree with many terminal nodes. The above equation will +tend to be minimized for a smaller subtree. + +

+It turns out that as we increase \( \alpha \) from zero +branches get pruned from the tree in a nested and predictable fashion, +so obtaining the whole sequence of subtrees as a function of \( \alpha \) is +easy. We can select a value of \( \alpha \) using a validation set or using +cross-validation. We then return to the full data set and obtain the +subtree corresponding to \( \alpha \). + +

+









+ +

Schematic Regression Procedure

+ +

+

+Building a Regression Tree. +

+ +

    +
  1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.
  2. +
  3. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of \( \alpha \).
  4. +
  5. Use for example \( K \)-fold cross-validation to choose \( \alpha \). Divide the training observations into \( K \) folds. For each \( k=1,2,\dots,K \) we:
  6. + +
      +
    • repeat steps 1 and 2 on all but the \( k \)-th fold of the training data.
    • +
    • Then we valuate the mean squared prediction error on the data in the left-out \( k \)-th fold, as a function of \( \alpha \).
    • +
    • Finally we average the results for each value of \( \alpha \), and pick \( \alpha \) to minimize the average error.
    • +
    + +
  7. Return the subtree from Step 2 that corresponds to the chosen value of \( \alpha \).
  8. +
+
+ + +

+









+ +

A Classification Tree

+ +

+A classification tree is very similar to a regression tree, except +that it is used to predict a qualitative response rather than a +quantitative one. Recall that for a regression tree, the predicted +response for an observation is given by the mean response of the +training observations that belong to the same terminal node. In +contrast, for a classification tree, we predict that each observation +belongs to the most commonly occurring class of training observations +in the region to which it belongs. In interpreting the results of a +classification tree, we are often interested not only in the class +prediction corresponding to a particular terminal node region, but +also in the class proportions among the training observations that +fall into that region. + +

+









+ +

Growing a classification tree

+ +

+The task of growing a +classification tree is quite similar to the task of growing a +regression tree. Just as in the regression setting, we use recursive +binary splitting to grow a classification tree. However, in the +classification setting, the MSE cannot be used as a criterion for making +the binary splits. A natural alternative to MSE is the classification +error rate. Since we plan to assign an observation in a given region +to the most commonly occurring error rate class of training +observations in that region, the classification error rate is simply +the fraction of the training observations in that region that do not +belong to the most common class. + +

+When building a classification tree, either the Gini index or the +entropy are typically used to evaluate the quality of a particular +split, since these two approaches are more sensitive to node purity +than is the classification error rate. + +

+









+ +

Classification tree, how to split nodes

+ +

+If our targets are the outcome of a classification process that takes +for example \( k=1,2,\dots,K \) values, the only thing we need to think of +is to set up the splitting criteria for each node. + +

+We define a PDF \( p_{mk} \) that represents the number of observations of +a class \( k \) in a region \( R_m \) with \( N_m \) observations. We represent +this likelihood function in terms of the proportion \( I(y_i=k) \) of +observations of this class in the region \( R_m \) as + +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i=k). +$$ + +

+We let \( p_{mk} \) represent the majority class of observations in region +\( m \). The three most common ways of splitting a node are given by + +

    +
  • Misclassification error
  • +
+ +$$ +p_{mk} = \frac{1}{N_m}\sum_{x_i\in R_m}I(y_i\ne k) = 1-p_{mk}. +$$ + + +
    +
  • Gini index \( g \)
  • +
+ +$$ +g = \sum_{k=1}^K p_{mk}(1-p_{mk}). +$$ + + +
    +
  • Information entropy or just entropy \( s \)
  • +
+ +$$ +s = -\sum_{k=1}^K p_{mk}\log{p_{mk}}. +$$ + +

+









+ +

Visualizing the Tree, Classification

+

+ + +

import os
+from sklearn.datasets import load_breast_cancer
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.metrics import confusion_matrix
+from sklearn.tree import export_graphviz
+
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import pandas as pd
+import numpy as np
+
+
+cancer = load_breast_cancer()
+X = pd.DataFrame(cancer.data, columns=cancer.feature_names)
+print(X)
+y = pd.Categorical.from_codes(cancer.target, cancer.target_names)
+y = pd.get_dummies(y)
+print(y)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/cancer.dot",
+    feature_names=cancer.feature_names,
+    class_names=cancer.target_names,
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+

+









+ +

Visualizing the Tree, The Moons

+

+ + +

# Common imports
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+from pydot import graph_from_dot_data
+import pandas as pd
+import os
+
+np.random.seed(42)
+X, y = make_moons(n_samples=100, noise=0.25, random_state=53)
+X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)
+tree_clf = DecisionTreeClassifier(max_depth=5)
+tree_clf.fit(X_train, y_train)
+
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/moons.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'
+os.system(cmd)
+
+

+









+ +

Algorithms for Setting up Decision Trees

+ +

+Two algorithms stand out in the set up of decision trees: + +

    +
  1. The CART (Classification And Regression Tree) algorithm for both classification and regression
  2. +
  3. The ID3 algorithm based on the computation of the information gain for classification
  4. +
+ +We discuss both algorithms with applications here. The popular library +Scikit-Learn uses the CART algorithm. For classification problems +you can use either the gini index or the entropy to split a tree +in two branches. + +

+









+ +

The CART algorithm for Classification

+ +

+For classification, the CART algorithm splits the data set in two subsets using a single feature \( k \) and a threshold \( t_k \). +This could be for example a threshold set by a number below a certain circumference of a malign tumor. + +

+How do we find these two quantities? +We search for the pair \( (k,t_k) \) that produces the purest subset using for example the gini factor \( G \). +The cost function it tries to minimize is then +$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}G_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}G_{\mathrm{right}}, +$$ + +where \( G_{\mathrm{left/right}} \) measures the impurity of the left/right subset and \( m_{\mathrm{left/right}} \) + is the number of instances in the left/right subset + +

+Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets +and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the +\( max\_depth \) hyperparameter), or if it cannot find a split that will reduce impurity. A few other +hyperparameters control additional stopping conditions such as the \( min\_samples\_split \), +\( min\_samples\_leaf \), \( min\_weight\_fraction\_leaf \), and \( max\_leaf\_nodes \). + +

+









+ +

The CART algorithm for Regression

+ +

+The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the +training set in a way that minimizes say the gini or entropy impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now +$$ +C(k,t_k) = \frac{m_{\mathrm{left}}}{m}\mathrm{MSE}_{\mathrm{left}}+ \frac{m_{\mathrm{right}}}{m}\mathrm{MSE}_{\mathrm{right}}. +$$ + +Here the MSE for a specific node is defined as +$$ +\mathrm{MSE}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}(\overline{y}_{\mathrm{node}}-y_i)^2, +$$ + +with +$$ +\overline{y}_{\mathrm{node}}=\frac{1}{m_\mathrm{node}}\sum_{i\in \mathrm{node}}y_i, +$$ + +the mean value of all observations in a specific node. + +

+Without any regularization, the regression task for decision trees, +just like for classification tasks, is prone to overfitting. + +

+









+ +

Computing the Gini index

+ +

+The example we will look at is a classical one in many Machine +Learning applications. Based on various meteorological features, we +have several so-called attributes which decide whether we at the end +will do some outdoor activity like skiing, going for a bike ride etc +etc. The table here contains the feautures outlook, temperature, +humidity and wind. The target or output is whether we ride +(True=1) or whether we do something else that day (False=0). The +attributes for each feature are then sunny, overcast and rain for the +outlook, hot, cold and mild for temperature, high and normal for +humidity and weak and strong for wind. + +

+The table here summarizes the various attributes and + + + + + + + + + + + + + + + + + + + + +
Day Outlook Temperature Humidity Wind Ride
1 Sunny Hot High Weak 0
2 Sunny Hot High Strong 1
3 Overcast Hot High Weak 1
4 Rain Mild High Weak 1
5 Rain Cool Normal Weak 1
6 Rain Cool Normal Strong 0
7 Overcast Cool Normal Strong 1
8 Sunny Mild High Weak 0
9 Sunny Cool Normal Weak 1
10 Rain Mild Normal Weak 1
11 Sunny Mild Normal Strong 1
12 Overcast Mild High Strong 1
13 Overcast Hot Normal Weak 1
14 Rain Mild High Strong 0
+

+









+ +

Simple Python Code to read in Data and perform Classification

+ +

+ + +

# Common imports
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image 
+from pydot import graph_from_dot_data
+import os
+
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
+
+if not os.path.exists(PROJECT_ROOT_DIR):
+    os.mkdir(PROJECT_ROOT_DIR)
+
+if not os.path.exists(FIGURE_ID):
+    os.makedirs(FIGURE_ID)
+
+if not os.path.exists(DATA_ID):
+    os.makedirs(DATA_ID)
+
+def image_path(fig_id):
+    return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+    return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+    plt.savefig(image_path(fig_id) + ".png", format='png')
+
+infile = open(data_path("rideclass.csv"),'r')
+
+# Read the experimental data with Pandas
+from IPython.display import display
+ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))
+ridedata = pd.DataFrame(ridedata)
+
+# Features and targets
+X = ridedata.loc[:, ridedata.columns != 'Ride'].values
+y = ridedata.loc[:, ridedata.columns == 'Ride'].values
+
+# Create the encoder.
+encoder = OneHotEncoder(handle_unknown="ignore")
+# Assume for simplicity all features are categorical.
+encoder.fit(X)    
+# Apply the encoder.
+X = encoder.transform(X)
+print(X)
+# Then do a Classification tree
+tree_clf = DecisionTreeClassifier(max_depth=2)
+tree_clf.fit(X, y)
+print("Train set accuracy with Decision Tree: {:.2f}".format(tree_clf.score(X,y)))
+#transfer to a decision tree graph
+export_graphviz(
+    tree_clf,
+    out_file="DataFiles/ride.dot",
+    rounded=True,
+    filled=True
+)
+cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'
+os.system(cmd)
+
+

+









+ +

Computing the Gini Factor

+ +

+The above functions (gini, entropy and misclassification error) are +important components of the so-called CART algorithm. We will discuss +this algorithm below after we have discussed the information gain +algorithm ID3. + +

+In the example here we have converted all our attributes into numerical values \( 0,1,2 \) etc. + +

+ + +

# Split a dataset based on an attribute and an attribute value
+def test_split(index, value, dataset):
+	left, right = list(), list()
+	for row in dataset:
+		if row[index] < value:
+			left.append(row)
+		else:
+			right.append(row)
+	return left, right
+ 
+# Calculate the Gini index for a split dataset
+def gini_index(groups, classes):
+	# count all samples at split point
+	n_instances = float(sum([len(group) for group in groups]))
+	# sum weighted Gini index for each group
+	gini = 0.0
+	for group in groups:
+		size = float(len(group))
+		# avoid divide by zero
+		if size == 0:
+			continue
+		score = 0.0
+		# score the group based on the score for each class
+		for class_val in classes:
+			p = [row[-1] for row in group].count(class_val) / size
+			score += p * p
+		# weight the group score by its relative size
+		gini += (1.0 - score) * (size / n_instances)
+	return gini
+
+# Select the best split point for a dataset
+def get_split(dataset):
+	class_values = list(set(row[-1] for row in dataset))
+	b_index, b_value, b_score, b_groups = 999, 999, 999, None
+	for index in range(len(dataset[0])-1):
+		for row in dataset:
+			groups = test_split(index, row[index], dataset)
+			gini = gini_index(groups, class_values)
+			print('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))
+			if gini < b_score:
+				b_index, b_value, b_score, b_groups = index, row[index], gini, groups
+	return {'index':b_index, 'value':b_value, 'groups':b_groups}
+ 
+dataset = [[0,0,0,0,0],
+            [0,0,0,1,1],
+            [1,0,0,0,1],
+            [2,1,0,0,1],
+            [2,2,1,0,1],
+            [2,2,1,1,0],
+            [1,2,1,1,1],
+            [0,1,0,0,0],
+            [0,2,1,0,1],
+            [2,1,1,0,1],
+            [0,1,1,1,1],
+            [1,1,0,1,1],
+            [1,0,1,0,1],
+            [2,1,0,1,0]]
+
+split = get_split(dataset)
+print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))
+
+

+









+ +

Entropy and the ID3 algorithm

+ +

+ID3, learns decision trees by constructing +them topdown, beginning with the question which attribute should be tested at the root of the tree? + +

    +
  1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.
  2. +
  3. The best attribute is selected and used as the test at the root node of the tree.
  4. +
  5. A descendant of the root node is then created for each possible value of this attribute.
  6. +
  7. Training examples are sorted to the appropriate descendant node.
  8. +
  9. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.
  10. +
  11. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices.
  12. +
+ +The ID3 algorithm selects, which attribute to test at each node in the +tree. + +

+We would like to select the attribute that is most useful for classifying +examples. + +

+What is a good quantitative measure of the worth of an attribute? + +

+Information gain measures how well a given attribute separates the +training examples according to their target classification. + +

+The ID3 algorithm uses this information gain measure to select among the candidate +attributes at each step while growing the tree. + +

+









+ +

Implementing the ID3 Algorithm

+ +

+ + +

import re
+import math
+from collections import deque
+
+# x is examples in training set
+# y is set of targets
+# label is target attributes
+# Node is a class which has properties values, childs, and next
+# root is top node in the decision tree
+
+class Node(object):
+	def __init__(self):
+		self.value = None
+		self.next = None
+		self.childs = None
+
+# Simple class of Decision Tree
+# Aimed for who want to learn Decision Tree, so it is not optimized
+class DecisionTree(object):
+	def __init__(self, sample, attributes, labels):
+		self.sample = sample
+		self.attributes = attributes
+		self.labels = labels
+		self.labelCodes = None
+		self.labelCodesCount = None
+		self.initLabelCodes()
+		# print(self.labelCodes)
+		self.root = None
+		self.entropy = self.getEntropy([x for x in range(len(self.labels))])
+
+	def initLabelCodes(self):
+		self.labelCodes = []
+		self.labelCodesCount = []
+		for l in self.labels:
+			if l not in self.labelCodes:
+				self.labelCodes.append(l)
+				self.labelCodesCount.append(0)
+			self.labelCodesCount[self.labelCodes.index(l)] += 1
+
+	def getLabelCodeId(self, sampleId):
+		return self.labelCodes.index(self.labels[sampleId])
+
+	def getAttributeValues(self, sampleIds, attributeId):
+		vals = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in vals:
+				vals.append(val)
+		# print(vals)
+		return vals
+
+	def getEntropy(self, sampleIds):
+		entropy = 0
+		labelCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCount[self.getLabelCodeId(sid)] += 1
+		# print("-ge", labelCount)
+		for lv in labelCount:
+			# print(lv)
+			if lv != 0:
+				entropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)
+			else:
+				entropy += 0
+		return entropy
+
+	def getDominantLabel(self, sampleIds):
+		labelCodesCount = [0] * len(self.labelCodes)
+		for sid in sampleIds:
+			labelCodesCount[self.labelCodes.index(self.labels[sid])] += 1
+		return self.labelCodes[labelCodesCount.index(max(labelCodesCount))]
+
+	def getInformationGain(self, sampleIds, attributeId):
+		gain = self.getEntropy(sampleIds)
+		attributeVals = []
+		attributeValsCount = []
+		attributeValsIds = []
+		for sid in sampleIds:
+			val = self.sample[sid][attributeId]
+			if val not in attributeVals:
+				attributeVals.append(val)
+				attributeValsCount.append(0)
+				attributeValsIds.append([])
+			vid = attributeVals.index(val)
+			attributeValsCount[vid] += 1
+			attributeValsIds[vid].append(sid)
+		# print("-gig", self.attributes[attributeId])
+		for vc, vids in zip(attributeValsCount, attributeValsIds):
+			# print("-gig", vids)
+			gain -= vc/len(sampleIds) * self.getEntropy(vids)
+		return gain
+
+	def getAttributeMaxInformationGain(self, sampleIds, attributeIds):
+		attributesEntropy = [0] * len(attributeIds)
+		for i, attId in zip(range(len(attributeIds)), attributeIds):
+			attributesEntropy[i] = self.getInformationGain(sampleIds, attId)
+		maxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]
+		return self.attributes[maxId], maxId
+
+	def isSingleLabeled(self, sampleIds):
+		label = self.labels[sampleIds[0]]
+		for sid in sampleIds:
+			if self.labels[sid] != label:
+				return False
+		return True
+
+	def getLabel(self, sampleId):
+		return self.labels[sampleId]
+
+	def id3(self):
+		sampleIds = [x for x in range(len(self.sample))]
+		attributeIds = [x for x in range(len(self.attributes))]
+		self.root = self.id3Recv(sampleIds, attributeIds, self.root)
+
+	def id3Recv(self, sampleIds, attributeIds, root):
+		root = Node() # Initialize current root
+		if self.isSingleLabeled(sampleIds):
+			root.value = self.labels[sampleIds[0]]
+			return root
+		# print(attributeIds)
+		if len(attributeIds) == 0:
+			root.value = self.getDominantLabel(sampleIds)
+			return root
+		bestAttrName, bestAttrId = self.getAttributeMaxInformationGain(
+			sampleIds, attributeIds)
+		# print(bestAttrName)
+		root.value = bestAttrName
+		root.childs = []  # Create list of children
+		for value in self.getAttributeValues(sampleIds, bestAttrId):
+			# print(value)
+			child = Node()
+			child.value = value
+			root.childs.append(child)  # Append new child node to current
+									   # root
+			childSampleIds = []
+			for sid in sampleIds:
+				if self.sample[sid][bestAttrId] == value:
+					childSampleIds.append(sid)
+			if len(childSampleIds) == 0:
+				child.next = self.getDominantLabel(sampleIds)
+			else:
+				# print(bestAttrName, bestAttrId)
+				# print(attributeIds)
+				if len(attributeIds) > 0 and bestAttrId in attributeIds:
+					toRemove = attributeIds.index(bestAttrId)
+					attributeIds.pop(toRemove)
+				child.next = self.id3Recv(
+					childSampleIds, attributeIds, child.next)
+		return root
+
+	def printTree(self):
+		if self.root:
+			roots = deque()
+			roots.append(self.root)
+			while len(roots) > 0:
+				root = roots.popleft()
+				print(root.value)
+				if root.childs:
+					for child in root.childs:
+						print('({})'.format(child.value))
+						roots.append(child.next)
+				elif root.next:
+					print(root.next)
+
+
+def test():
+	f = open('DataFiles/rideclass.csv')
+	attributes = f.readline().split(',')
+	attributes = attributes[1:len(attributes)-1]
+	print(attributes)
+	sample = f.readlines()
+	f.close()
+	for i in range(len(sample)):
+		sample[i] = re.sub('\d+,', '', sample[i])
+		sample[i] = sample[i].strip().split(',')
+	labels = []
+	for s in sample:
+		labels.append(s.pop())
+	# print(sample)
+	# print(labels)
+	decisionTree = DecisionTree(sample, attributes, labels)
+	print("System entropy {}".format(decisionTree.entropy))
+	decisionTree.id3()
+	decisionTree.printTree()
+
+
+if __name__ == '__main__':
+	test()
+
+

+









+ +

Cancer Data again now with Decision Trees and other Methods

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+

+









+ +

Another example, the moons again

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+# Common imports
+import numpy as np
+import os
+
+# to make this notebook's output stable across runs
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.datasets import make_moons
+from sklearn.tree import export_graphviz
+
+Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)
+
+deep_tree_clf1 = DecisionTreeClassifier(random_state=42)
+deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)
+deep_tree_clf1.fit(Xm, ym)
+deep_tree_clf2.fit(Xm, ym)
+
+
+def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if not iris:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    if plot_training:
+        plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", label="Iris-Setosa")
+        plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", label="Iris-Versicolor")
+        plt.plot(X[:, 0][y==2], X[:, 1][y==2], "g^", label="Iris-Virginica")
+        plt.axis(axes)
+    if iris:
+        plt.xlabel("Petal length", fontsize=14)
+        plt.ylabel("Petal width", fontsize=14)
+    else:
+        plt.xlabel(r"$x_1$", fontsize=18)
+        plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+    if legend:
+        plt.legend(loc="lower right", fontsize=14)
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("No restrictions", fontsize=16)
+plt.subplot(122)
+plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)
+plt.title("min_samples_leaf = {}".format(deep_tree_clf2.min_samples_leaf), fontsize=14)
+plt.show()
+
+

+









+ +

Playing around with regions

+

+ + +

np.random.seed(6)
+Xs = np.random.rand(100, 2) - 0.5
+ys = (Xs[:, 0] > 0).astype(np.float32) * 2
+
+angle = np.pi/4
+rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
+Xsr = Xs.dot(rotation_matrix)
+
+tree_clf_s = DecisionTreeClassifier(random_state=42)
+tree_clf_s.fit(Xs, ys)
+tree_clf_sr = DecisionTreeClassifier(random_state=42)
+tree_clf_sr.fit(Xsr, ys)
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+plt.subplot(122)
+plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)
+
+plt.show()
+
+

+









+ +

Regression trees

+

+ + +

# Quadratic training set + noise
+np.random.seed(42)
+m = 200
+X = np.random.rand(m, 1)
+y = 4 * (X - 0.5) ** 2
+y = y + np.random.randn(m, 1) / 10
+
+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)
+tree_reg.fit(X, y)
+
+

+









+ +

Final regressor code

+

+ + +

from sklearn.tree import DecisionTreeRegressor
+
+tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)
+tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"):
+    x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)
+    y_pred = tree_reg.predict(x1)
+    plt.axis(axes)
+    plt.xlabel("$x_1$", fontsize=18)
+    if ylabel:
+        plt.ylabel(ylabel, fontsize=18, rotation=0)
+    plt.plot(X, y, "b.")
+    plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$")
+
+plt.figure(figsize=(11, 4))
+plt.subplot(121)
+plot_regression_predictions(tree_reg1, X, y)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+plt.text(0.21, 0.65, "Depth=0", fontsize=15)
+plt.text(0.01, 0.2, "Depth=1", fontsize=13)
+plt.text(0.65, 0.8, "Depth=1", fontsize=13)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("max_depth=2", fontsize=14)
+
+plt.subplot(122)
+plot_regression_predictions(tree_reg2, X, y, ylabel=None)
+for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")):
+    plt.plot([split, split], [-0.2, 1], style, linewidth=2)
+for split in (0.0458, 0.1298, 0.2873, 0.9040):
+    plt.plot([split, split], [-0.2, 1], "k:", linewidth=1)
+plt.text(0.3, 0.5, "Depth=2", fontsize=13)
+plt.title("max_depth=3", fontsize=14)
+
+plt.show()
+
+

+ + +

tree_reg1 = DecisionTreeRegressor(random_state=42)
+tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)
+tree_reg1.fit(X, y)
+tree_reg2.fit(X, y)
+
+x1 = np.linspace(0, 1, 500).reshape(-1, 1)
+y_pred1 = tree_reg1.predict(x1)
+y_pred2 = tree_reg2.predict(x1)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.ylabel("$y$", fontsize=18, rotation=0)
+plt.legend(loc="upper center", fontsize=18)
+plt.title("No restrictions", fontsize=14)
+
+plt.subplot(122)
+plt.plot(X, y, "b.")
+plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$")
+plt.axis([0, 1, -0.2, 1.1])
+plt.xlabel("$x_1$", fontsize=18)
+plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14)
+
+plt.show()
+
+

+









+ +

Pros and cons of trees, pros

+ +
    +
  • White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)
  • +
  • Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!
  • +
  • No feature normalization needed
  • +
  • Tree models can handle both continuous and categorical data (Classification and Regression Trees)
  • +
  • Can model nonlinear relationships
  • +
  • Can model interactions between the different descriptive features
  • +
  • Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)
  • +
+ +









+ +

Disadvantages

+ +
    +
  • Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches
  • +
  • If continuous features are used the tree may become quite large and hence less interpretable
  • +
  • Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented
  • +
  • Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests
  • +
  • Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones.
  • +
  • If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data
  • +
  • Features with many levels may be preferred over features with less levels since for them it is more easy to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain
  • +
+ +However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. + +

+









+ +

Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods

+ +

+As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +

+This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct +forests and jungles of trees, homogeneous ones or heterogenous +ones. These methods are recognized by different names which we will +try to explain here. These are + +

    +
  1. Voting classifiers
  2. +
  3. Bagging and Pasting
  4. +
  5. Random forests
  6. +
  7. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)
  8. +
+ +We discuss these methods here. + +

+









+ +

An Overview of Ensemble Methods

+ +

+



+ +

+









+ +

Bagging

+ +

+The plain decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of \( n \) to \( p \) is moderately large. + +

+Bootstrap aggregation, or just bagging, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + +

+









+ +

More bagging

+ +

+Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +

+However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all \( B \) possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all \( B \) trees. + +

+









+ +

Simple Voting Example, head or tail

+

+ + +

heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
+plt.show()
+
+

+









+ +

Using the Voting Classifier

+

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+









+ +

Please, not the moons again! Voting and Bagging

+ +

+ + +

from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='hard')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+ + +

log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+    voting='soft')
+voting_clf.fit(X_train, y_train)
+
+

+ + +

from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+    clf.fit(X_train, y_train)
+    y_pred = clf.predict(X_test)
+    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+

+









+ +

Bagging Examples

+ +

+ + +

from sklearn.ensemble import BaggingClassifier
+from sklearn.tree import DecisionTreeClassifier
+
+bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(random_state=42), n_estimators=500,
+    max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
+bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+
+

+ + +

from sklearn.metrics import accuracy_score
+print(accuracy_score(y_test, y_pred))
+
+

+ + +

tree_clf = DecisionTreeClassifier(random_state=42)
+tree_clf.fit(X_train, y_train)
+y_pred_tree = tree_clf.predict(X_test)
+print(accuracy_score(y_test, y_pred_tree))
+
+

+ + +

from matplotlib.colors import ListedColormap
+
+def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
+    x1s = np.linspace(axes[0], axes[1], 100)
+    x2s = np.linspace(axes[2], axes[3], 100)
+    x1, x2 = np.meshgrid(x1s, x2s)
+    X_new = np.c_[x1.ravel(), x2.ravel()]
+    y_pred = clf.predict(X_new).reshape(x1.shape)
+    custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
+    plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
+    if contour:
+        custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
+        plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
+    plt.axis(axes)
+    plt.xlabel(r"$x_1$", fontsize=18)
+    plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
+plt.figure(figsize=(11,4))
+plt.subplot(121)
+plot_decision_boundary(tree_clf, X, y)
+plt.title("Decision Tree", fontsize=14)
+plt.subplot(122)
+plot_decision_boundary(bag_clf, X, y)
+plt.title("Decision Trees with Bagging", fontsize=14)
+save_fig("baggingtree")
+plt.show()
+
+

+









+ +

Making your own Bootstrap: Changing the Level of the Decision Tree

+ +

+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 100
+n_boostraps = 100
+maxdepth = 8
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+# we produce a simple tree first as benchmark
+simpletree = DecisionTreeRegressor(max_depth=3) 
+simpletree.fit(X_train_scaled, y_train)
+simpleprediction = simpletree.predict(X_test_scaled)
+for degree in range(1,maxdepth):
+    model = DecisionTreeRegressor(max_depth=degree) 
+    y_pred = np.empty((y_test.shape[0], n_boostraps))
+    for i in range(n_boostraps):
+        x_, y_ = resample(X_train_scaled, y_train)
+        model.fit(x_, y_)
+        y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+    print('Polynomial degree:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE simple tree')
+plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
+plt.show()
+
+

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz b/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz new file mode 100644 index 000000000..879300629 Binary files /dev/null and b/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz differ diff --git a/doc/pub/week44/ipynb/week44.ipynb b/doc/pub/week44/ipynb/week44.ipynb new file mode 100644 index 000000000..63f28b0fa --- /dev/null +++ b/doc/pub/week44/ipynb/week44.ipynb @@ -0,0 +1,1914 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# week 44: From Decision Trees to Bagging methods\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "\n", + "## Decision trees, overarching aims\n", + "\n", + "\n", + "We start here with the most basic algorithm, the so-called decision\n", + "tree. With this basic algorithm we can in turn build more complex\n", + "networks, spanning from homogeneous and heterogenous forests (bagging,\n", + "random forests and more) to one of the most popular supervised\n", + "algorithms nowadays, the extreme gradient boosting, or just\n", + "XGBoost. But let us start with the simplest possible ingredient.\n", + "\n", + "Decision trees are supervised learning algorithms used for both,\n", + "classification and regression tasks.\n", + "\n", + "\n", + "The main idea of decision trees\n", + "is to find those descriptive features which contain the most\n", + "**information** regarding the target feature and then split the dataset\n", + "along the values of these features such that the target feature values\n", + "for the resulting underlying datasets are as pure as possible.\n", + "\n", + "The descriptive features which reproduce best the target/output features are normally said\n", + "to be the most informative ones. The process of finding the **most\n", + "informative** feature is done until we accomplish a stopping criteria\n", + "where we then finally end up in so called **leaf nodes**. \n", + "\n", + "\n", + "\n", + "A decision tree is typically divided into a **root node**, the **interior nodes**,\n", + "and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n", + "\n", + "The leaf nodes\n", + "contain the predictions we will make for new query instances presented\n", + "to our trained model. This is possible since the model has \n", + "learned the underlying structure of the training data and hence can,\n", + "given some assumptions, make predictions about the target feature value\n", + "(class) of unseen query instances.\n", + "\n", + "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", + "\n", + "\n", + "\n", + "\n", + "

\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using **Scikit-Learn**'s decision tree classifier. Here we have used the so-called **gini** index (see below) to split the various branches.\n", + "\n", + "\n", + "\n", + "## General Features\n", + "\n", + "The overarching approach to decision trees is a top-down approach.\n", + "\n", + "* A leaf provides the classification of a given instance.\n", + "\n", + "* A node specifies a test of some attribute of the instance.\n", + "\n", + "* A branch corresponds to a possible values of an attribute.\n", + "\n", + "* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n", + "\n", + "This process is then repeated for the subtree rooted at the new\n", + "node.\n", + "\n", + "\n", + "## How do we set it up?\n", + "\n", + "\n", + "In simplified terms, the process of training a decision tree and\n", + "predicting the target features of query instances is as follows:\n", + "\n", + "1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n", + "\n", + "2. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process\n", + "\n", + "3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n", + "\n", + "4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n", + "\n", + "Then we are essentially done!\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Decision trees and Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "steps=250\n", + "\n", + "distance=0\n", + "x=0\n", + "distance_list=[]\n", + "steps_list=[]\n", + "while x\n", + "## Pruning the tree\n", + "\n", + "The above procedure is rather straightforward, but leads often to\n", + "overfitting and unnecessarily large and complicated trees. The basic\n", + "idea is to grow a large tree $T_0$ and then prune it back in order to\n", + "obtain a subtree. A smaller tree with fewer splits (fewer regions) can\n", + "lead to smaller variance and better interpretation at the cost of a\n", + "little more bias.\n", + "\n", + "The so-called Cost complexity pruning algorithm gives us a\n", + "way to do just this. Rather than considering every possible subtree,\n", + "we consider a sequence of trees indexed by a nonnegative tuning\n", + "parameter $\\alpha$.\n", + "\n", + "## Cost complexity pruning\n", + "For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is as small as possible. Here $\\overline{T}$ is \n", + "the number of terminal nodes of the tree $T$ , $R_m$ is the\n", + "rectangle (i.e. the subset of predictor space) corresponding to the $m$-th terminal node.\n", + "\n", + "The tuning parameter $\\alpha$ controls a trade-off between the subtree’s\n", + "com- plexity and its fit to the training data. When $\\alpha = 0$, then the\n", + "subtree $T$ will simply equal $T_0$, \n", + "because then the above equation just measures the\n", + "training error. \n", + "However, as $\\alpha$ increases, there is a price to pay for\n", + "having a tree with many terminal nodes. The above equation will\n", + "tend to be minimized for a smaller subtree. \n", + "\n", + "\n", + "It turns out that as we increase $\\alpha$ from zero\n", + "branches get pruned from the tree in a nested and predictable fashion,\n", + "so obtaining the whole sequence of subtrees as a function of $\\alpha$ is\n", + "easy. We can select a value of $\\alpha$ using a validation set or using\n", + "cross-validation. We then return to the full data set and obtain the\n", + "subtree corresponding to $\\alpha$. \n", + "\n", + "\n", + "## Schematic Regression Procedure\n", + "\n", + "**Building a Regression Tree.**\n", + "\n", + "1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.\n", + "\n", + "2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of $\\alpha$.\n", + "\n", + "3. Use for example $K$-fold cross-validation to choose $\\alpha$. Divide the training observations into $K$ folds. For each $k=1,2,\\dots,K$ we: \n", + "\n", + " * repeat steps 1 and 2 on all but the $k$-th fold of the training data. \n", + "\n", + " * Then we valuate the mean squared prediction error on the data in the left-out $k$-th fold, as a function of $\\alpha$.\n", + "\n", + " * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n", + "\n", + "\n", + "4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$.\n", + "\n", + "\n", + "\n", + "\n", + "## A Classification Tree\n", + "\n", + "A classification tree is very similar to a regression tree, except\n", + "that it is used to predict a qualitative response rather than a\n", + "quantitative one. Recall that for a regression tree, the predicted\n", + "response for an observation is given by the mean response of the\n", + "training observations that belong to the same terminal node. In\n", + "contrast, for a classification tree, we predict that each observation\n", + "belongs to the most commonly occurring class of training observations\n", + "in the region to which it belongs. In interpreting the results of a\n", + "classification tree, we are often interested not only in the class\n", + "prediction corresponding to a particular terminal node region, but\n", + "also in the class proportions among the training observations that\n", + "fall into that region. \n", + "\n", + "## Growing a classification tree\n", + "\n", + "The task of growing a\n", + "classification tree is quite similar to the task of growing a\n", + "regression tree. Just as in the regression setting, we use recursive\n", + "binary splitting to grow a classification tree. However, in the\n", + "classification setting, the MSE cannot be used as a criterion for making\n", + "the binary splits. A natural alternative to MSE is the **classification\n", + "error rate**. Since we plan to assign an observation in a given region\n", + "to the most commonly occurring error rate class of training\n", + "observations in that region, the classification error rate is simply\n", + "the fraction of the training observations in that region that do not\n", + "belong to the most common class. \n", + "\n", + "When building a classification tree, either the Gini index or the\n", + "entropy are typically used to evaluate the quality of a particular\n", + "split, since these two approaches are more sensitive to node purity\n", + "than is the classification error rate. \n", + "\n", + "\n", + "## Classification tree, how to split nodes\n", + "\n", + "If our targets are the outcome of a classification process that takes\n", + "for example $k=1,2,\\dots,K$ values, the only thing we need to think of\n", + "is to set up the splitting criteria for each node.\n", + "\n", + "We define a PDF $p_{mk}$ that represents the number of observations of\n", + "a class $k$ in a region $R_m$ with $N_m$ observations. We represent\n", + "this likelihood function in terms of the proportion $I(y_i=k)$ of\n", + "observations of this class in the region $R_m$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i=k).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We let $p_{mk}$ represent the majority class of observations in region\n", + "$m$. The three most common ways of splitting a node are given by\n", + "\n", + "* Misclassification error" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Gini index $g$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "g = \\sum_{k=1}^K p_{mk}(1-p_{mk}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Information entropy or just entropy $s$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Visualizing the Tree, Classification" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import os\n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.metrics import confusion_matrix\n", + "from sklearn.tree import export_graphviz\n", + "\n", + "from IPython.display import Image \n", + "from pydot import graph_from_dot_data\n", + "import pandas as pd\n", + "import numpy as np\n", + "\n", + "\n", + "cancer = load_breast_cancer()\n", + "X = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n", + "print(X)\n", + "y = pd.Categorical.from_codes(cancer.target, cancer.target_names)\n", + "y = pd.get_dummies(y)\n", + "print(y)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n", + "tree_clf = DecisionTreeClassifier(max_depth=5)\n", + "tree_clf.fit(X_train, y_train)\n", + "\n", + "export_graphviz(\n", + " tree_clf,\n", + " out_file=\"DataFiles/cancer.dot\",\n", + " feature_names=cancer.feature_names,\n", + " class_names=cancer.target_names,\n", + " rounded=True,\n", + " filled=True\n", + ")\n", + "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n", + "os.system(cmd)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Visualizing the Tree, The Moons" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Common imports\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.datasets import make_moons\n", + "from sklearn.tree import export_graphviz\n", + "from pydot import graph_from_dot_data\n", + "import pandas as pd\n", + "import os\n", + "\n", + "np.random.seed(42)\n", + "X, y = make_moons(n_samples=100, noise=0.25, random_state=53)\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)\n", + "tree_clf = DecisionTreeClassifier(max_depth=5)\n", + "tree_clf.fit(X_train, y_train)\n", + "\n", + "export_graphviz(\n", + " tree_clf,\n", + " out_file=\"DataFiles/moons.dot\",\n", + " rounded=True,\n", + " filled=True\n", + ")\n", + "cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'\n", + "os.system(cmd)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Algorithms for Setting up Decision Trees\n", + "\n", + "Two algorithms stand out in the set up of decision trees:\n", + "1. The CART (Classification And Regression Tree) algorithm for both classification and regression\n", + "\n", + "2. The ID3 algorithm based on the computation of the information gain for classification\n", + "\n", + "We discuss both algorithms with applications here. The popular library\n", + "**Scikit-Learn** uses the CART algorithm. For classification problems\n", + "you can use either the **gini** index or the **entropy** to split a tree\n", + "in two branches.\n", + "\n", + "## The CART algorithm for Classification\n", + "\n", + "For classification, the CART algorithm splits the data set in two subsets using a single feature $k$ and a threshold $t_k$.\n", + "This could be for example a threshold set by a number below a certain circumference of a malign tumor.\n", + "\n", + "How do we find these two quantities?\n", + "We search for the pair $(k,t_k)$ that produces the purest subset using for example the **gini** factor $G$.\n", + "The cost function it tries to minimize is then" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $G_{\\mathrm{left/right}}$ measures the impurity of the left/right subset and $m_{\\mathrm{left/right}}$\n", + " is the number of instances in the left/right subset\n", + "\n", + "Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets\n", + "and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the\n", + "$max\\_depth$ hyperparameter), or if it cannot find a split that will reduce impurity. A few other\n", + "hyperparameters control additional stopping conditions such as the $min\\_samples\\_split$,\n", + "$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$.\n", + "\n", + "## The CART algorithm for Regression\n", + "\n", + "The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the\n", + "training set in a way that minimizes say the **gini** or **entropy** impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}\\mathrm{MSE}_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}\\mathrm{MSE}_{\\mathrm{right}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here the MSE for a specific node is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "the mean value of all observations in a specific node.\n", + "\n", + "Without any regularization, the regression task for decision trees, \n", + "just like for classification tasks, is prone to overfitting.\n", + "\n", + "\n", + "## Computing the Gini index\n", + "\n", + "The example we will look at is a classical one in many Machine\n", + "Learning applications. Based on various meteorological features, we\n", + "have several so-called attributes which decide whether we at the end\n", + "will do some outdoor activity like skiing, going for a bike ride etc\n", + "etc. The table here contains the feautures **outlook**, **temperature**,\n", + "**humidity** and **wind**. The target or output is whether we ride\n", + "(True=1) or whether we do something else that day (False=0). The\n", + "attributes for each feature are then sunny, overcast and rain for the\n", + "outlook, hot, cold and mild for temperature, high and normal for\n", + "humidity and weak and strong for wind.\n", + "\n", + "The table here summarizes the various attributes and\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
Day Outlook Temperature Humidity Wind Ride
1 Sunny Hot High Weak 0
2 Sunny Hot High Strong 1
3 Overcast Hot High Weak 1
4 Rain Mild High Weak 1
5 Rain Cool Normal Weak 1
6 Rain Cool Normal Strong 0
7 Overcast Cool Normal Strong 1
8 Sunny Mild High Weak 0
9 Sunny Cool Normal Weak 1
10 Rain Mild Normal Weak 1
11 Sunny Mild Normal Strong 1
12 Overcast Mild High Strong 1
13 Overcast Hot Normal Weak 1
14 Rain Mild High Strong 0
\n", + "\n", + "## Simple Python Code to read in Data and perform Classification" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Common imports\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.tree import export_graphviz\n", + "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", + "from sklearn.compose import ColumnTransformer\n", + "from IPython.display import Image \n", + "from pydot import graph_from_dot_data\n", + "import os\n", + "\n", + "# Where to save the figures and data files\n", + "PROJECT_ROOT_DIR = \"Results\"\n", + "FIGURE_ID = \"Results/FigureFiles\"\n", + "DATA_ID = \"DataFiles/\"\n", + "\n", + "if not os.path.exists(PROJECT_ROOT_DIR):\n", + " os.mkdir(PROJECT_ROOT_DIR)\n", + "\n", + "if not os.path.exists(FIGURE_ID):\n", + " os.makedirs(FIGURE_ID)\n", + "\n", + "if not os.path.exists(DATA_ID):\n", + " os.makedirs(DATA_ID)\n", + "\n", + "def image_path(fig_id):\n", + " return os.path.join(FIGURE_ID, fig_id)\n", + "\n", + "def data_path(dat_id):\n", + " return os.path.join(DATA_ID, dat_id)\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "infile = open(data_path(\"rideclass.csv\"),'r')\n", + "\n", + "# Read the experimental data with Pandas\n", + "from IPython.display import display\n", + "ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n", + "ridedata = pd.DataFrame(ridedata)\n", + "\n", + "# Features and targets\n", + "X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n", + "y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n", + "\n", + "# Create the encoder.\n", + "encoder = OneHotEncoder(handle_unknown=\"ignore\")\n", + "# Assume for simplicity all features are categorical.\n", + "encoder.fit(X) \n", + "# Apply the encoder.\n", + "X = encoder.transform(X)\n", + "print(X)\n", + "# Then do a Classification tree\n", + "tree_clf = DecisionTreeClassifier(max_depth=2)\n", + "tree_clf.fit(X, y)\n", + "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n", + "#transfer to a decision tree graph\n", + "export_graphviz(\n", + " tree_clf,\n", + " out_file=\"DataFiles/ride.dot\",\n", + " rounded=True,\n", + " filled=True\n", + ")\n", + "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n", + "os.system(cmd)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Computing the Gini Factor\n", + "\n", + "The above functions (gini, entropy and misclassification error) are\n", + "important components of the so-called CART algorithm. We will discuss\n", + "this algorithm below after we have discussed the information gain\n", + "algorithm ID3.\n", + "\n", + "In the example here we have converted all our attributes into numerical values $0,1,2$ etc." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Split a dataset based on an attribute and an attribute value\n", + "def test_split(index, value, dataset):\n", + "\tleft, right = list(), list()\n", + "\tfor row in dataset:\n", + "\t\tif row[index] < value:\n", + "\t\t\tleft.append(row)\n", + "\t\telse:\n", + "\t\t\tright.append(row)\n", + "\treturn left, right\n", + " \n", + "# Calculate the Gini index for a split dataset\n", + "def gini_index(groups, classes):\n", + "\t# count all samples at split point\n", + "\tn_instances = float(sum([len(group) for group in groups]))\n", + "\t# sum weighted Gini index for each group\n", + "\tgini = 0.0\n", + "\tfor group in groups:\n", + "\t\tsize = float(len(group))\n", + "\t\t# avoid divide by zero\n", + "\t\tif size == 0:\n", + "\t\t\tcontinue\n", + "\t\tscore = 0.0\n", + "\t\t# score the group based on the score for each class\n", + "\t\tfor class_val in classes:\n", + "\t\t\tp = [row[-1] for row in group].count(class_val) / size\n", + "\t\t\tscore += p * p\n", + "\t\t# weight the group score by its relative size\n", + "\t\tgini += (1.0 - score) * (size / n_instances)\n", + "\treturn gini\n", + "\n", + "# Select the best split point for a dataset\n", + "def get_split(dataset):\n", + "\tclass_values = list(set(row[-1] for row in dataset))\n", + "\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n", + "\tfor index in range(len(dataset[0])-1):\n", + "\t\tfor row in dataset:\n", + "\t\t\tgroups = test_split(index, row[index], dataset)\n", + "\t\t\tgini = gini_index(groups, class_values)\n", + "\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n", + "\t\t\tif gini < b_score:\n", + "\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n", + "\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n", + " \n", + "dataset = [[0,0,0,0,0],\n", + " [0,0,0,1,1],\n", + " [1,0,0,0,1],\n", + " [2,1,0,0,1],\n", + " [2,2,1,0,1],\n", + " [2,2,1,1,0],\n", + " [1,2,1,1,1],\n", + " [0,1,0,0,0],\n", + " [0,2,1,0,1],\n", + " [2,1,1,0,1],\n", + " [0,1,1,1,1],\n", + " [1,1,0,1,1],\n", + " [1,0,1,0,1],\n", + " [2,1,0,1,0]]\n", + "\n", + "split = get_split(dataset)\n", + "print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Entropy and the ID3 algorithm\n", + "\n", + "ID3, learns decision trees by constructing\n", + "them topdown, beginning with the question **which attribute should be tested at the root of the tree**?\n", + "\n", + "1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.\n", + "\n", + "2. The best attribute is selected and used as the test at the root node of the tree.\n", + "\n", + "3. A descendant of the root node is then created for each possible value of this attribute.\n", + "\n", + "4. Training examples are sorted to the appropriate descendant node.\n", + "\n", + "5. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.\n", + "\n", + "6. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices. \n", + "\n", + "The ID3 algorithm selects, which attribute to test at each node in the\n", + "tree.\n", + "\n", + "We would like to select the attribute that is most useful for classifying\n", + "examples.\n", + "\n", + "What is a good quantitative measure of the worth of an attribute?\n", + "\n", + "Information gain measures how well a given attribute separates the\n", + "training examples according to their target classification.\n", + "\n", + "The ID3 algorithm uses this information gain measure to select among the candidate\n", + "attributes at each step while growing the tree.\n", + "\n", + "## Implementing the ID3 Algorithm" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import re\n", + "import math\n", + "from collections import deque\n", + "\n", + "# x is examples in training set\n", + "# y is set of targets\n", + "# label is target attributes\n", + "# Node is a class which has properties values, childs, and next\n", + "# root is top node in the decision tree\n", + "\n", + "class Node(object):\n", + "\tdef __init__(self):\n", + "\t\tself.value = None\n", + "\t\tself.next = None\n", + "\t\tself.childs = None\n", + "\n", + "# Simple class of Decision Tree\n", + "# Aimed for who want to learn Decision Tree, so it is not optimized\n", + "class DecisionTree(object):\n", + "\tdef __init__(self, sample, attributes, labels):\n", + "\t\tself.sample = sample\n", + "\t\tself.attributes = attributes\n", + "\t\tself.labels = labels\n", + "\t\tself.labelCodes = None\n", + "\t\tself.labelCodesCount = None\n", + "\t\tself.initLabelCodes()\n", + "\t\t# print(self.labelCodes)\n", + "\t\tself.root = None\n", + "\t\tself.entropy = self.getEntropy([x for x in range(len(self.labels))])\n", + "\n", + "\tdef initLabelCodes(self):\n", + "\t\tself.labelCodes = []\n", + "\t\tself.labelCodesCount = []\n", + "\t\tfor l in self.labels:\n", + "\t\t\tif l not in self.labelCodes:\n", + "\t\t\t\tself.labelCodes.append(l)\n", + "\t\t\t\tself.labelCodesCount.append(0)\n", + "\t\t\tself.labelCodesCount[self.labelCodes.index(l)] += 1\n", + "\n", + "\tdef getLabelCodeId(self, sampleId):\n", + "\t\treturn self.labelCodes.index(self.labels[sampleId])\n", + "\n", + "\tdef getAttributeValues(self, sampleIds, attributeId):\n", + "\t\tvals = []\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tval = self.sample[sid][attributeId]\n", + "\t\t\tif val not in vals:\n", + "\t\t\t\tvals.append(val)\n", + "\t\t# print(vals)\n", + "\t\treturn vals\n", + "\n", + "\tdef getEntropy(self, sampleIds):\n", + "\t\tentropy = 0\n", + "\t\tlabelCount = [0] * len(self.labelCodes)\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tlabelCount[self.getLabelCodeId(sid)] += 1\n", + "\t\t# print(\"-ge\", labelCount)\n", + "\t\tfor lv in labelCount:\n", + "\t\t\t# print(lv)\n", + "\t\t\tif lv != 0:\n", + "\t\t\t\tentropy += -lv/len(sampleIds) * math.log(lv/len(sampleIds), 2)\n", + "\t\t\telse:\n", + "\t\t\t\tentropy += 0\n", + "\t\treturn entropy\n", + "\n", + "\tdef getDominantLabel(self, sampleIds):\n", + "\t\tlabelCodesCount = [0] * len(self.labelCodes)\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tlabelCodesCount[self.labelCodes.index(self.labels[sid])] += 1\n", + "\t\treturn self.labelCodes[labelCodesCount.index(max(labelCodesCount))]\n", + "\n", + "\tdef getInformationGain(self, sampleIds, attributeId):\n", + "\t\tgain = self.getEntropy(sampleIds)\n", + "\t\tattributeVals = []\n", + "\t\tattributeValsCount = []\n", + "\t\tattributeValsIds = []\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tval = self.sample[sid][attributeId]\n", + "\t\t\tif val not in attributeVals:\n", + "\t\t\t\tattributeVals.append(val)\n", + "\t\t\t\tattributeValsCount.append(0)\n", + "\t\t\t\tattributeValsIds.append([])\n", + "\t\t\tvid = attributeVals.index(val)\n", + "\t\t\tattributeValsCount[vid] += 1\n", + "\t\t\tattributeValsIds[vid].append(sid)\n", + "\t\t# print(\"-gig\", self.attributes[attributeId])\n", + "\t\tfor vc, vids in zip(attributeValsCount, attributeValsIds):\n", + "\t\t\t# print(\"-gig\", vids)\n", + "\t\t\tgain -= vc/len(sampleIds) * self.getEntropy(vids)\n", + "\t\treturn gain\n", + "\n", + "\tdef getAttributeMaxInformationGain(self, sampleIds, attributeIds):\n", + "\t\tattributesEntropy = [0] * len(attributeIds)\n", + "\t\tfor i, attId in zip(range(len(attributeIds)), attributeIds):\n", + "\t\t\tattributesEntropy[i] = self.getInformationGain(sampleIds, attId)\n", + "\t\tmaxId = attributeIds[attributesEntropy.index(max(attributesEntropy))]\n", + "\t\treturn self.attributes[maxId], maxId\n", + "\n", + "\tdef isSingleLabeled(self, sampleIds):\n", + "\t\tlabel = self.labels[sampleIds[0]]\n", + "\t\tfor sid in sampleIds:\n", + "\t\t\tif self.labels[sid] != label:\n", + "\t\t\t\treturn False\n", + "\t\treturn True\n", + "\n", + "\tdef getLabel(self, sampleId):\n", + "\t\treturn self.labels[sampleId]\n", + "\n", + "\tdef id3(self):\n", + "\t\tsampleIds = [x for x in range(len(self.sample))]\n", + "\t\tattributeIds = [x for x in range(len(self.attributes))]\n", + "\t\tself.root = self.id3Recv(sampleIds, attributeIds, self.root)\n", + "\n", + "\tdef id3Recv(self, sampleIds, attributeIds, root):\n", + "\t\troot = Node() # Initialize current root\n", + "\t\tif self.isSingleLabeled(sampleIds):\n", + "\t\t\troot.value = self.labels[sampleIds[0]]\n", + "\t\t\treturn root\n", + "\t\t# print(attributeIds)\n", + "\t\tif len(attributeIds) == 0:\n", + "\t\t\troot.value = self.getDominantLabel(sampleIds)\n", + "\t\t\treturn root\n", + "\t\tbestAttrName, bestAttrId = self.getAttributeMaxInformationGain(\n", + "\t\t\tsampleIds, attributeIds)\n", + "\t\t# print(bestAttrName)\n", + "\t\troot.value = bestAttrName\n", + "\t\troot.childs = [] # Create list of children\n", + "\t\tfor value in self.getAttributeValues(sampleIds, bestAttrId):\n", + "\t\t\t# print(value)\n", + "\t\t\tchild = Node()\n", + "\t\t\tchild.value = value\n", + "\t\t\troot.childs.append(child) # Append new child node to current\n", + "\t\t\t\t\t\t\t\t\t # root\n", + "\t\t\tchildSampleIds = []\n", + "\t\t\tfor sid in sampleIds:\n", + "\t\t\t\tif self.sample[sid][bestAttrId] == value:\n", + "\t\t\t\t\tchildSampleIds.append(sid)\n", + "\t\t\tif len(childSampleIds) == 0:\n", + "\t\t\t\tchild.next = self.getDominantLabel(sampleIds)\n", + "\t\t\telse:\n", + "\t\t\t\t# print(bestAttrName, bestAttrId)\n", + "\t\t\t\t# print(attributeIds)\n", + "\t\t\t\tif len(attributeIds) > 0 and bestAttrId in attributeIds:\n", + "\t\t\t\t\ttoRemove = attributeIds.index(bestAttrId)\n", + "\t\t\t\t\tattributeIds.pop(toRemove)\n", + "\t\t\t\tchild.next = self.id3Recv(\n", + "\t\t\t\t\tchildSampleIds, attributeIds, child.next)\n", + "\t\treturn root\n", + "\n", + "\tdef printTree(self):\n", + "\t\tif self.root:\n", + "\t\t\troots = deque()\n", + "\t\t\troots.append(self.root)\n", + "\t\t\twhile len(roots) > 0:\n", + "\t\t\t\troot = roots.popleft()\n", + "\t\t\t\tprint(root.value)\n", + "\t\t\t\tif root.childs:\n", + "\t\t\t\t\tfor child in root.childs:\n", + "\t\t\t\t\t\tprint('({})'.format(child.value))\n", + "\t\t\t\t\t\troots.append(child.next)\n", + "\t\t\t\telif root.next:\n", + "\t\t\t\t\tprint(root.next)\n", + "\n", + "\n", + "def test():\n", + "\tf = open('DataFiles/rideclass.csv')\n", + "\tattributes = f.readline().split(',')\n", + "\tattributes = attributes[1:len(attributes)-1]\n", + "\tprint(attributes)\n", + "\tsample = f.readlines()\n", + "\tf.close()\n", + "\tfor i in range(len(sample)):\n", + "\t\tsample[i] = re.sub('\\d+,', '', sample[i])\n", + "\t\tsample[i] = sample[i].strip().split(',')\n", + "\tlabels = []\n", + "\tfor s in sample:\n", + "\t\tlabels.append(s.pop())\n", + "\t# print(sample)\n", + "\t# print(labels)\n", + "\tdecisionTree = DecisionTree(sample, attributes, labels)\n", + "\tprint(\"System entropy {}\".format(decisionTree.entropy))\n", + "\tdecisionTree.id3()\n", + "\tdecisionTree.printTree()\n", + "\n", + "\n", + "if __name__ == '__main__':\n", + "\ttest()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Cancer Data again now with Decision Trees and other Methods" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.svm import SVC\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "\n", + "# Load the data\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "# Logistic Regression\n", + "logreg = LogisticRegression(solver='lbfgs')\n", + "logreg.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", + "# Support vector machine\n", + "svm = SVC(gamma='auto', C=100)\n", + "svm.fit(X_train, y_train)\n", + "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", + "deep_tree_clf.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n", + "#now scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "# Logistic Regression\n", + "logreg.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Support Vector Machine\n", + "svm.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Another example, the moons again" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from __future__ import division, print_function, unicode_literals\n", + "\n", + "# Common imports\n", + "import numpy as np\n", + "import os\n", + "\n", + "# to make this notebook's output stable across runs\n", + "np.random.seed(42)\n", + "\n", + "# To plot pretty figures\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib.colors import ListedColormap\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "from sklearn import datasets\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "from sklearn.datasets import make_moons\n", + "from sklearn.tree import export_graphviz\n", + "\n", + "Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)\n", + "\n", + "deep_tree_clf1 = DecisionTreeClassifier(random_state=42)\n", + "deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n", + "deep_tree_clf1.fit(Xm, ym)\n", + "deep_tree_clf2.fit(Xm, ym)\n", + "\n", + "\n", + "def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n", + " x1s = np.linspace(axes[0], axes[1], 100)\n", + " x2s = np.linspace(axes[2], axes[3], 100)\n", + " x1, x2 = np.meshgrid(x1s, x2s)\n", + " X_new = np.c_[x1.ravel(), x2.ravel()]\n", + " y_pred = clf.predict(X_new).reshape(x1.shape)\n", + " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n", + " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n", + " if not iris:\n", + " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n", + " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n", + " if plot_training:\n", + " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", label=\"Iris-Setosa\")\n", + " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", label=\"Iris-Versicolor\")\n", + " plt.plot(X[:, 0][y==2], X[:, 1][y==2], \"g^\", label=\"Iris-Virginica\")\n", + " plt.axis(axes)\n", + " if iris:\n", + " plt.xlabel(\"Petal length\", fontsize=14)\n", + " plt.ylabel(\"Petal width\", fontsize=14)\n", + " else:\n", + " plt.xlabel(r\"$x_1$\", fontsize=18)\n", + " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n", + " if legend:\n", + " plt.legend(loc=\"lower right\", fontsize=14)\n", + "plt.figure(figsize=(11, 4))\n", + "plt.subplot(121)\n", + "plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n", + "plt.title(\"No restrictions\", fontsize=16)\n", + "plt.subplot(122)\n", + "plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n", + "plt.title(\"min_samples_leaf = {}\".format(deep_tree_clf2.min_samples_leaf), fontsize=14)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Playing around with regions" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "np.random.seed(6)\n", + "Xs = np.random.rand(100, 2) - 0.5\n", + "ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n", + "\n", + "angle = np.pi/4\n", + "rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n", + "Xsr = Xs.dot(rotation_matrix)\n", + "\n", + "tree_clf_s = DecisionTreeClassifier(random_state=42)\n", + "tree_clf_s.fit(Xs, ys)\n", + "tree_clf_sr = DecisionTreeClassifier(random_state=42)\n", + "tree_clf_sr.fit(Xsr, ys)\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "plt.subplot(121)\n", + "plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n", + "plt.subplot(122)\n", + "plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Regression trees" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Quadratic training set + noise\n", + "np.random.seed(42)\n", + "m = 200\n", + "X = np.random.rand(m, 1)\n", + "y = 4 * (X - 0.5) ** 2\n", + "y = y + np.random.randn(m, 1) / 10" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n", + "tree_reg.fit(X, y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Final regressor code" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n", + "tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n", + "tree_reg1.fit(X, y)\n", + "tree_reg2.fit(X, y)\n", + "\n", + "def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n", + " x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n", + " y_pred = tree_reg.predict(x1)\n", + " plt.axis(axes)\n", + " plt.xlabel(\"$x_1$\", fontsize=18)\n", + " if ylabel:\n", + " plt.ylabel(ylabel, fontsize=18, rotation=0)\n", + " plt.plot(X, y, \"b.\")\n", + " plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "plt.subplot(121)\n", + "plot_regression_predictions(tree_reg1, X, y)\n", + "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", + " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", + "plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n", + "plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n", + "plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n", + "plt.legend(loc=\"upper center\", fontsize=18)\n", + "plt.title(\"max_depth=2\", fontsize=14)\n", + "\n", + "plt.subplot(122)\n", + "plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n", + "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", + " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", + "for split in (0.0458, 0.1298, 0.2873, 0.9040):\n", + " plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n", + "plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n", + "plt.title(\"max_depth=3\", fontsize=14)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "tree_reg1 = DecisionTreeRegressor(random_state=42)\n", + "tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n", + "tree_reg1.fit(X, y)\n", + "tree_reg2.fit(X, y)\n", + "\n", + "x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n", + "y_pred1 = tree_reg1.predict(x1)\n", + "y_pred2 = tree_reg2.predict(x1)\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plt.plot(X, y, \"b.\")\n", + "plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", + "plt.axis([0, 1, -0.2, 1.1])\n", + "plt.xlabel(\"$x_1$\", fontsize=18)\n", + "plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n", + "plt.legend(loc=\"upper center\", fontsize=18)\n", + "plt.title(\"No restrictions\", fontsize=14)\n", + "\n", + "plt.subplot(122)\n", + "plt.plot(X, y, \"b.\")\n", + "plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", + "plt.axis([0, 1, -0.2, 1.1])\n", + "plt.xlabel(\"$x_1$\", fontsize=18)\n", + "plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pros and cons of trees, pros\n", + "\n", + "* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)\n", + "\n", + "* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n", + "\n", + "* No feature normalization needed\n", + "\n", + "* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n", + "\n", + "* Can model nonlinear relationships\n", + "\n", + "* Can model interactions between the different descriptive features\n", + "\n", + "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)\n", + "\n", + "## Disadvantages\n", + "\n", + "* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n", + "\n", + "* If continuous features are used the tree may become quite large and hence less interpretable\n", + "\n", + "* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented\n", + "\n", + "* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests\n", + "\n", + "* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. \n", + "\n", + "* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n", + "\n", + "* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain\n", + "\n", + "However, by aggregating many decision trees, using methods like\n", + "bagging, random forests, and boosting, the predictive performance of\n", + "trees can be substantially improved.\n", + "\n", + "\n", + "## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n", + "\n", + "As stated above and seen in many of the examples discussed here about\n", + "a single decision tree, we often end up overfitting our training\n", + "data. This normally means that we have a high variance. Can we reduce\n", + "the variance of a statistical learning method?\n", + "\n", + "This leads us to a set of different methods that can combine different\n", + "machine learning algorithms or just use one of them to construct\n", + "forests and jungles of trees, homogeneous ones or heterogenous\n", + "ones. These methods are recognized by different names which we will\n", + "try to explain here. These are\n", + "\n", + "1. Voting classifiers\n", + "\n", + "2. Bagging and Pasting\n", + "\n", + "3. Random forests\n", + "\n", + "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n", + "\n", + "We discuss these methods here.\n", + "\n", + "\n", + "## An Overview of Ensemble Methods\n", + "\n", + "\n", + "\n", + "\n", + "

\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Bagging\n", + "\n", + "The **plain** decision trees suffer from high\n", + "variance. This means that if we split the training data into two parts\n", + "at random, and fit a decision tree to both halves, the results that we\n", + "get could be quite different. In contrast, a procedure with low\n", + "variance will yield similar results if applied repeatedly to distinct\n", + "data sets; linear regression tends to have low variance, if the ratio\n", + "of $n$ to $p$ is moderately large. \n", + "\n", + "**Bootstrap aggregation**, or just **bagging**, is a\n", + "general-purpose procedure for reducing the variance of a statistical\n", + "learning method. \n", + "\n", + "\n", + "## More bagging\n", + "\n", + "Bagging typically results in improved accuracy\n", + "over prediction using a single tree. Unfortunately, however, it can be\n", + "difficult to interpret the resulting model. Recall that one of the\n", + "advantages of decision trees is the attractive and easily interpreted\n", + "diagram that results.\n", + "\n", + "However, when we bag a large number of trees, it is no longer\n", + "possible to represent the resulting statistical learning procedure\n", + "using a single tree, and it is no longer clear which variables are\n", + "most important to the procedure. Thus, bagging improves prediction\n", + "accuracy at the expense of interpretability. Although the collection\n", + "of bagged trees is much more difficult to interpret than a single\n", + "tree, one can obtain an overall summary of the importance of each\n", + "predictor using the MSE (for bagging regression trees) or the Gini\n", + "index (for bagging classification trees). In the case of bagging\n", + "regression trees, we can record the total amount that the MSE is\n", + "decreased due to splits over a given predictor, averaged over all $B$ possible\n", + "trees. A large value indicates an important predictor. Similarly, in\n", + "the context of bagging classification trees, we can add up the total\n", + "amount that the Gini index is decreased by splits over a given\n", + "predictor, averaged over all $B$ trees.\n", + "\n", + "## Simple Voting Example, head or tail" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "heads_proba = 0.51\n", + "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n", + "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n", + "plt.figure(figsize=(8,3.5))\n", + "plt.plot(cumulative_heads_ratio)\n", + "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n", + "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n", + "plt.xlabel(\"Number of coin tosses\")\n", + "plt.ylabel(\"Heads ratio\")\n", + "plt.legend(loc=\"lower right\")\n", + "plt.axis([0, 10000, 0.42, 0.58])\n", + "save_fig(\"votingsimple\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using the Voting Classifier" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "from sklearn.datasets import make_moons\n", + "\n", + "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.svm import SVC\n", + "\n", + "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n", + "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n", + "svm_clf = SVC(gamma=\"auto\", random_state=42)\n", + "\n", + "voting_clf = VotingClassifier(\n", + " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", + " voting='hard')\n", + "\n", + "voting_clf.fit(X_train, y_train)\n", + "\n", + "from sklearn.metrics import accuracy_score\n", + "\n", + "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", + " clf.fit(X_train, y_train)\n", + " y_pred = clf.predict(X_test)\n", + " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n", + "\n", + "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n", + "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n", + "svm_clf = SVC(gamma=\"auto\", probability=True, random_state=42)\n", + "\n", + "voting_clf = VotingClassifier(\n", + " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", + " voting='soft')\n", + "voting_clf.fit(X_train, y_train)\n", + "\n", + "from sklearn.metrics import accuracy_score\n", + "\n", + "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", + " clf.fit(X_train, y_train)\n", + " y_pred = clf.predict(X_test)\n", + " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Please, not the moons again! Voting and Bagging" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "from sklearn.datasets import make_moons\n", + "\n", + "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.ensemble import VotingClassifier\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.svm import SVC\n", + "\n", + "log_clf = LogisticRegression(random_state=42)\n", + "rnd_clf = RandomForestClassifier(random_state=42)\n", + "svm_clf = SVC(random_state=42)\n", + "\n", + "voting_clf = VotingClassifier(\n", + " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", + " voting='hard')\n", + "voting_clf.fit(X_train, y_train)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.metrics import accuracy_score\n", + "\n", + "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", + " clf.fit(X_train, y_train)\n", + " y_pred = clf.predict(X_test)\n", + " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "log_clf = LogisticRegression(random_state=42)\n", + "rnd_clf = RandomForestClassifier(random_state=42)\n", + "svm_clf = SVC(probability=True, random_state=42)\n", + "\n", + "voting_clf = VotingClassifier(\n", + " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", + " voting='soft')\n", + "voting_clf.fit(X_train, y_train)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.metrics import accuracy_score\n", + "\n", + "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", + " clf.fit(X_train, y_train)\n", + " y_pred = clf.predict(X_test)\n", + " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Bagging Examples" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.ensemble import BaggingClassifier\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "\n", + "bag_clf = BaggingClassifier(\n", + " DecisionTreeClassifier(random_state=42), n_estimators=500,\n", + " max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)\n", + "bag_clf.fit(X_train, y_train)\n", + "y_pred = bag_clf.predict(X_test)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.metrics import accuracy_score\n", + "print(accuracy_score(y_test, y_pred))" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "tree_clf = DecisionTreeClassifier(random_state=42)\n", + "tree_clf.fit(X_train, y_train)\n", + "y_pred_tree = tree_clf.predict(X_test)\n", + "print(accuracy_score(y_test, y_pred_tree))" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from matplotlib.colors import ListedColormap\n", + "\n", + "def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):\n", + " x1s = np.linspace(axes[0], axes[1], 100)\n", + " x2s = np.linspace(axes[2], axes[3], 100)\n", + " x1, x2 = np.meshgrid(x1s, x2s)\n", + " X_new = np.c_[x1.ravel(), x2.ravel()]\n", + " y_pred = clf.predict(X_new).reshape(x1.shape)\n", + " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n", + " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n", + " if contour:\n", + " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n", + " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n", + " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n", + " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n", + " plt.axis(axes)\n", + " plt.xlabel(r\"$x_1$\", fontsize=18)\n", + " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n", + "plt.figure(figsize=(11,4))\n", + "plt.subplot(121)\n", + "plot_decision_boundary(tree_clf, X, y)\n", + "plt.title(\"Decision Tree\", fontsize=14)\n", + "plt.subplot(122)\n", + "plot_decision_boundary(bag_clf, X, y)\n", + "plt.title(\"Decision Trees with Bagging\", fontsize=14)\n", + "save_fig(\"baggingtree\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Making your own Bootstrap: Changing the Level of the Decision Tree\n", + "\n", + "Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n", + "a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$)." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "\n", + "n = 100\n", + "n_boostraps = 100\n", + "maxdepth = 8\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "error = np.zeros(maxdepth)\n", + "bias = np.zeros(maxdepth)\n", + "variance = np.zeros(maxdepth)\n", + "polydegree = np.zeros(maxdepth)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "# we produce a simple tree first as benchmark\n", + "simpletree = DecisionTreeRegressor(max_depth=3) \n", + "simpletree.fit(X_train_scaled, y_train)\n", + "simpleprediction = simpletree.predict(X_test_scaled)\n", + "for degree in range(1,maxdepth):\n", + " model = DecisionTreeRegressor(max_depth=degree) \n", + " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + " for i in range(n_boostraps):\n", + " x_, y_ = resample(X_train_scaled, y_train)\n", + " model.fit(x_, y_)\n", + " y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n", + "\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + " print('Polynomial degree:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "mse_simpletree = np.mean( np.mean((y_test - simpleprediction)**2)\n", + "plt.xlim(1,maxdepth)\n", + "plt.plot(polydegree, error, label='MSE simple tree')\n", + "plt.plot(polydegree, mse_simpletree, label='MSE for Bootstrap')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "save_fig(\"baggingboot\")\n", + "plt.show()" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html new file mode 100644 index 000000000..716937c89 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs000.html @@ -0,0 +1,247 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +

 

 

 

+ + + + + + +
+

Week 45: Random Forests and Boosting

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs001.html b/doc/pub/week45/html/._week45-bs001.html new file mode 100644 index 000000000..8fe4f92a5 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs001.html @@ -0,0 +1,262 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Random forests

+ +

+Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. + +

+As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of \( m \) predictors is chosen as split +candidates from the full set of \( p \) predictors. The split is allowed to +use only one of those \( m \) predictors. + +

+A fresh sample of \( m \) predictors is +taken at each split, and typically we choose + +$$ +m\approx \sqrt{p}. +$$ + +

+In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +

+The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quantities. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs002.html b/doc/pub/week45/html/._week45-bs002.html new file mode 100644 index 000000000..44fcf6c6a --- /dev/null +++ b/doc/pub/week45/html/._week45-bs002.html @@ -0,0 +1,245 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Random Forest Algorithm

+The algorithm described here can be applied to both classification and regression problems. + +

+We will grow of forest of say \( B \) trees. + +

    +
  1. For \( b=1:B \)
  2. + +
      +
    • Draw a bootstrap sample of from the training data organized in our \( \boldsymbol{X} \) matrix.
    • +
    • We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
    • + +
        +
      1. we select \( m \le p \) variables at random from the \( p \) predictors/features
      2. +
      3. pick the best split point among the \( m \) features using either the CART algorithm or the ID3 for classification and create a new node
      4. +
      5. split the node into daughter nodes
      6. +
      + +
    + +
  3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
  4. +
+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs003.html b/doc/pub/week45/html/._week45-bs003.html new file mode 100644 index 000000000..515520c4c --- /dev/null +++ b/doc/pub/week45/html/._week45-bs003.html @@ -0,0 +1,293 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Random Forests Compared with other Methods on the Cancer Data

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+#Instantiate the model with 500 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
+Random_Forest_model.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
+
+
+import scikitplot as skplt
+y_pred = Random_Forest_model.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = Random_Forest_model.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs004.html b/doc/pub/week45/html/._week45-bs004.html new file mode 100644 index 000000000..e6c05eb01 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs004.html @@ -0,0 +1,243 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Compare Bagging on Trees with Random Forests

+

+ + +

bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+
+

+ + +

bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred) 
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs005.html b/doc/pub/week45/html/._week45-bs005.html new file mode 100644 index 000000000..76e049c98 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs005.html @@ -0,0 +1,239 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Boosting, a Bird's Eye View

+ +

+The basic idea is to combine weak classifiers in order to create a good +classifier. With a weak classifier we often intend a classifier which +produces results which are only slightly better than we would get by +random guesses. + +

+This is done by applying in an iterative way a weak (or a standard +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs006.html b/doc/pub/week45/html/._week45-bs006.html new file mode 100644 index 000000000..ee183170e --- /dev/null +++ b/doc/pub/week45/html/._week45-bs006.html @@ -0,0 +1,275 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

What is boosting? Additive Modelling/Iterative Fitting

+ +

+Boosting is a way of fitting an additive expansion in a set of +elementary basis functions like for example some simple polynomials. +Assume for example that we have a function +$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ + +

+where \( \beta_m \) are the expansion parameters to be determined in a +minimization process and \( b(x;\gamma_m) \) are some simple functions of +the multivariable parameter \( x \) which is characterized by the +parameters \( \gamma_m \). + +

+As an example, consider the Sigmoid function we used in logistic +regression. In that case, we can translate the function +\( b(x;\gamma_m) \) into the Sigmoid function + +$$ +\sigma(t) = \frac{1}{1+\exp{(-t)}}, +$$ + +

+where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +\( \gamma_1 \) were determined by the Logistic Regression fitting +algorithm. + +

+As another example, consider the cost function we defined for linear regression +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+In this case the function \( f(x) \) was replaced by the design matrix +\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), +that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can +simply invert a matrix and obtain the parameters \( \beta \) by + +$$ +\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ + +

+In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs007.html b/doc/pub/week45/html/._week45-bs007.html new file mode 100644 index 000000000..c48865fdd --- /dev/null +++ b/doc/pub/week45/html/._week45-bs007.html @@ -0,0 +1,249 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Iterative Fitting, Regression and Squared-error Cost Function

+ +

+The way we proceed is as follows (here we specialize to the squared-error cost function) + +

    +
  1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
  2. +
  3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
  4. +
  5. For \( m=1:M \) + +
      +
    1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
    2. +
    3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
    4. +
    5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
    6. +
    + +
+ +We could use any of the algorithms we have discussed till now. If we +use trees, \( \gamma \) parameterizes the split variables and split points +at the internal nodes, and the predictions at the terminal nodes. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs008.html b/doc/pub/week45/html/._week45-bs008.html new file mode 100644 index 000000000..37f771c24 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs008.html @@ -0,0 +1,273 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Squared-Error Example and Iterative Fitting

+ +

+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. + +

+For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). + +

+This means that for every iteration \( m \), we need to optimize + +$$ +(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. +$$ + +

+We start our iteration by simply setting \( f_0(x)=0 \). +Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain +$$ +\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, +$$ + +and +$$ +\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. +$$ + +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) +$$ +\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, +$$ + +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have +$$ +\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, +$$ + +

+which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting +for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. + +

+The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as +\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs009.html b/doc/pub/week45/html/._week45-bs009.html new file mode 100644 index 000000000..c4a2cbce4 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs009.html @@ -0,0 +1,261 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Iterative Fitting, Classification and AdaBoost

+ +

+Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values +\( \{-1,1\} \). + +

+The error rate of the training sample is then + +$$ +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). +$$ + +

+The iterative procedure starts with defining a weak classifier whose +error rate is barely better than random guessing. The iterative +procedure in boosting is to sequentially apply a weak +classification algorithm to repeatedly modified versions of the data +producing a sequence of weak classifiers \( G_m(x) \). + +

+Here we will express our function \( f(x) \) in terms of \( G(x) \). That is +$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ + +will be a function of +$$ +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs010.html b/doc/pub/week45/html/._week45-bs010.html new file mode 100644 index 000000000..a7b170f5d --- /dev/null +++ b/doc/pub/week45/html/._week45-bs010.html @@ -0,0 +1,255 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Adaptive Boosting, AdaBoost

+ +

+In our iterative procedure we define thus +$$ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +$$ + +

+The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the +exponential cost/loss function defined as +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. +$$ + +

+We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. +This is normally done in two steps. Let us however first rewrite the cost function as + +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, +$$ + +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs011.html b/doc/pub/week45/html/._week45-bs011.html new file mode 100644 index 000000000..b38b17e47 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs011.html @@ -0,0 +1,271 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Building up AdaBoost

+ +

+First, for any \( \beta > 0 \), we optimize \( G \) by setting +$$ +G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), +$$ + +which is the classifier that minimizes the weighted error rate in predicting \( y \). + +

+We can do this by rewriting +$$ +\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +$$ + +which can be rewritten as +$$ +(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, +$$ + +which leads to +$$ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +$$ + +where we have redefined the error as +$$ +\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, +$$ + +which leads to an update of +$$ +f_m(x) = f_{m-1}(x) +\beta_m G_m(x). +$$ + +This leads to the new weights +$$ +w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs012.html b/doc/pub/week45/html/._week45-bs012.html new file mode 100644 index 000000000..f0cae321d --- /dev/null +++ b/doc/pub/week45/html/._week45-bs012.html @@ -0,0 +1,249 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Adaptive boosting: AdaBoost, Basic Algorithm

+ +

+The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). + +

+We have already defined the misclassification error \( \mathrm{err} \) as +$$ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), +$$ + +where the function \( I() \) is one if we misclassify and zero if we classify correctly. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs013.html b/doc/pub/week45/html/._week45-bs013.html new file mode 100644 index 000000000..52c5bcdef --- /dev/null +++ b/doc/pub/week45/html/._week45-bs013.html @@ -0,0 +1,267 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Basic Steps of AdaBoost

+ +

+With the above definitions we are now ready to set up the algorithm for AdaBoost. +The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. + +

    +
  1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
  2. +
  3. We rewrite the misclassification error as
  4. +
+ +$$ +\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, +$$ + + +
    +
  1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. + +
      +
    1. Fit then a given classifier to the training set using the weights \( w_i \).
    2. +
    3. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
    4. +
    5. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
    6. +
    7. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
    8. +
    + +
  2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
  3. +
+ +For the iterations with \( m \le 2 \) the weights are modified +individually at each steps. The observations which were misclassified +at iteration \( m-1 \) have a weight which is larger than those which were +classified properly. As this proceeds, the observations which were +difficult to classifiy correctly are given a larger influence. Each +new classification step \( m \) is then forced to concentrate on those +observations that are missed in the previous iterations. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs014.html b/doc/pub/week45/html/._week45-bs014.html new file mode 100644 index 000000000..6120f1db4 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs014.html @@ -0,0 +1,260 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

AdaBoost Examples

+ +

+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. + +

+ + +

from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train, y_train)
+
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train_scaled, y_train)
+y_pred = ada_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs015.html b/doc/pub/week45/html/._week45-bs015.html new file mode 100644 index 000000000..28a1bdc2b --- /dev/null +++ b/doc/pub/week45/html/._week45-bs015.html @@ -0,0 +1,255 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

AdaBoost for Regression

+ +

+Here we present Drucker's AdaBoost tailored for regression. + +

+In bagging, each training example is equally likely to be +picked. In boosting, the probability of a particular +example being in the training set of a particular machine +depends on the performance of the prior machines on +that example. The following is a modification of +Adaboost by Drucker. + +

+Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: + +

    +
  1. We define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
  2. +
  3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
  4. +
  5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
  6. +
  7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
  8. +
+ +\( L_i\in [0,1] \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs016.html b/doc/pub/week45/html/._week45-bs016.html new file mode 100644 index 000000000..d1797d35e --- /dev/null +++ b/doc/pub/week45/html/._week45-bs016.html @@ -0,0 +1,240 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient boosting: Basics with Steepest Descent

+ +

+Gradient boosting is again a similar technique to Adaptive boosting, +it combines so-called weak classifiers or regressors into a strong +method via a series of iterations. + +

+In order to understand the method, let us illustrate its basics by +bringing back the essential steps in linear regression, where our cost +function was the least squares function. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs017.html b/doc/pub/week45/html/._week45-bs017.html new file mode 100644 index 000000000..203a1995d --- /dev/null +++ b/doc/pub/week45/html/._week45-bs017.html @@ -0,0 +1,259 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The Squared-Error again! Steepest Descent

+ +

+We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +This means that for every iteration, we need to optimize + +$$ +(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as +$$ +f_M(x) = \sum_{m=0}^M h_m(x). +$$ + +

+In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as +$$ +g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. +$$ + +

+With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that +the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). + +

+Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have +$$ +(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs018.html b/doc/pub/week45/html/._week45-bs018.html new file mode 100644 index 000000000..07af08aba --- /dev/null +++ b/doc/pub/week45/html/._week45-bs018.html @@ -0,0 +1,241 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Steepest Descent Example

+ +

+Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that +$$ +f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. +$$ + +We can then proceed and compute +$$ +g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, +$$ + +and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs019.html b/doc/pub/week45/html/._week45-bs019.html new file mode 100644 index 000000000..5afb58198 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs019.html @@ -0,0 +1,248 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient Boosting, algorithm

+ +

+Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function +$$ +C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+The way we proceed in an iterative fashion is to + +

    +
  1. Initialize our estimate \( f_0(x) \).
  2. +
  3. For \( m=1:M \), we + +
      +
    1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
    2. +
    3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
    4. +
    5. update the estimate \( f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x) \);
    6. +
    + +
  4. The final estimate is then \( f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x) \).
  5. +
+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs020.html b/doc/pub/week45/html/._week45-bs020.html new file mode 100644 index 000000000..56c7c37d7 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs020.html @@ -0,0 +1,229 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient Boosting Example, Regression

+ +

+We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs021.html b/doc/pub/week45/html/._week45-bs021.html new file mode 100644 index 000000000..132a5d245 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs021.html @@ -0,0 +1,274 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient Boosting, Examples of Regression

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs022.html b/doc/pub/week45/html/._week45-bs022.html new file mode 100644 index 000000000..51c974b7a --- /dev/null +++ b/doc/pub/week45/html/._week45-bs022.html @@ -0,0 +1,267 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Gradient Boosting, Classification Example

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
+gd_clf.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = gd_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("gdclassiffierconfusion")
+plt.show()
+y_probas = gd_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("gdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs023.html b/doc/pub/week45/html/._week45-bs023.html new file mode 100644 index 000000000..d95a816cf --- /dev/null +++ b/doc/pub/week45/html/._week45-bs023.html @@ -0,0 +1,239 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

XGBoost: Extreme Gradient Boosting

+ +

+XGBoost or Extreme Gradient +Boosting, is an optimized distributed gradient boosting library +designed to be highly efficient, flexible and portable. It implements +machine learning algorithms under the Gradient Boosting +framework. XGBoost provides a parallel tree boosting that solve many +data science problems in a fast and accurate way. See the article by Chen and Guestrin. + +

+The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +

+It is now the algorithm which wins essentially all ML competitions!!! + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs024.html b/doc/pub/week45/html/._week45-bs024.html new file mode 100644 index 000000000..3064e1287 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs024.html @@ -0,0 +1,272 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Regression Case

+ +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+    model =  xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/._week45-bs025.html b/doc/pub/week45/html/._week45-bs025.html new file mode 100644 index 000000000..ef1498738 --- /dev/null +++ b/doc/pub/week45/html/._week45-bs025.html @@ -0,0 +1,278 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Xgboost on the Cancer Data

+ +

+As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+import scikitplot as skplt
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
+
+y_test = xg_clf.predict(X_test_scaled)
+
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = xg_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("xdclassiffierconfusion")
+plt.show()
+y_probas = xg_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("xdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+xgb.plot_tree(xg_clf,num_trees=0)
+plt.rcParams['figure.figsize'] = [50, 10]
+save_fig("xgtree")
+plt.show()
+
+xgb.plot_importance(xg_clf)
+plt.rcParams['figure.figsize'] = [5, 5]
+save_fig("xgparams")
+plt.show()
+
+

+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week45/html/reveal.js/.gitignore b/doc/pub/week45/html/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/pub/week45/html/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/pub/week45/html/reveal.js/.travis.yml b/doc/pub/week45/html/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/pub/week45/html/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/week45/html/reveal.js/CONTRIBUTING.md b/doc/pub/week45/html/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/pub/week45/html/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/pub/week45/html/reveal.js/Gruntfile.js b/doc/pub/week45/html/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/pub/week45/html/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/pub/week45/html/reveal.js/LICENSE b/doc/pub/week45/html/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/pub/week45/html/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/pub/week45/html/reveal.js/README.md b/doc/pub/week45/html/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/pub/week45/html/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
+
+
Single Horizontal Slide
+
+
Vertical Slide 1
+
Vertical Slide 2
+
+
+
+``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` +
+``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
+
+``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
+ +
+``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. + +```html +
+ +
+``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
+``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
+

All CSS color formats are supported, like rgba() or hsl().

+
+
+

This slide will have a full-size background image.

+
+
+

This background image will be sized to 100px and repeated.

+
+
+

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

+
+
+

Embeds a web page as a background. Note that the page won't be interactive.

+
+``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
+

This slide will override the presentation transition and zoom!

+
+ +
+

Choose from three transition speeds: default, fast or slow!

+
+``` + +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
+

grow

+

shrink

+

fade-out

+

visible only once

+

blue only once

+

highlight-red

+

highlight-green

+

highlight-blue

+
+``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
+ + I'll fade in, then out + +
+``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
+

Appears last

+

Appears first

+

Appears second

+
+``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
+

+(def lazy-fib
+  (concat
+   [0 1]
+   ((fn rfib [a b]
+        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
+	
+
+``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `
+ +
+ +

 

 

 

+ + + + + + +
+

Week 45: Random Forests and Boosting

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week45/html/week45-reveal.html b/doc/pub/week45/html/week45-reveal.html new file mode 100644 index 000000000..6a1390336 --- /dev/null +++ b/doc/pub/week45/html/week45-reveal.html @@ -0,0 +1,1260 @@ + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + + + + + + + + + + +
+ + + + +

Week 45: Random Forests and Boosting

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

 
+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

 
+

Sep 16, 2020

+
+

+ +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+
+ + +
+

Random forests

+ +

+Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. + +

+As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of \( m \) predictors is chosen as split +candidates from the full set of \( p \) predictors. The split is allowed to +use only one of those \( m \) predictors. + +

+A fresh sample of \( m \) predictors is +taken at each split, and typically we choose + +

 
+$$ +m\approx \sqrt{p}. +$$ +

 
+ +

+In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +

+The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quantities. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. +

+ + +
+

Random Forest Algorithm

+The algorithm described here can be applied to both classification and regression problems. + +

+We will grow of forest of say \( B \) trees. + +

    +

  1. For \( b=1:B \)
  2. + +
      + +

    • Draw a bootstrap sample of from the training data organized in our \( \boldsymbol{X} \) matrix.
    • + +

    • We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
    • + +
        + +

      1. we select \( m \le p \) variables at random from the \( p \) predictors/features
      2. + +

      3. pick the best split point among the \( m \) features using either the CART algorithm or the ID3 for classification and create a new node
      4. + +

      5. split the node into daughter nodes
      6. +
      +

      +

    +

  3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
  4. +
+
+ + +
+

Random Forests Compared with other Methods on the Cancer Data

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+#Instantiate the model with 500 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
+Random_Forest_model.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
+
+
+import scikitplot as skplt
+y_pred = Random_Forest_model.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = Random_Forest_model.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+
+ + +
+

Compare Bagging on Trees with Random Forests

+

+ + +

bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+
+

+ + +

bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred) 
+
+
+ + +
+

Boosting, a Bird's Eye View

+ +

+The basic idea is to combine weak classifiers in order to create a good +classifier. With a weak classifier we often intend a classifier which +produces results which are only slightly better than we would get by +random guesses. + +

+This is done by applying in an iterative way a weak (or a standard +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. +

+ + +
+

What is boosting? Additive Modelling/Iterative Fitting

+ +

+Boosting is a way of fitting an additive expansion in a set of +elementary basis functions like for example some simple polynomials. +Assume for example that we have a function +

 
+$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ +

 
+ +

+where \( \beta_m \) are the expansion parameters to be determined in a +minimization process and \( b(x;\gamma_m) \) are some simple functions of +the multivariable parameter \( x \) which is characterized by the +parameters \( \gamma_m \). + +

+As an example, consider the Sigmoid function we used in logistic +regression. In that case, we can translate the function +\( b(x;\gamma_m) \) into the Sigmoid function + +

 
+$$ +\sigma(t) = \frac{1}{1+\exp{(-t)}}, +$$ +

 
+ +

+where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +\( \gamma_1 \) were determined by the Logistic Regression fitting +algorithm. + +

+As another example, consider the cost function we defined for linear regression +

 
+$$ +C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ +

 
+ +

+In this case the function \( f(x) \) was replaced by the design matrix +\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), +that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can +simply invert a matrix and obtain the parameters \( \beta \) by + +

 
+$$ +\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ +

 
+ +

+In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). +

+ + +
+

Iterative Fitting, Regression and Squared-error Cost Function

+ +

+The way we proceed is as follows (here we specialize to the squared-error cost function) + +

    +

  1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
  2. +

  3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
  4. +

  5. For \( m=1:M \) + +
      +

    1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
    2. +

    3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
    4. +

    5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
    6. +
    +

    +

+

+ +We could use any of the algorithms we have discussed till now. If we +use trees, \( \gamma \) parameterizes the split variables and split points +at the internal nodes, and the predictions at the terminal nodes. +

+ + +
+

Squared-Error Example and Iterative Fitting

+ +

+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. + +

+For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). + +

+This means that for every iteration \( m \), we need to optimize + +

 
+$$ +(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. +$$ +

 
+ +

+We start our iteration by simply setting \( f_0(x)=0 \). +Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain +

 
+$$ +\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, +$$ +

 
+ +and +

 
+$$ +\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. +$$ +

 
+ +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) +

 
+$$ +\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, +$$ +

 
+ +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have +

 
+$$ +\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, +$$ +

 
+ +

+which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting +for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. + +

+The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as +\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). +

+ + +
+

Iterative Fitting, Classification and AdaBoost

+ +

+Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values +\( \{-1,1\} \). + +

+The error rate of the training sample is then + +

 
+$$ +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). +$$ +

 
+ +

+The iterative procedure starts with defining a weak classifier whose +error rate is barely better than random guessing. The iterative +procedure in boosting is to sequentially apply a weak +classification algorithm to repeatedly modified versions of the data +producing a sequence of weak classifiers \( G_m(x) \). + +

+Here we will express our function \( f(x) \) in terms of \( G(x) \). That is +

 
+$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ +

 
+ +will be a function of +

 
+$$ +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). +$$ +

 
+

+ + +
+

Adaptive Boosting, AdaBoost

+ +

+In our iterative procedure we define thus +

 
+$$ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +$$ +

 
+ +

+The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the +exponential cost/loss function defined as +

 
+$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. +$$ +

 
+ +

+We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. +This is normally done in two steps. Let us however first rewrite the cost function as + +

 
+$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, +$$ +

 
+ +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). +

+ + +
+

Building up AdaBoost

+ +

+First, for any \( \beta > 0 \), we optimize \( G \) by setting +

 
+$$ +G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), +$$ +

 
+ +which is the classifier that minimizes the weighted error rate in predicting \( y \). + +

+We can do this by rewriting +

 
+$$ +\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +$$ +

 
+ +which can be rewritten as +

 
+$$ +(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, +$$ +

 
+ +which leads to +

 
+$$ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +$$ +

 
+ +where we have redefined the error as +

 
+$$ +\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, +$$ +

 
+ +which leads to an update of +

 
+$$ +f_m(x) = f_{m-1}(x) +\beta_m G_m(x). +$$ +

 
+ +This leads to the new weights +

 
+$$ +w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} +$$ +

 
+

+ + +
+

Adaptive boosting: AdaBoost, Basic Algorithm

+ +

+The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). + +

+We have already defined the misclassification error \( \mathrm{err} \) as +

 
+$$ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), +$$ +

 
+ +where the function \( I() \) is one if we misclassify and zero if we classify correctly. +

+ + +
+

Basic Steps of AdaBoost

+ +

+With the above definitions we are now ready to set up the algorithm for AdaBoost. +The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. + +

    +

  1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
  2. +

  3. We rewrite the misclassification error as
  4. +
+

 
+$$ +\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, +$$ +

 
+ + +

    +

  1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. + +
      +

    1. Fit then a given classifier to the training set using the weights \( w_i \).
    2. +

    3. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
    4. +

    5. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
    6. +

    7. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
    8. +
    +

  2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
  3. +
+

+ +For the iterations with \( m \le 2 \) the weights are modified +individually at each steps. The observations which were misclassified +at iteration \( m-1 \) have a weight which is larger than those which were +classified properly. As this proceeds, the observations which were +difficult to classifiy correctly are given a larger influence. Each +new classification step \( m \) is then forced to concentrate on those +observations that are missed in the previous iterations. +

+ + +
+

AdaBoost Examples

+ +

+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. + +

+ + +

from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train, y_train)
+
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train_scaled, y_train)
+y_pred = ada_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+
+ + +
+

AdaBoost for Regression

+ +

+Here we present Drucker's AdaBoost tailored for regression. + +

+In bagging, each training example is equally likely to be +picked. In boosting, the probability of a particular +example being in the training set of a particular machine +depends on the performance of the prior machines on +that example. The following is a modification of +Adaboost by Drucker. + +

+Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: + +

    +

  1. We define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
  2. +

  3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
  4. +

  5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
  6. +

  7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
  8. +
+

+ +\( L_i\in [0,1] \). +

+ + +
+

Gradient boosting: Basics with Steepest Descent

+ +

+Gradient boosting is again a similar technique to Adaptive boosting, +it combines so-called weak classifiers or regressors into a strong +method via a series of iterations. + +

+In order to understand the method, let us illustrate its basics by +bringing back the essential steps in linear regression, where our cost +function was the least squares function. +

+ + +
+

The Squared-Error again! Steepest Descent

+ +

+We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +This means that for every iteration, we need to optimize + +

 
+$$ +(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ +

 
+ +

+We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as +

 
+$$ +f_M(x) = \sum_{m=0}^M h_m(x). +$$ +

 
+ +

+In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as +

 
+$$ +g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. +$$ +

 
+ +

+With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that +the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). + +

+Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have +

 
+$$ +(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +$$ +

 
+

+ + +
+

Steepest Descent Example

+ +

+Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that +

 
+$$ +f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. +$$ +

 
+ +We can then proceed and compute +

 
+$$ +g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, +$$ +

 
+ +and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. +

+ + +
+

Gradient Boosting, algorithm

+ +

+Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function +

 
+$$ +C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ +

 
+ +

+The way we proceed in an iterative fashion is to + +

    +

  1. Initialize our estimate \( f_0(x) \).
  2. +

  3. For \( m=1:M \), we + +
      +

    1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
    2. +

    3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
    4. +

    5. update the estimate \( f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x) \);
    6. +
    +

  4. The final estimate is then \( f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x) \).
  5. +
+
+ + +
+

Gradient Boosting Example, Regression

+ +

+We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. +

+ + +
+

Gradient Boosting, Examples of Regression

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+
+
+ + +
+

Gradient Boosting, Classification Example

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
+gd_clf.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = gd_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("gdclassiffierconfusion")
+plt.show()
+y_probas = gd_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("gdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+ + +
+

XGBoost: Extreme Gradient Boosting

+ +

+XGBoost or Extreme Gradient +Boosting, is an optimized distributed gradient boosting library +designed to be highly efficient, flexible and portable. It implements +machine learning algorithms under the Gradient Boosting +framework. XGBoost provides a parallel tree boosting that solve many +data science problems in a fast and accurate way. See the article by Chen and Guestrin. + +

+The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +

+It is now the algorithm which wins essentially all ML competitions!!! +

+ + +
+

Regression Case

+ +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+    model =  xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+
+ + +
+

Xgboost on the Cancer Data

+ +

+As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+import scikitplot as skplt
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
+
+y_test = xg_clf.predict(X_test_scaled)
+
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = xg_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("xdclassiffierconfusion")
+plt.show()
+y_probas = xg_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("xdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+xgb.plot_tree(xg_clf,num_trees=0)
+plt.rcParams['figure.figsize'] = [50, 10]
+save_fig("xgtree")
+plt.show()
+
+xgb.plot_importance(xg_clf)
+plt.rcParams['figure.figsize'] = [5, 5]
+save_fig("xgparams")
+plt.show()
+
+
+ + + +
+
+ + + + + + + + + + + + diff --git a/doc/pub/week45/html/week45-solarized.html b/doc/pub/week45/html/week45-solarized.html new file mode 100644 index 000000000..d1277cffd --- /dev/null +++ b/doc/pub/week45/html/week45-solarized.html @@ -0,0 +1,1031 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Week 45: Random Forests and Boosting

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Random forests

+ +

+Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. + +

+As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of \( m \) predictors is chosen as split +candidates from the full set of \( p \) predictors. The split is allowed to +use only one of those \( m \) predictors. + +

+A fresh sample of \( m \) predictors is +taken at each split, and typically we choose + +$$ +m\approx \sqrt{p}. +$$ + +

+In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +

+The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quantities. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. + +

+









+ +

Random Forest Algorithm

+The algorithm described here can be applied to both classification and regression problems. + +

+We will grow of forest of say \( B \) trees. + +

    +
  1. For \( b=1:B \)
  2. + +
      +
    • Draw a bootstrap sample of from the training data organized in our \( \boldsymbol{X} \) matrix.
    • +
    • We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
    • + +
        +
      1. we select \( m \le p \) variables at random from the \( p \) predictors/features
      2. +
      3. pick the best split point among the \( m \) features using either the CART algorithm or the ID3 for classification and create a new node
      4. +
      5. split the node into daughter nodes
      6. +
      + +
    + +
  3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
  4. +
+ +









+ +

Random Forests Compared with other Methods on the Cancer Data

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+#Instantiate the model with 500 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
+Random_Forest_model.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
+
+
+import scikitplot as skplt
+y_pred = Random_Forest_model.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = Random_Forest_model.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+

+









+ +

Compare Bagging on Trees with Random Forests

+

+ + +

bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+
+

+ + +

bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred) 
+
+

+









+ +

Boosting, a Bird's Eye View

+ +

+The basic idea is to combine weak classifiers in order to create a good +classifier. With a weak classifier we often intend a classifier which +produces results which are only slightly better than we would get by +random guesses. + +

+This is done by applying in an iterative way a weak (or a standard +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. + +

+









+ +

What is boosting? Additive Modelling/Iterative Fitting

+ +

+Boosting is a way of fitting an additive expansion in a set of +elementary basis functions like for example some simple polynomials. +Assume for example that we have a function +$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ + +

+where \( \beta_m \) are the expansion parameters to be determined in a +minimization process and \( b(x;\gamma_m) \) are some simple functions of +the multivariable parameter \( x \) which is characterized by the +parameters \( \gamma_m \). + +

+As an example, consider the Sigmoid function we used in logistic +regression. In that case, we can translate the function +\( b(x;\gamma_m) \) into the Sigmoid function + +$$ +\sigma(t) = \frac{1}{1+\exp{(-t)}}, +$$ + +

+where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +\( \gamma_1 \) were determined by the Logistic Regression fitting +algorithm. + +

+As another example, consider the cost function we defined for linear regression +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+In this case the function \( f(x) \) was replaced by the design matrix +\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), +that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can +simply invert a matrix and obtain the parameters \( \beta \) by + +$$ +\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ + +

+In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). + +

+









+ +

Iterative Fitting, Regression and Squared-error Cost Function

+ +

+The way we proceed is as follows (here we specialize to the squared-error cost function) + +

    +
  1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
  2. +
  3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
  4. +
  5. For \( m=1:M \) + +
      +
    1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
    2. +
    3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
    4. +
    5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
    6. +
    + +
+ +We could use any of the algorithms we have discussed till now. If we +use trees, \( \gamma \) parameterizes the split variables and split points +at the internal nodes, and the predictions at the terminal nodes. + +

+









+ +

Squared-Error Example and Iterative Fitting

+ +

+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. + +

+For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). + +

+This means that for every iteration \( m \), we need to optimize + +$$ +(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. +$$ + +

+We start our iteration by simply setting \( f_0(x)=0 \). +Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain +$$ +\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, +$$ + +and +$$ +\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. +$$ + +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) +$$ +\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, +$$ + +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have +$$ +\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, +$$ + +

+which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting +for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. + +

+The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as +\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). + +

+









+ +

Iterative Fitting, Classification and AdaBoost

+ +

+Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values +\( \{-1,1\} \). + +

+The error rate of the training sample is then + +$$ +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). +$$ + +

+The iterative procedure starts with defining a weak classifier whose +error rate is barely better than random guessing. The iterative +procedure in boosting is to sequentially apply a weak +classification algorithm to repeatedly modified versions of the data +producing a sequence of weak classifiers \( G_m(x) \). + +

+Here we will express our function \( f(x) \) in terms of \( G(x) \). That is +$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ + +will be a function of +$$ +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). +$$ + +

+









+ +

Adaptive Boosting, AdaBoost

+ +

+In our iterative procedure we define thus +$$ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +$$ + +

+The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the +exponential cost/loss function defined as +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. +$$ + +

+We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. +This is normally done in two steps. Let us however first rewrite the cost function as + +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, +$$ + +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). + +

+









+ +

Building up AdaBoost

+ +

+First, for any \( \beta > 0 \), we optimize \( G \) by setting +$$ +G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), +$$ + +which is the classifier that minimizes the weighted error rate in predicting \( y \). + +

+We can do this by rewriting +$$ +\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +$$ + +which can be rewritten as +$$ +(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, +$$ + +which leads to +$$ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +$$ + +where we have redefined the error as +$$ +\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, +$$ + +which leads to an update of +$$ +f_m(x) = f_{m-1}(x) +\beta_m G_m(x). +$$ + +This leads to the new weights +$$ +w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} +$$ + +

+









+ +

Adaptive boosting: AdaBoost, Basic Algorithm

+ +

+The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). + +

+We have already defined the misclassification error \( \mathrm{err} \) as +$$ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), +$$ + +where the function \( I() \) is one if we misclassify and zero if we classify correctly. + +

+









+ +

Basic Steps of AdaBoost

+ +

+With the above definitions we are now ready to set up the algorithm for AdaBoost. +The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. + +

    +
  1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
  2. +
  3. We rewrite the misclassification error as
  4. +
+ +$$ +\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, +$$ + + +
    +
  1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. + +
      +
    1. Fit then a given classifier to the training set using the weights \( w_i \).
    2. +
    3. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
    4. +
    5. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
    6. +
    7. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
    8. +
    + +
  2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
  3. +
+ +For the iterations with \( m \le 2 \) the weights are modified +individually at each steps. The observations which were misclassified +at iteration \( m-1 \) have a weight which is larger than those which were +classified properly. As this proceeds, the observations which were +difficult to classifiy correctly are given a larger influence. Each +new classification step \( m \) is then forced to concentrate on those +observations that are missed in the previous iterations. + +

+









+ +

AdaBoost Examples

+ +

+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. + +

+ + +

from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train, y_train)
+
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train_scaled, y_train)
+y_pred = ada_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+

+









+ +

AdaBoost for Regression

+ +

+Here we present Drucker's AdaBoost tailored for regression. + +

+In bagging, each training example is equally likely to be +picked. In boosting, the probability of a particular +example being in the training set of a particular machine +depends on the performance of the prior machines on +that example. The following is a modification of +Adaboost by Drucker. + +

+Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: + +

    +
  1. We define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
  2. +
  3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
  4. +
  5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
  6. +
  7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
  8. +
+ +\( L_i\in [0,1] \). + +

+









+ +

Gradient boosting: Basics with Steepest Descent

+ +

+Gradient boosting is again a similar technique to Adaptive boosting, +it combines so-called weak classifiers or regressors into a strong +method via a series of iterations. + +

+In order to understand the method, let us illustrate its basics by +bringing back the essential steps in linear regression, where our cost +function was the least squares function. + +

+









+ +

The Squared-Error again! Steepest Descent

+ +

+We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +This means that for every iteration, we need to optimize + +$$ +(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as +$$ +f_M(x) = \sum_{m=0}^M h_m(x). +$$ + +

+In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as +$$ +g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. +$$ + +

+With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that +the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). + +

+Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have +$$ +(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +$$ + +

+









+ +

Steepest Descent Example

+ +

+Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that +$$ +f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. +$$ + +We can then proceed and compute +$$ +g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, +$$ + +and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. + +

+









+ +

Gradient Boosting, algorithm

+ +

+Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function +$$ +C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+The way we proceed in an iterative fashion is to + +

    +
  1. Initialize our estimate \( f_0(x) \).
  2. +
  3. For \( m=1:M \), we + +
      +
    1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
    2. +
    3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
    4. +
    5. update the estimate \( f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x) \);
    6. +
    + +
  4. The final estimate is then \( f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x) \).
  5. +
+ +









+ +

Gradient Boosting Example, Regression

+ +

+We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. + +

+









+ +

Gradient Boosting, Examples of Regression

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+
+

+









+ +

Gradient Boosting, Classification Example

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
+gd_clf.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = gd_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("gdclassiffierconfusion")
+plt.show()
+y_probas = gd_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("gdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+

+









+ +

XGBoost: Extreme Gradient Boosting

+ +

+XGBoost or Extreme Gradient +Boosting, is an optimized distributed gradient boosting library +designed to be highly efficient, flexible and portable. It implements +machine learning algorithms under the Gradient Boosting +framework. XGBoost provides a parallel tree boosting that solve many +data science problems in a fast and accurate way. See the article by Chen and Guestrin. + +

+The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +

+It is now the algorithm which wins essentially all ML competitions!!! + +

+









+ +

Regression Case

+ +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+    model =  xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+

+









+ +

Xgboost on the Cancer Data

+ +

+As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+import scikitplot as skplt
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
+
+y_test = xg_clf.predict(X_test_scaled)
+
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = xg_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("xdclassiffierconfusion")
+plt.show()
+y_probas = xg_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("xdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+xgb.plot_tree(xg_clf,num_trees=0)
+plt.rcParams['figure.figsize'] = [50, 10]
+save_fig("xgtree")
+plt.show()
+
+xgb.plot_importance(xg_clf)
+plt.rcParams['figure.figsize'] = [5, 5]
+save_fig("xgparams")
+plt.show()
+
+

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html new file mode 100644 index 000000000..a3859ad05 --- /dev/null +++ b/doc/pub/week45/html/week45.html @@ -0,0 +1,1036 @@ + + + + + + + + +Week 45: Random Forests and Boosting + + + + + + + + + + + + + + + + + + + + + + + +

Week 45: Random Forests and Boosting

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Random forests

+ +

+Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. + +

+As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of \( m \) predictors is chosen as split +candidates from the full set of \( p \) predictors. The split is allowed to +use only one of those \( m \) predictors. + +

+A fresh sample of \( m \) predictors is +taken at each split, and typically we choose + +$$ +m\approx \sqrt{p}. +$$ + +

+In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. + +

+The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quantities. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. + +

+









+ +

Random Forest Algorithm

+The algorithm described here can be applied to both classification and regression problems. + +

+We will grow of forest of say \( B \) trees. + +

    +
  1. For \( b=1:B \)
  2. + +
      +
    • Draw a bootstrap sample of from the training data organized in our \( \boldsymbol{X} \) matrix.
    • +
    • We grow then a random forest tree \( T_b \) based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
    • + +
        +
      1. we select \( m \le p \) variables at random from the \( p \) predictors/features
      2. +
      3. pick the best split point among the \( m \) features using either the CART algorithm or the ID3 for classification and create a new node
      4. +
      5. split the node into daughter nodes
      6. +
      + +
    + +
  3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
  4. +
+ +









+ +

Random Forests Compared with other Methods on the Cancer Data

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.svm import SVC
+from sklearn.linear_model import LogisticRegression
+from sklearn.tree import DecisionTreeClassifier
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+# Logistic Regression
+logreg = LogisticRegression(solver='lbfgs')
+logreg.fit(X_train, y_train)
+print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
+# Support vector machine
+svm = SVC(gamma='auto', C=100)
+svm.fit(X_train, y_train)
+print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
+# Decision Trees
+deep_tree_clf = DecisionTreeClassifier(max_depth=None)
+deep_tree_clf.fit(X_train, y_train)
+print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+# Logistic Regression
+logreg.fit(X_train_scaled, y_train)
+print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Support Vector Machine
+svm.fit(X_train_scaled, y_train)
+print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
+# Decision Trees
+deep_tree_clf.fit(X_train_scaled, y_train)
+print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
+
+
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+# Data set not specificied
+#Instantiate the model with 500 trees and entropy as splitting criteria
+Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
+Random_Forest_model.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
+
+
+import scikitplot as skplt
+y_pred = Random_Forest_model.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = Random_Forest_model.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+

+









+ +

Compare Bagging on Trees with Random Forests

+

+ + +

bag_clf = BaggingClassifier(
+    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+
+

+ + +

bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
+from sklearn.ensemble import RandomForestClassifier
+rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
+rnd_clf.fit(X_train, y_train)
+y_pred_rf = rnd_clf.predict(X_test)
+np.sum(y_pred == y_pred_rf) / len(y_pred) 
+
+

+









+ +

Boosting, a Bird's Eye View

+ +

+The basic idea is to combine weak classifiers in order to create a good +classifier. With a weak classifier we often intend a classifier which +produces results which are only slightly better than we would get by +random guesses. + +

+This is done by applying in an iterative way a weak (or a standard +classifier like decision trees) to modify the data. In each iteration +we emphasize those observations which are misclassified by weighting +them with a factor. + +

+









+ +

What is boosting? Additive Modelling/Iterative Fitting

+ +

+Boosting is a way of fitting an additive expansion in a set of +elementary basis functions like for example some simple polynomials. +Assume for example that we have a function +$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ + +

+where \( \beta_m \) are the expansion parameters to be determined in a +minimization process and \( b(x;\gamma_m) \) are some simple functions of +the multivariable parameter \( x \) which is characterized by the +parameters \( \gamma_m \). + +

+As an example, consider the Sigmoid function we used in logistic +regression. In that case, we can translate the function +\( b(x;\gamma_m) \) into the Sigmoid function + +$$ +\sigma(t) = \frac{1}{1+\exp{(-t)}}, +$$ + +

+where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +\( \gamma_1 \) were determined by the Logistic Regression fitting +algorithm. + +

+As another example, consider the cost function we defined for linear regression +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+In this case the function \( f(x) \) was replaced by the design matrix +\( \boldsymbol{X} \) and the unknown linear regression parameters \( \boldsymbol{\beta} \), +that is \( \boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta} \). In linear regression we can +simply invert a matrix and obtain the parameters \( \beta \) by + +$$ +\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ + +

+In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \). + +

+









+ +

Iterative Fitting, Regression and Squared-error Cost Function

+ +

+The way we proceed is as follows (here we specialize to the squared-error cost function) + +

    +
  1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
  2. +
  3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
  4. +
  5. For \( m=1:M \) + +
      +
    1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
    2. +
    3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
    4. +
    5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
    6. +
    + +
+ +We could use any of the algorithms we have discussed till now. If we +use trees, \( \gamma \) parameterizes the split variables and split points +at the internal nodes, and the predictions at the terminal nodes. + +

+









+ +

Squared-Error Example and Iterative Fitting

+ +

+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. + +

+For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \). + +

+This means that for every iteration \( m \), we need to optimize + +$$ +(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2. +$$ + +

+We start our iteration by simply setting \( f_0(x)=0 \). +Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain +$$ +\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, +$$ + +and +$$ +\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. +$$ + +We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector) +$$ +\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0, +$$ + +which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have +$$ +\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0, +$$ + +

+which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting +for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically. + +

+The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as +\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \). + +

+









+ +

Iterative Fitting, Classification and AdaBoost

+ +

+Let us consider a binary classification problem with two outcomes \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. We define a classification function \( G(x) \) which produces a prediction taking one or the other of the two values +\( \{-1,1\} \). + +

+The error rate of the training sample is then + +$$ +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). +$$ + +

+The iterative procedure starts with defining a weak classifier whose +error rate is barely better than random guessing. The iterative +procedure in boosting is to sequentially apply a weak +classification algorithm to repeatedly modified versions of the data +producing a sequence of weak classifiers \( G_m(x) \). + +

+Here we will express our function \( f(x) \) in terms of \( G(x) \). That is +$$ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +$$ + +will be a function of +$$ +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). +$$ + +

+









+ +

Adaptive Boosting, AdaBoost

+ +

+In our iterative procedure we define thus +$$ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +$$ + +

+The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the +exponential cost/loss function defined as +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. +$$ + +

+We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case. +This is normally done in two steps. Let us however first rewrite the cost function as + +$$ +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, +$$ + +where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \). + +

+









+ +

Building up AdaBoost

+ +

+First, for any \( \beta > 0 \), we optimize \( G \) by setting +$$ +G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), +$$ + +which is the classifier that minimizes the weighted error rate in predicting \( y \). + +

+We can do this by rewriting +$$ +\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +$$ + +which can be rewritten as +$$ +(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0, +$$ + +which leads to +$$ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +$$ + +where we have redefined the error as +$$ +\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m}, +$$ + +which leads to an update of +$$ +f_m(x) = f_{m-1}(x) +\beta_m G_m(x). +$$ + +This leads to the new weights +$$ +w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} +$$ + +

+









+ +

Adaptive boosting: AdaBoost, Basic Algorithm

+ +

+The algorithm here is rather straightforward. Assume that our weak +classifier is a decision tree and we consider a binary set of outputs +with \( y_i \in \{-1,1\} \) and \( i=0,1,2,\dots,n-1 \) as our set of +observations. Our design matrix is given in terms of the +feature/predictor vectors +\( \boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}] \). Finally, we define also a +classifier determined by our data via a function \( G(x) \). This function tells us how well we are able to classify our outputs/targets \( \boldsymbol{y} \). + +

+We have already defined the misclassification error \( \mathrm{err} \) as +$$ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), +$$ + +where the function \( I() \) is one if we misclassify and zero if we classify correctly. + +

+









+ +

Basic Steps of AdaBoost

+ +

+With the above definitions we are now ready to set up the algorithm for AdaBoost. +The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases. + +

    +
  1. We start by initializing all weights to \( w_i = 1/n \), with \( i=0,1,2,\dots n-1 \). It is easy to see that we must have \( \sum_{i=0}^{n-1}w_i = 1 \).
  2. +
  3. We rewrite the misclassification error as
  4. +
+ +$$ +\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i}, +$$ + + +
    +
  1. Then we start looping over all attempts at classifying, namely we start an iterative process for \( m=1:M \), where \( M \) is the final number of classifications. Our given classifier could for example be a plain decision tree. + +
      +
    1. Fit then a given classifier to the training set using the weights \( w_i \).
    2. +
    3. Compute then \( \mathrm{err} \) and figure out which events are classified properly and which are classified wrongly.
    4. +
    5. Define a quantity \( \alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m} \)
    6. +
    7. Set the new weights to \( w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)} \).
    8. +
    + +
  2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
  3. +
+ +For the iterations with \( m \le 2 \) the weights are modified +individually at each steps. The observations which were misclassified +at iteration \( m-1 \) have a weight which is larger than those which were +classified properly. As this proceeds, the observations which were +difficult to classifiy correctly are given a larger influence. Each +new classification step \( m \) is then forced to concentrate on those +observations that are missed in the previous iterations. + +

+









+ +

AdaBoost Examples

+ +

+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. + +

+ + +

from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train, y_train)
+
+from sklearn.ensemble import AdaBoostClassifier
+
+ada_clf = AdaBoostClassifier(
+    DecisionTreeClassifier(max_depth=1), n_estimators=200,
+    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
+ada_clf.fit(X_train_scaled, y_train)
+y_pred = ada_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+plt.show()
+y_probas = ada_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+plt.show()
+
+

+









+ +

AdaBoost for Regression

+ +

+Here we present Drucker's AdaBoost tailored for regression. + +

+In bagging, each training example is equally likely to be +picked. In boosting, the probability of a particular +example being in the training set of a particular machine +depends on the performance of the prior machines on +that example. The following is a modification of +Adaboost by Drucker. + +

+Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: + +

    +
  1. We define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
  2. +
  3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
  4. +
  5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
  6. +
  7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
  8. +
+ +\( L_i\in [0,1] \). + +

+









+ +

Gradient boosting: Basics with Steepest Descent

+ +

+Gradient boosting is again a similar technique to Adaptive boosting, +it combines so-called weak classifiers or regressors into a strong +method via a series of iterations. + +

+In order to understand the method, let us illustrate its basics by +bringing back the essential steps in linear regression, where our cost +function was the least squares function. + +

+









+ +

The Squared-Error again! Steepest Descent

+ +

+We start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize +This means that for every iteration, we need to optimize + +$$ +(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as +$$ +f_M(x) = \sum_{m=0}^M h_m(x). +$$ + +

+In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as +$$ +g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}. +$$ + +

+With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that +the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \). + +

+Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have +$$ +(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +$$ + +

+









+ +

Steepest Descent Example

+ +

+Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that +$$ +f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. +$$ + +We can then proceed and compute +$$ +g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i, +$$ + +and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \( m=M \). We can modify the steepest descent method, or steepest boosting, by introducing what is called gradient boosting. + +

+









+ +

Gradient Boosting, algorithm

+ +

+Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function +$$ +C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ + +

+The way we proceed in an iterative fashion is to + +

    +
  1. Initialize our estimate \( f_0(x) \).
  2. +
  3. For \( m=1:M \), we + +
      +
    1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
    2. +
    3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
    4. +
    5. update the estimate \( f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x) \);
    6. +
    + +
  4. The final estimate is then \( f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x) \).
  5. +
+ +









+ +

Gradient Boosting Example, Regression

+ +

+We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. + +

+









+ +

Gradient Boosting, Examples of Regression

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+
+

+









+ +

Gradient Boosting, Classification Example

+

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
+
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
+gd_clf.fit(X_train_scaled, y_train)
+#Cross validation
+accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
+print(accuracy)
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = gd_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("gdclassiffierconfusion")
+plt.show()
+y_probas = gd_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("gdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+

+









+ +

XGBoost: Extreme Gradient Boosting

+ +

+XGBoost or Extreme Gradient +Boosting, is an optimized distributed gradient boosting library +designed to be highly efficient, flexible and portable. It implements +machine learning algorithms under the Gradient Boosting +framework. XGBoost provides a parallel tree boosting that solve many +data science problems in a fast and accurate way. See the article by Chen and Guestrin. + +

+The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +

+It is now the algorithm which wins essentially all ML competitions!!! + +

+









+ +

Regression Case

+ +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+    model =  xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+    model.fit(X_train_scaled,y_train)
+    y_pred = model.predict(X_test_scaled)
+    polydegree[degree] = degree
+    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+    variance[degree] = np.mean( np.var(y_pred) )
+    print('Max depth:', degree)
+    print('Error:', error[degree])
+    print('Bias^2:', bias[degree])
+    print('Var:', variance[degree])
+    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
+

+









+ +

Xgboost on the Cancer Data

+ +

+As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. +

+ + +

import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import  train_test_split 
+from sklearn.datasets import load_breast_cancer
+from sklearn.preprocessing import LabelEncoder
+from sklearn.model_selection import cross_validate
+import scikitplot as skplt
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
+
+X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
+print(X_train.shape)
+print(X_test.shape)
+#now scale the data
+from sklearn.preprocessing import StandardScaler
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
+
+y_test = xg_clf.predict(X_test_scaled)
+
+print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
+
+import scikitplot as skplt
+y_pred = xg_clf.predict(X_test_scaled)
+skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
+save_fig("xdclassiffierconfusion")
+plt.show()
+y_probas = xg_clf.predict_proba(X_test_scaled)
+skplt.metrics.plot_roc(y_test, y_probas)
+save_fig("xdclassiffierroc")
+plt.show()
+skplt.metrics.plot_cumulative_gain(y_test, y_probas)
+save_fig("gdclassiffiercgain")
+plt.show()
+
+
+xgb.plot_tree(xg_clf,num_trees=0)
+plt.rcParams['figure.figsize'] = [50, 10]
+save_fig("xgtree")
+plt.show()
+
+xgb.plot_importance(xg_clf)
+plt.rcParams['figure.figsize'] = [5, 5]
+save_fig("xgparams")
+plt.show()
+
+

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz new file mode 100644 index 000000000..f30ba752f Binary files /dev/null and b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz differ diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb new file mode 100644 index 000000000..80433a3e0 --- /dev/null +++ b/doc/pub/week45/ipynb/week45.ipynb @@ -0,0 +1,1212 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Week 45: Random Forests and Boosting\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Random forests\n", + "\n", + "Random forests provide an improvement over bagged trees by way of a\n", + "small tweak that decorrelates the trees. \n", + "\n", + "As in bagging, we build a\n", + "number of decision trees on bootstrapped training samples. But when\n", + "building these decision trees, each time a split in a tree is\n", + "considered, a random sample of $m$ predictors is chosen as split\n", + "candidates from the full set of $p$ predictors. The split is allowed to\n", + "use only one of those $m$ predictors. \n", + "\n", + "A fresh sample of $m$ predictors is\n", + "taken at each split, and typically we choose" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "m\\approx \\sqrt{p}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In building a random forest, at\n", + "each split in the tree, the algorithm is not even allowed to consider\n", + "a majority of the available predictors. \n", + "\n", + "The reason for this is rather clever. Suppose that there is one very\n", + "strong predictor in the data set, along with a number of other\n", + "moderately strong predictors. Then in the collection of bagged\n", + "variable importance random forest trees, most or all of the trees will\n", + "use this strong predictor in the top split. Consequently, all of the\n", + "bagged trees will look quite similar to each other. Hence the\n", + "predictions from the bagged trees will be highly correlated.\n", + "Unfortunately, averaging many highly correlated quantities does not\n", + "lead to as large of a reduction in variance as averaging many\n", + "uncorrelated quantities. In particular, this means that bagging will\n", + "not lead to a substantial reduction in variance over a single tree in\n", + "this setting.\n", + "\n", + "\n", + "## Random Forest Algorithm\n", + "The algorithm described here can be applied to both classification and regression problems.\n", + "\n", + "We will grow of forest of say $B$ trees.\n", + "1. For $b=1:B$\n", + "\n", + " * Draw a bootstrap sample of from the training data organized in our $\\boldsymbol{X}$ matrix.\n", + "\n", + " * We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached\n", + "\n", + "1. we select $m \\le p$ variables at random from the $p$ predictors/features\n", + "\n", + "2. pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node\n", + "\n", + "3. split the node into daughter nodes\n", + "\n", + "\n", + "\n", + "4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem. \n", + "\n", + "## Random Forests Compared with other Methods on the Cancer Data" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.svm import SVC\n", + "from sklearn.linear_model import LogisticRegression\n", + "from sklearn.tree import DecisionTreeClassifier\n", + "\n", + "# Load the data\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "# Logistic Regression\n", + "logreg = LogisticRegression(solver='lbfgs')\n", + "logreg.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", + "# Support vector machine\n", + "svm = SVC(gamma='auto', C=100)\n", + "svm.fit(X_train, y_train)\n", + "print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", + "deep_tree_clf.fit(X_train, y_train)\n", + "print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n", + "#now scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "# Logistic Regression\n", + "logreg.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Support Vector Machine\n", + "svm.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", + "# Decision Trees\n", + "deep_tree_clf.fit(X_train_scaled, y_train)\n", + "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))\n", + "\n", + "\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import cross_validate\n", + "# Data set not specificied\n", + "#Instantiate the model with 500 trees and entropy as splitting criteria\n", + "Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion=\"entropy\")\n", + "Random_Forest_model.fit(X_train_scaled, y_train)\n", + "#Cross validation\n", + "accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']\n", + "print(accuracy)\n", + "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(Random_Forest_model.score(X_test_scaled,y_test)))\n", + "\n", + "\n", + "import scikitplot as skplt\n", + "y_pred = Random_Forest_model.predict(X_test_scaled)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "plt.show()\n", + "y_probas = Random_Forest_model.predict_proba(X_test_scaled)\n", + "skplt.metrics.plot_roc(y_test, y_probas)\n", + "plt.show()\n", + "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Compare Bagging on Trees with Random Forests" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "bag_clf = BaggingClassifier(\n", + " DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n", + " n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "bag_clf.fit(X_train, y_train)\n", + "y_pred = bag_clf.predict(X_test)\n", + "from sklearn.ensemble import RandomForestClassifier\n", + "rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n", + "rnd_clf.fit(X_train, y_train)\n", + "y_pred_rf = rnd_clf.predict(X_test)\n", + "np.sum(y_pred == y_pred_rf) / len(y_pred)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Boosting, a Bird's Eye View\n", + "\n", + "The basic idea is to combine weak classifiers in order to create a good\n", + "classifier. With a weak classifier we often intend a classifier which\n", + "produces results which are only slightly better than we would get by\n", + "random guesses.\n", + "\n", + "This is done by applying in an iterative way a weak (or a standard\n", + "classifier like decision trees) to modify the data. In each iteration\n", + "we emphasize those observations which are misclassified by weighting\n", + "them with a factor.\n", + "\n", + "\n", + "## What is boosting? Additive Modelling/Iterative Fitting\n", + "\n", + "Boosting is a way of fitting an additive expansion in a set of\n", + "elementary basis functions like for example some simple polynomials.\n", + "Assume for example that we have a function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\beta_m$ are the expansion parameters to be determined in a\n", + "minimization process and $b(x;\\gamma_m)$ are some simple functions of\n", + "the multivariable parameter $x$ which is characterized by the\n", + "parameters $\\gamma_m$.\n", + "\n", + "As an example, consider the Sigmoid function we used in logistic\n", + "regression. In that case, we can translate the function\n", + "$b(x;\\gamma_m)$ into the Sigmoid function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n", + "$\\gamma_1$ were determined by the Logistic Regression fitting\n", + "algorithm.\n", + "\n", + "As another example, consider the cost function we defined for linear regression" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this case the function $f(x)$ was replaced by the design matrix\n", + "$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n", + "that is $\\boldsymbol{f}=\\boldsymbol{X}\\boldsymbol{\\beta}$. In linear regression we can \n", + "simply invert a matrix and obtain the parameters $\\beta$ by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$.\n", + "\n", + "\n", + "## Iterative Fitting, Regression and Squared-error Cost Function\n", + "\n", + "The way we proceed is as follows (here we specialize to the squared-error cost function)\n", + "\n", + "1. Establish a cost function, here ${\\cal C}(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m)$.\n", + "\n", + "2. Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.\n", + "\n", + "3. For $m=1:M$\n", + "\n", + "a. minimize $\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2$ wrt $\\gamma$ and $\\beta$\n", + "\n", + "b. This gives the optimal values $\\beta_m$ and $\\gamma_m$\n", + "\n", + "c. Determine then the new values $f_m(x)=f_{m-1}(x) +\\beta_m b(x;\\gamma_m)$\n", + "\n", + "\n", + "We could use any of the algorithms we have discussed till now. If we\n", + "use trees, $\\gamma$ parameterizes the split variables and split points\n", + "at the internal nodes, and the predictions at the terminal nodes.\n", + "\n", + "\n", + "## Squared-Error Example and Iterative Fitting\n", + "\n", + "To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.\n", + "\n", + "For simplicity we assume also that our functions $b(x;\\gamma)=1+\\gamma x$. \n", + "\n", + "This means that for every iteration $m$, we need to optimize" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\beta_m,\\gamma_m) = \\mathrm{argmin}_{\\beta,\\lambda}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2=\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta(1+\\gamma x_i))^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We start our iteration by simply setting $f_0(x)=0$. \n", + "Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n", + "for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n", + "\n", + "The solution to these two equations gives us in turn $\\beta_1$ and $\\gamma_1$ leading to the new expression for $f_1(x)$ as\n", + "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$. \n", + "\n", + "\n", + "\n", + "## Iterative Fitting, Classification and AdaBoost\n", + "\n", + "Let us consider a binary classification problem with two outcomes $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", + "observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values \n", + "$\\{-1,1\\}$.\n", + "\n", + "The error rate of the training sample is then" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The iterative procedure starts with defining a weak classifier whose\n", + "error rate is barely better than random guessing. The iterative\n", + "procedure in boosting is to sequentially apply a weak\n", + "classification algorithm to repeatedly modified versions of the data\n", + "producing a sequence of weak classifiers $G_m(x)$.\n", + "\n", + "Here we will express our function $f(x)$ in terms of $G(x)$. That is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "will be a function of" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Adaptive Boosting, AdaBoost\n", + "\n", + "In our iterative procedure we define thus" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n", + "exponential cost/loss function defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n", + "This is normally done in two steps. Let us however first rewrite the cost function as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$.\n", + "\n", + "## Building up AdaBoost\n", + "\n", + "First, for any $\\beta > 0$, we optimize $G$ by setting" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which is the classifier that minimizes the weighted error rate in predicting $y$.\n", + "\n", + "We can do this by rewriting" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which can be rewritten as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\exp{(\\beta)}-\\exp{-(\\beta)})\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i))+\\exp{(-\\beta)}\\sum_{i=0}^{n-1}w_i^m=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which leads to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have redefined the error as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{\\overline{err}}_m=\\frac{1}{n}\\frac{\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i)}{\\sum_{i=0}^{n-1}w_i^m},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which leads to an update of" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This leads to the new weights" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Adaptive boosting: AdaBoost, Basic Algorithm\n", + "\n", + "The algorithm here is rather straightforward. Assume that our weak\n", + "classifier is a decision tree and we consider a binary set of outputs\n", + "with $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", + "observations. Our design matrix is given in terms of the\n", + "feature/predictor vectors\n", + "$\\boldsymbol{X}=[\\boldsymbol{x}_0\\boldsymbol{x}_1\\dots\\boldsymbol{x}_{p-1}]$. Finally, we define also a\n", + "classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\\boldsymbol{y}$. \n", + "\n", + "We have already defined the misclassification error $\\mathrm{err}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the function $I()$ is one if we misclassify and zero if we classify correctly. \n", + "\n", + "## Basic Steps of AdaBoost\n", + "\n", + "With the above definitions we are now ready to set up the algorithm for AdaBoost.\n", + "The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.\n", + "1. We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\\dots n-1$. It is easy to see that we must have $\\sum_{i=0}^{n-1}w_i = 1$.\n", + "\n", + "2. We rewrite the misclassification error as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{\\overline{err}}_m=\\frac{\\sum_{i=0}^{n-1}w_i^m I(y_i\\ne G(x_i))}{\\sum_{i=0}^{n-1}w_i},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.\n", + "\n", + "a. Fit then a given classifier to the training set using the weights $w_i$.\n", + "\n", + "b. Compute then $\\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.\n", + "\n", + "c. Define a quantity $\\alpha_{m} = \\log{(1-\\mathrm{\\overline{err}}_m)/\\mathrm{\\overline{err}}_m}$\n", + "\n", + "d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(x_i)}$.\n", + "\n", + "\n", + "5. Compute the new classifier $G(x)= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(x_i)$.\n", + "\n", + "For the iterations with $m \\le 2$ the weights are modified\n", + "individually at each steps. The observations which were misclassified\n", + "at iteration $m-1$ have a weight which is larger than those which were\n", + "classified properly. As this proceeds, the observations which were\n", + "difficult to classifiy correctly are given a larger influence. Each\n", + "new classification step $m$ is then forced to concentrate on those\n", + "observations that are missed in the previous iterations.\n", + "\n", + "\n", + "\n", + "## AdaBoost Examples\n", + "\n", + "Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from sklearn.ensemble import AdaBoostClassifier\n", + "\n", + "ada_clf = AdaBoostClassifier(\n", + " DecisionTreeClassifier(max_depth=1), n_estimators=200,\n", + " algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n", + "ada_clf.fit(X_train, y_train)\n", + "\n", + "from sklearn.ensemble import AdaBoostClassifier\n", + "\n", + "ada_clf = AdaBoostClassifier(\n", + " DecisionTreeClassifier(max_depth=1), n_estimators=200,\n", + " algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n", + "ada_clf.fit(X_train_scaled, y_train)\n", + "y_pred = ada_clf.predict(X_test_scaled)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "plt.show()\n", + "y_probas = ada_clf.predict_proba(X_test_scaled)\n", + "skplt.metrics.plot_roc(y_test, y_probas)\n", + "plt.show()\n", + "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## AdaBoost for Regression\n", + "\n", + "Here we present [Drucker's AdaBoost](https://pdfs.semanticscholar.org/8d49/e2dedb817f2c3330e74b63c5fc86d2399ce3.pdf) tailored for regression.\n", + "\n", + "In bagging, each training example is equally likely to be\n", + "picked. In boosting, the probability of a particular\n", + "example being in the training set of a particular machine\n", + "depends on the performance of the prior machines on\n", + "that example. The following is a modification of\n", + "Adaboost by Drucker.\n", + "\n", + "Start by selecting a set of training data $n$ and assign to each entry a weight $w_i=1$ for $i=1,2,\\dots,n$. As we have done earlier, we could pick say $80\\%$ of the data set for training. The algorithm runs as follows:\n", + "1. We define the probability that the training sample $i$ is in the set by $p_i = w_i/\\sum_iw_i$. We pick $n$ samples (with replacement) to form our training set. We pick a number uniformly in the range $[0,\\sum_iw_i]$.\n", + "\n", + "2. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.\n", + "\n", + "3. Using every member of the training set with the chosen regression machine we obtain then a prediction $\\tilde{y}_i$.\n", + "\n", + "4. We calculate then the loss function $L_i$ for each training sample. We can use various types of loss function as long as we have a value\n", + "\n", + "$L_i\\in [0,1]$. \n", + "\n", + "## Gradient boosting: Basics with Steepest Descent\n", + "\n", + "Gradient boosting is again a similar technique to Adaptive boosting,\n", + "it combines so-called weak classifiers or regressors into a strong\n", + "method via a series of iterations.\n", + "\n", + "In order to understand the method, let us illustrate its basics by\n", + "bringing back the essential steps in linear regression, where our cost\n", + "function was the least squares function.\n", + "\n", + "## The Squared-Error again! Steepest Descent\n", + "\n", + "We start again with our cost function ${\\cal C}(\\boldsymbol{y}m\\boldsymbol{f})=\\sum_{i=0}^{n-1}{\\cal L}(y_i, f(x_i))$ where we want to minimize\n", + "This means that for every iteration, we need to optimize" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f_M(x) = \\sum_{m=0}^M h_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the steepest decent approach we approximate $h_m(x) = -\\rho_m g_m(x)$, where $\\rho_m$ is a scalar and $g_m(x)$ the gradient defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "g_m(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{m-1}(x_i)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With the new gradient we can update $f_m(x) = f_{m-1}(x) -\\rho_m g_m(x)$. Using the above squared-error function we see that\n", + "the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.\n", + "\n", + "Choosing $f_0(x)=0$ we obtain $g_m(x) = -2y_i$ and inserting this into the minimization problem for the cost function we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Steepest Descent Example\n", + "\n", + "Optimizing with respect to $\\rho$ we obtain (taking the derivative) that $\\rho_1 = -1/2$. We have then that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can then proceed and compute" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "g_2(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and find a new value for $\\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called **gradient boosting**. \n", + "\n", + "## Gradient Boosting, algorithm\n", + "\n", + "Suppose we have a cost function $C(f)=\\sum_{i=0}^{n-1}L(y_i, f(x_i))$ where $y_i$ is our target and $f(x_i)$ the function which is meant to model $y_i$. The above cost function could be our standard squared-error function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The way we proceed in an iterative fashion is to\n", + "1. Initialize our estimate $f_0(x)$.\n", + "\n", + "2. For $m=1:M$, we\n", + "\n", + "a. compute the negative gradient vector $\\boldsymbol{u}_m = -\\partial C(\\boldsymbol{y},\\boldsymbol{f})/\\partial \\boldsymbol{f}(x)$ at $f(x) = f_{m-1}(x)$;\n", + "\n", + "b. fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;\n", + "\n", + "c. update the estimate $f_m(x) = f_{m-1}(x)+\\nu h_m(u_m,x)$;\n", + "\n", + "\n", + "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M\\nu h_m(u_m,x)$.\n", + "\n", + "## Gradient Boosting Example, Regression\n", + "\n", + "We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. \n", + "\n", + "\n", + "## Gradient Boosting, Examples of Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.ensemble import GradientBoostingRegressor\n", + "from sklearn.preprocessing import StandardScaler\n", + "import scikitplot as skplt\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "n = 100\n", + "maxdegree = 6\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "\n", + "error = np.zeros(maxdegree)\n", + "bias = np.zeros(maxdegree)\n", + "variance = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "for degree in range(1,maxdegree):\n", + " model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) \n", + " model.fit(X_train_scaled,y_train)\n", + " y_pred = model.predict(X_test_scaled)\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred) )\n", + " print('Max depth:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.xlim(1,maxdegree-1)\n", + "plt.plot(polydegree, error, label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "save_fig(\"gdregression\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Gradient Boosting, Classification Example" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "import scikitplot as skplt\n", + "from sklearn.ensemble import GradientBoostingClassifier\n", + "from sklearn.model_selection import cross_validate\n", + "\n", + "# Load the data\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "#now scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0) \n", + "gd_clf.fit(X_train_scaled, y_train)\n", + "#Cross validation\n", + "accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']\n", + "print(accuracy)\n", + "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(gd_clf.score(X_test_scaled,y_test)))\n", + "\n", + "import scikitplot as skplt\n", + "y_pred = gd_clf.predict(X_test_scaled)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "save_fig(\"gdclassiffierconfusion\")\n", + "plt.show()\n", + "y_probas = gd_clf.predict_proba(X_test_scaled)\n", + "skplt.metrics.plot_roc(y_test, y_probas)\n", + "save_fig(\"gdclassiffierroc\")\n", + "plt.show()\n", + "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", + "save_fig(\"gdclassiffiercgain\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## XGBoost: Extreme Gradient Boosting\n", + "\n", + "\n", + "[XGBoost](https://github.com/dmlc/xgboost) or Extreme Gradient\n", + "Boosting, is an optimized distributed gradient boosting library\n", + "designed to be highly efficient, flexible and portable. It implements\n", + "machine learning algorithms under the Gradient Boosting\n", + "framework. XGBoost provides a parallel tree boosting that solve many\n", + "data science problems in a fast and accurate way. See the [article by Chen and Guestrin](https://arxiv.org/abs/1603.02754).\n", + "\n", + "The authors design and build a highly scalable end-to-end tree\n", + "boosting system. It has a theoretically justified weighted quantile\n", + "sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.\n", + "\n", + "It is now the algorithm which wins essentially all ML competitions!!!\n", + "\n", + "## Regression Case" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split\n", + "import xgboost as xgb\n", + "from sklearn.preprocessing import StandardScaler\n", + "import scikitplot as skplt\n", + "from sklearn.metrics import mean_squared_error\n", + "\n", + "n = 100\n", + "maxdegree = 6\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "\n", + "error = np.zeros(maxdegree)\n", + "bias = np.zeros(maxdegree)\n", + "variance = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "for degree in range(maxdegree):\n", + " model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)\n", + "\n", + " model.fit(X_train_scaled,y_train)\n", + " y_pred = model.predict(X_test_scaled)\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred) )\n", + " print('Max depth:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.xlim(1,maxdegree-1)\n", + "plt.plot(polydegree, error, label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Xgboost on the Cancer Data\n", + "\n", + "As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\n", + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.model_selection import train_test_split \n", + "from sklearn.datasets import load_breast_cancer\n", + "from sklearn.preprocessing import LabelEncoder\n", + "from sklearn.model_selection import cross_validate\n", + "import scikitplot as skplt\n", + "import xgboost as xgb\n", + "# Load the data\n", + "cancer = load_breast_cancer()\n", + "\n", + "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "#now scale the data\n", + "from sklearn.preprocessing import StandardScaler\n", + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)\n", + "\n", + "xg_clf = xgb.XGBClassifier()\n", + "xg_clf.fit(X_train_scaled,y_train)\n", + "\n", + "y_test = xg_clf.predict(X_test_scaled)\n", + "\n", + "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(xg_clf.score(X_test_scaled,y_test)))\n", + "\n", + "import scikitplot as skplt\n", + "y_pred = xg_clf.predict(X_test_scaled)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "save_fig(\"xdclassiffierconfusion\")\n", + "plt.show()\n", + "y_probas = xg_clf.predict_proba(X_test_scaled)\n", + "skplt.metrics.plot_roc(y_test, y_probas)\n", + "save_fig(\"xdclassiffierroc\")\n", + "plt.show()\n", + "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", + "save_fig(\"gdclassiffiercgain\")\n", + "plt.show()\n", + "\n", + "\n", + "xgb.plot_tree(xg_clf,num_trees=0)\n", + "plt.rcParams['figure.figsize'] = [50, 10]\n", + "save_fig(\"xgtree\")\n", + "plt.show()\n", + "\n", + "xgb.plot_importance(xg_clf)\n", + "plt.rcParams['figure.figsize'] = [5, 5]\n", + "save_fig(\"xgparams\")\n", + "plt.show()" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/pub/week46/html/._week46-bs000.html b/doc/pub/week46/html/._week46-bs000.html new file mode 100644 index 000000000..513efd003 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs000.html @@ -0,0 +1,224 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +

 

 

 

+ + + + + + +
+

Week 46: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs001.html b/doc/pub/week46/html/._week46-bs001.html new file mode 100644 index 000000000..98df677dd --- /dev/null +++ b/doc/pub/week46/html/._week46-bs001.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs002.html b/doc/pub/week46/html/._week46-bs002.html new file mode 100644 index 000000000..51b706e19 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs002.html @@ -0,0 +1,283 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs003.html b/doc/pub/week46/html/._week46-bs003.html new file mode 100644 index 000000000..e094bf185 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs003.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +$$ +b+w_1x_1+w_2x_2=0, +$$ + +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs004.html b/doc/pub/week46/html/._week46-bs004.html new file mode 100644 index 000000000..676c2026a --- /dev/null +++ b/doc/pub/week46/html/._week46-bs004.html @@ -0,0 +1,240 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ + +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ + +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ + +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ + +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ + +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs005.html b/doc/pub/week46/html/._week46-bs005.html new file mode 100644 index 000000000..4d25996e9 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs005.html @@ -0,0 +1,226 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs006.html b/doc/pub/week46/html/._week46-bs006.html new file mode 100644 index 000000000..984ce5be6 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs006.html @@ -0,0 +1,222 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Getting into the details

+ +

+Let us define the function +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs007.html b/doc/pub/week46/html/._week46-bs007.html new file mode 100644 index 000000000..9915f86c3 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs007.html @@ -0,0 +1,226 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ + +and +$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs008.html b/doc/pub/week46/html/._week46-bs008.html new file mode 100644 index 000000000..6ddd29d7b --- /dev/null +++ b/doc/pub/week46/html/._week46-bs008.html @@ -0,0 +1,220 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ + +and +$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ + +where \( \eta \) is our by now well-known learning rate. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs009.html b/doc/pub/week46/html/._week46-bs009.html new file mode 100644 index 000000000..28d85781e --- /dev/null +++ b/doc/pub/week46/html/._week46-bs009.html @@ -0,0 +1,217 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs010.html b/doc/pub/week46/html/._week46-bs010.html new file mode 100644 index 000000000..f998d45d2 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs010.html @@ -0,0 +1,220 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs011.html b/doc/pub/week46/html/._week46-bs011.html new file mode 100644 index 000000000..2122c84c7 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs011.html @@ -0,0 +1,246 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ + +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ + +or just +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ + +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ + +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs012.html b/doc/pub/week46/html/._week46-bs012.html new file mode 100644 index 000000000..8b43aaaf2 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs012.html @@ -0,0 +1,254 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +$$ +df=0. +$$ + +A necessary and sufficient condition is +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +due to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ + +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +$$ +\phi(x,y,z) = 0, +$$ + + resulting in +$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ + +Now we cannot set anymore +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs013.html b/doc/pub/week46/html/._week46-bs013.html new file mode 100644 index 000000000..a49085998 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs013.html @@ -0,0 +1,247 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Adding the Multiplier

+ +

+However, we can add to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ + +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ + +Our multiplier is chosen so that +$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ + +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ + +and +$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ + +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs014.html b/doc/pub/week46/html/._week46-bs014.html new file mode 100644 index 000000000..1ad93cdf5 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs014.html @@ -0,0 +1,245 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ + +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ + + +

    +
  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +
  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs015.html b/doc/pub/week46/html/._week46-bs015.html new file mode 100644 index 000000000..43ff34e4b --- /dev/null +++ b/doc/pub/week46/html/._week46-bs015.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The problem to solve

+ +

+We can rewrite +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs016.html b/doc/pub/week46/html/._week46-bs016.html new file mode 100644 index 000000000..d450ffecd --- /dev/null +++ b/doc/pub/week46/html/._week46-bs016.html @@ -0,0 +1,238 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +resulting in +$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ + +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ + +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs017.html b/doc/pub/week46/html/._week46-bs017.html new file mode 100644 index 000000000..419283256 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs017.html @@ -0,0 +1,239 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ + +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs018.html b/doc/pub/week46/html/._week46-bs018.html new file mode 100644 index 000000000..80fcb4b0a --- /dev/null +++ b/doc/pub/week46/html/._week46-bs018.html @@ -0,0 +1,256 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ + +subject to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ + +and +$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +and +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs019.html b/doc/pub/week46/html/._week46-bs019.html new file mode 100644 index 000000000..5c099d50e --- /dev/null +++ b/doc/pub/week46/html/._week46-bs019.html @@ -0,0 +1,274 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs020.html b/doc/pub/week46/html/._week46-bs020.html new file mode 100644 index 000000000..deecbf7ff --- /dev/null +++ b/doc/pub/week46/html/._week46-bs020.html @@ -0,0 +1,245 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ + +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +For the above example, the kernel reads +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ + +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs021.html b/doc/pub/week46/html/._week46-bs021.html new file mode 100644 index 000000000..cfb5564c8 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs021.html @@ -0,0 +1,235 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs022.html b/doc/pub/week46/html/._week46-bs022.html new file mode 100644 index 000000000..a8fd3772b --- /dev/null +++ b/doc/pub/week46/html/._week46-bs022.html @@ -0,0 +1,236 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +
  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +
  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +
  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +
  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs023.html b/doc/pub/week46/html/._week46-bs023.html new file mode 100644 index 000000000..dffa845a2 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs023.html @@ -0,0 +1,393 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs024.html b/doc/pub/week46/html/._week46-bs024.html new file mode 100644 index 000000000..13ddfd84c --- /dev/null +++ b/doc/pub/week46/html/._week46-bs024.html @@ -0,0 +1,221 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs025.html b/doc/pub/week46/html/._week46-bs025.html new file mode 100644 index 000000000..9df02acb3 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs025.html @@ -0,0 +1,221 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs026.html b/doc/pub/week46/html/._week46-bs026.html new file mode 100644 index 000000000..0d0eefb19 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs026.html @@ -0,0 +1,262 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A simple example

+ +

+We remind ourselves about the general problem we want to solve +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ + +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ + +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ + +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ + +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=’d’)
+q = matrix(numpy.array([3,4]), tc=’d’)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[’x’] 
+sol[’primal objective’]
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/._week46-bs027.html b/doc/pub/week46/html/._week46-bs027.html new file mode 100644 index 000000000..817d3168d --- /dev/null +++ b/doc/pub/week46/html/._week46-bs027.html @@ -0,0 +1,216 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added + +

+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week46/html/reveal.js/.gitignore b/doc/pub/week46/html/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/pub/week46/html/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/pub/week46/html/reveal.js/.travis.yml b/doc/pub/week46/html/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/pub/week46/html/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/week46/html/reveal.js/CONTRIBUTING.md b/doc/pub/week46/html/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/pub/week46/html/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/pub/week46/html/reveal.js/Gruntfile.js b/doc/pub/week46/html/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/pub/week46/html/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/pub/week46/html/reveal.js/LICENSE b/doc/pub/week46/html/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/pub/week46/html/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/pub/week46/html/reveal.js/README.md b/doc/pub/week46/html/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/pub/week46/html/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
+
+
Single Horizontal Slide
+
+
Vertical Slide 1
+
Vertical Slide 2
+
+
+
+``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` +
+``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
+
+``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
+ +
+``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. + +```html +
+ +
+``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
+``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
+

All CSS color formats are supported, like rgba() or hsl().

+
+
+

This slide will have a full-size background image.

+
+
+

This background image will be sized to 100px and repeated.

+
+
+

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

+
+
+

Embeds a web page as a background. Note that the page won't be interactive.

+
+``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
+

This slide will override the presentation transition and zoom!

+
+ +
+

Choose from three transition speeds: default, fast or slow!

+
+``` + +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
+

grow

+

shrink

+

fade-out

+

visible only once

+

blue only once

+

highlight-red

+

highlight-green

+

highlight-blue

+
+``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
+ + I'll fade in, then out + +
+``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
+

Appears last

+

Appears first

+

Appears second

+
+``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
+

+(def lazy-fib
+  (concat
+   [0 1]
+   ((fn rfib [a b]
+        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
+	
+
+``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `
+ +
+ +

 

 

 

+ + + + + + +
+

Week 46: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week46/html/week46-reveal.html b/doc/pub/week46/html/week46-reveal.html new file mode 100644 index 000000000..696e3908f --- /dev/null +++ b/doc/pub/week46/html/week46-reveal.html @@ -0,0 +1,1619 @@ + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + + + + + + + + + + +
+ + + + +

Week 46: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

 
+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

 
+

Sep 16, 2020

+
+

+ +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+
+ + +
+

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. +

+ + +
+

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+
+ + +
+

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +

 
+$$ +b+w_1x_1+w_2x_2=0, +$$ +

 
+ +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +

 
+$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ +

 
+

+ + +
+

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +

 
+$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ +

 
+ +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +

 
+$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ +

 
+ +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +

 
+$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ +

 
+ +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +

 
+$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ +

 
+ +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +

 
+$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ +

 
+ +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. +

+ + +
+

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. +

+ + +
+

Getting into the details

+ +

+Let us define the function +

 
+$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ +

 
+ +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +

 
+$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ +

 
+

+ + +
+

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +

 
+$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ +

 
+ +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +

 
+$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ +

 
+ +and +

 
+$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ +

 
+

+ + +
+

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +

 
+$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ +

 
+ +and +

 
+$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ +

 
+ +where \( \eta \) is our by now well-known learning rate. +

+ + +
+

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+
+ + +
+

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. +

+ + +
+

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ +

 
+ +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +

 
+$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ +

 
+ +or just +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ +

 
+ +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ +

 
+ +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. +

+ + +
+

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +

 
+$$ +df=0. +$$ +

 
+ +A necessary and sufficient condition is +

 
+$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ +

 
+ +due to +

 
+$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ +

 
+ +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +

 
+$$ +\phi(x,y,z) = 0, +$$ +

 
+ + resulting in +

 
+$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ +

 
+ +Now we cannot set anymore +

 
+$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ +

 
+ +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. +

+ + +
+

Adding the Multiplier

+ +

+However, we can add to +

 
+$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ +

 
+ +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +

 
+$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ +

 
+ +Our multiplier is chosen so that +

 
+$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ +

 
+ +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +

 
+$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ +

 
+ +and +

 
+$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ +

 
+ +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +

 
+$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ +

 
+

+ + +
+

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +

 
+$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ +

 
+ +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

 
+$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ +

 
+ +and +

 
+$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ +

 
+ +Inserting these constraints into the equation for \( {\cal L} \) we obtain +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ +

 
+ +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +

 
+$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ +

 
+ + +

    +

  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +

  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+

+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). +

+ + +
+

The problem to solve

+ +

+We can rewrite +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ +

 
+ +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +

 
+$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ +

 
+ +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

+ + +
+

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +

 
+$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ +

 
+ +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ +

 
+ +resulting in +

 
+$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ +

 
+ +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +

 
+$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ +

 
+ +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +

 
+$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ +

 
+ +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. +

+ + +
+

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ +

 
+ +to +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ +

 
+ +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. +

+ + +
+

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +

 
+$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ +

 
+ +subject to +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ +

 
+ +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

 
+$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ +

 
+ +and +

 
+$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ +

 
+ +and +

 
+$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ +

 
+ +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ +

 
+ +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +

 
+$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ +

 
+ +

 
+$$ +\gamma_i\xi_i = 0, +$$ +

 
+ +and +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ +

 
+

+ + +
+

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+
+ + +
+

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +

 
+$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ +

 
+ +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ +

 
+ +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ +

 
+ +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +

 
+$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ +

 
+ +For the above example, the kernel reads +

 
+$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ +

 
+ +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. +

+ + +
+

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ +

 
+ +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +

 
+$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ +

 
+ +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +

 
+$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ +

 
+ +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). +

+ + +
+

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +

  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +

  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +

  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +

  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+

+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +

 
+$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ +

 
+ +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. +

+ + +
+

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+
+ + +
+

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +

 
+$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ +

 
+ +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. +

+ + +
+

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. +

+ + +
+

A simple example

+ +

+We remind ourselves about the general problem we want to solve +

 
+$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ +

 
+ +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +

 
+$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ +

 
+ +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +

 
+$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ +

 
+ +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +

 
+$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ +

 
+ +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +

 
+$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ +

 
+ +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +

 
+$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ +

 
+ +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=d)
+q = matrix(numpy.array([3,4]), tc=d)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=d)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=d)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[x] 
+sol[primal objective]
+
+
+ + +
+

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +

 
+$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ +

 
+ +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added +

+ + + +
+
+ + + + + + + + + + + + diff --git a/doc/pub/week46/html/week46-solarized.html b/doc/pub/week46/html/week46-solarized.html new file mode 100644 index 000000000..35b8748a6 --- /dev/null +++ b/doc/pub/week46/html/week46-solarized.html @@ -0,0 +1,1295 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Week 46: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. + +

+









+ +

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+

+









+ +

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +$$ +b+w_1x_1+w_2x_2=0, +$$ + +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ + +

+









+ +

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ + +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ + +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ + +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ + +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ + +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. + +

+ + +

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. + +

+









+ +

Getting into the details

+ +

+Let us define the function +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ + +

+









+ +

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ + +and +$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ + +

+









+ +

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ + +and +$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ + +where \( \eta \) is our by now well-known learning rate. + +

+









+ +

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+

+









+ +

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. + +

+









+ +

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ + +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ + +or just +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ + +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ + +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. + +

+









+ +

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +$$ +df=0. +$$ + +A necessary and sufficient condition is +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +due to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ + +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +$$ +\phi(x,y,z) = 0, +$$ + + resulting in +$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ + +Now we cannot set anymore +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. + +

+









+ +

Adding the Multiplier

+ +

+However, we can add to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ + +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ + +Our multiplier is chosen so that +$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ + +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ + +and +$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ + +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ + +

+









+ +

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ + +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ + + +

    +
  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +
  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). + +

+









+ +

The problem to solve

+ +

+We can rewrite +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). + +

+









+ +

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +resulting in +$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ + +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ + +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. + +

+









+ +

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ + +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. + +

+









+ +

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ + +subject to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ + +and +$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +and +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ + +

+









+ +

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+

+









+ +

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ + +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +For the above example, the kernel reads +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ + +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. + +

+









+ +

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). + +

+









+ +

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +
  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +
  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +
  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +
  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. + +

+









+ +

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+

+









+ +

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. + +

+









+ +

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. + +

+









+ +

A simple example

+ +

+We remind ourselves about the general problem we want to solve +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ + +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ + +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ + +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ + +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=d)
+q = matrix(numpy.array([3,4]), tc=d)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=d)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=d)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[x] 
+sol[primal objective]
+
+

+









+ +

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added + +

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week46/html/week46.html b/doc/pub/week46/html/week46.html new file mode 100644 index 000000000..d8f773ff5 --- /dev/null +++ b/doc/pub/week46/html/week46.html @@ -0,0 +1,1300 @@ + + + + + + + + +Week 46: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + +

Week 46: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. + +

+









+ +

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+

+









+ +

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +$$ +b+w_1x_1+w_2x_2=0, +$$ + +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ + +

+









+ +

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ + +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ + +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ + +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ + +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ + +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. + +

+ + +

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. + +

+









+ +

Getting into the details

+ +

+Let us define the function +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ + +

+









+ +

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ + +and +$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ + +

+









+ +

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ + +and +$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ + +where \( \eta \) is our by now well-known learning rate. + +

+









+ +

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+

+









+ +

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. + +

+









+ +

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ + +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ + +or just +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ + +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ + +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. + +

+









+ +

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +$$ +df=0. +$$ + +A necessary and sufficient condition is +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +due to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ + +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +$$ +\phi(x,y,z) = 0, +$$ + + resulting in +$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ + +Now we cannot set anymore +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. + +

+









+ +

Adding the Multiplier

+ +

+However, we can add to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ + +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ + +Our multiplier is chosen so that +$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ + +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ + +and +$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ + +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ + +

+









+ +

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ + +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ + + +

    +
  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +
  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). + +

+









+ +

The problem to solve

+ +

+We can rewrite +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). + +

+









+ +

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +resulting in +$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ + +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ + +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. + +

+









+ +

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ + +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. + +

+









+ +

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ + +subject to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ + +and +$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +and +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ + +

+









+ +

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+

+









+ +

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ + +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +For the above example, the kernel reads +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ + +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. + +

+









+ +

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). + +

+









+ +

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +
  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +
  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +
  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +
  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. + +

+









+ +

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+

+









+ +

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. + +

+









+ +

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. + +

+









+ +

A simple example

+ +

+We remind ourselves about the general problem we want to solve +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ + +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ + +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ + +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ + +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=’d’)
+q = matrix(numpy.array([3,4]), tc=’d’)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[’x’] 
+sol[’primal objective’]
+
+

+









+ +

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added + +

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week46/ipynb/ipynb-week46-src.tar.gz b/doc/pub/week46/ipynb/ipynb-week46-src.tar.gz new file mode 100644 index 000000000..0dcc5aab3 Binary files /dev/null and b/doc/pub/week46/ipynb/ipynb-week46-src.tar.gz differ diff --git a/doc/pub/week46/ipynb/week46.ipynb b/doc/pub/week46/ipynb/week46.ipynb new file mode 100644 index 000000000..0cecd2558 --- /dev/null +++ b/doc/pub/week46/ipynb/week46.ipynb @@ -0,0 +1,1894 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Week 46: Support Vector Machines\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "## Support Vector Machines, overarching aims\n", + "\n", + "A Support Vector Machine (SVM) is a very powerful and versatile\n", + "Machine Learning method, capable of performing linear or nonlinear\n", + "classification, regression, and even outlier detection. It is one of\n", + "the most popular models in Machine Learning, and anyone interested in\n", + "Machine Learning should have it in their toolbox. SVMs are\n", + "particularly well suited for classification of complex but small-sized or\n", + "medium-sized datasets. \n", + "\n", + "The case with two well-separated classes only can be understood in an\n", + "intuitive way in terms of lines in a two-dimensional space separating\n", + "the two classes (see figure below).\n", + "\n", + "The basic mathematics behind the SVM is however less familiar to most of us. \n", + "It relies on the definition of hyperplanes and the\n", + "definition of a **margin** which separates classes (in case of\n", + "classification problems) of variables. It is also used for regression\n", + "problems.\n", + "\n", + "With SVMs we distinguish between hard margin and soft margins. The\n", + "latter introduces a so-called softening parameter to be discussed\n", + "below. We distinguish also between linear and non-linear\n", + "approaches. The latter are the most frequent ones since it is rather\n", + "unlikely that we can separate classes easily by say straight lines.\n", + "\n", + "## Hyperplanes and all that\n", + "\n", + "The theory behind support vector machines (SVM hereafter) is based on\n", + "the mathematical description of so-called hyperplanes. Let us start\n", + "with a two-dimensional case. This will also allow us to introduce our\n", + "first SVM examples. These will be tailored to the case of two specific\n", + "classes, as displayed in the figure here based on the usage of the petal data.\n", + "\n", + "We assume here that our data set can be well separated into two\n", + "domains, where a straight line does the job in the separating the two\n", + "classes. Here the two classes are represented by either squares or\n", + "circles." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "from sklearn import datasets\n", + "from sklearn.svm import SVC, LinearSVC\n", + "from sklearn.linear_model import SGDClassifier\n", + "from sklearn.preprocessing import StandardScaler\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "iris = datasets.load_iris()\n", + "X = iris[\"data\"][:, (2, 3)] # petal length, petal width\n", + "y = iris[\"target\"]\n", + "\n", + "setosa_or_versicolor = (y == 0) | (y == 1)\n", + "X = X[setosa_or_versicolor]\n", + "y = y[setosa_or_versicolor]\n", + "\n", + "\n", + "\n", + "C = 5\n", + "alpha = 1 / (C * len(X))\n", + "\n", + "lin_clf = LinearSVC(loss=\"hinge\", C=C, random_state=42)\n", + "svm_clf = SVC(kernel=\"linear\", C=C)\n", + "sgd_clf = SGDClassifier(loss=\"hinge\", learning_rate=\"constant\", eta0=0.001, alpha=alpha,\n", + " max_iter=100000, random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "lin_clf.fit(X_scaled, y)\n", + "svm_clf.fit(X_scaled, y)\n", + "sgd_clf.fit(X_scaled, y)\n", + "\n", + "print(\"LinearSVC: \", lin_clf.intercept_, lin_clf.coef_)\n", + "print(\"SVC: \", svm_clf.intercept_, svm_clf.coef_)\n", + "print(\"SGDClassifier(alpha={:.5f}):\".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)\n", + "\n", + "# Compute the slope and bias of each decision boundary\n", + "w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]\n", + "b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]\n", + "w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]\n", + "b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]\n", + "w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]\n", + "b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]\n", + "\n", + "# Transform the decision boundary lines back to the original scale\n", + "line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])\n", + "line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])\n", + "line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])\n", + "\n", + "# Plot all three decision boundaries\n", + "plt.figure(figsize=(11, 4))\n", + "plt.plot(line1[:, 0], line1[:, 1], \"k:\", label=\"LinearSVC\")\n", + "plt.plot(line2[:, 0], line2[:, 1], \"b--\", linewidth=2, label=\"SVC\")\n", + "plt.plot(line3[:, 0], line3[:, 1], \"r-\", label=\"SGDClassifier\")\n", + "plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\") # label=\"Iris-Versicolor\"\n", + "plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\") # label=\"Iris-Setosa\"\n", + "plt.xlabel(\"Petal length\", fontsize=14)\n", + "plt.ylabel(\"Petal width\", fontsize=14)\n", + "plt.legend(loc=\"upper center\", fontsize=14)\n", + "plt.axis([0, 5.5, 0, 2])\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is a hyperplane?\n", + "\n", + "The aim of the SVM algorithm is to find a hyperplane in a\n", + "$p$-dimensional space, where $p$ is the number of features that\n", + "distinctly classifies the data points.\n", + "\n", + "In a $p$-dimensional space, a hyperplane is what we call an affine subspace of dimension of $p-1$.\n", + "As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is \n", + "a two-dimensional subspace, or stated simply, a plane. \n", + "\n", + "In two dimensions, with the variables $x_1$ and $x_2$, the hyperplane is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+w_1x_1+w_2x_2=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $b$ is the intercept and $w_1$ and $w_2$ define the elements of a vector orthogonal to the line \n", + "$b+w_1x_1+w_2x_2=0$. \n", + "In two dimensions we define the vectors $\\boldsymbol{x} =[x1,x2]$ and $\\boldsymbol{w}=[w1,w2]$. \n", + "We can then rewrite the above equation as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{x}^T\\boldsymbol{w}+b=0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A $p$-dimensional space of features\n", + "\n", + "We limit ourselves to two classes of outputs $y_i$ and assign these classes the values $y_i = \\pm 1$. \n", + "In a $p$-dimensional space of say $p$ features we have a hyperplane defines as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+wx_1+w_2x_2+\\dots +w_px_p=0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we define a \n", + "matrix $\\boldsymbol{X}=\\left[\\boldsymbol{x}_1,\\boldsymbol{x}_2,\\dots, \\boldsymbol{x}_p\\right]$\n", + "of dimension $n\\times p$, where $n$ represents the observations for each feature and each vector $x_i$ is a column vector of the matrix $\\boldsymbol{X}$," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{x}_i = \\begin{bmatrix} x_{i1} \\\\ x_{i2} \\\\ \\dots \\\\ \\dots \\\\ x_{ip} \\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If the above condition is not met for a given vector $\\boldsymbol{x}_i$ we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} >0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "if our output $y_i=1$.\n", + "In this case we say that $\\boldsymbol{x}_i$ lies on one of the sides of the hyperplane and if" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} < 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "for the class of observations $y_i=-1$, \n", + "then $\\boldsymbol{x}_i$ lies on the other side. \n", + "\n", + "Equivalently, for the two classes of observations we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i\\left(b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip}\\right) > 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.\n", + "\n", + "\n", + "## The two-dimensional case\n", + "\n", + "Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional\n", + "plane. To separate the two classes of data points, there are many\n", + "possible lines (hyperplanes if you prefer a more strict naming) \n", + "that could be chosen. Our objective is to find a\n", + "plane that has the maximum margin, i.e the maximum distance between\n", + "data points of both classes. Maximizing the margin distance provides\n", + "some reinforcement so that future data points can be classified with\n", + "more confidence.\n", + "\n", + "What a linear classifier attempts to accomplish is to split the\n", + "feature space into two half spaces by placing a hyperplane between the\n", + "data points. This hyperplane will be our decision boundary. All\n", + "points on one side of the plane will belong to class one and all points\n", + "on the other side of the plane will belong to the second class two.\n", + "\n", + "Unfortunately there are many ways in which we can place a hyperplane\n", + "to divide the data. Below is an example of two candidate hyperplanes\n", + "for our data sample.\n", + "\n", + "## Getting into the details\n", + "\n", + "Let us define the function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(x) = \\boldsymbol{w}^T\\boldsymbol{x}+b = 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "as the function that determines the line $L$ that separates two classes (our two features), see the figure here. \n", + "\n", + "\n", + "Any point defined by $\\boldsymbol{x}_i$ and $\\boldsymbol{x}_2$ on the line $L$ will satisfy $\\boldsymbol{w}^T(\\boldsymbol{x}_1-\\boldsymbol{x}_2)=0$. \n", + "\n", + "The signed distance $\\delta$ from any point defined by a vector $\\boldsymbol{x}$ and a point $\\boldsymbol{x}_0$ on the line $L$ is then" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta = \\frac{1}{\\vert\\vert \\boldsymbol{w}\\vert\\vert}(\\boldsymbol{w}^T\\boldsymbol{x}+b).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## First attempt at a minimization approach\n", + "\n", + "How do we find the parameter $b$ and the vector $\\boldsymbol{w}$? What we could\n", + "do is to define a cost function which now contains the set of all\n", + "misclassified points $M$ and attempt to minimize this function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{w},b) = -\\sum_{i\\in M} y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could now for example define all values $y_i =1$ as misclassified in case we have $\\boldsymbol{w}^T\\boldsymbol{x}_i+b < 0$ and the opposite if we have $y_i=-1$. Taking the derivatives gives us" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial C}{\\partial b} = -\\sum_{i\\in M} y_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial C}{\\partial \\boldsymbol{w}} = -\\sum_{i\\in M} y_ix_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Solving the equations\n", + "\n", + "We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b \\leftarrow b +\\eta \\frac{\\partial C}{\\partial b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{w} \\leftarrow \\boldsymbol{w} +\\eta \\frac{\\partial C}{\\partial \\boldsymbol{w}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\eta$ is our by now well-known learning rate. \n", + "\n", + "\n", + "## Code Example\n", + "\n", + "The equations we discussed above can be coded rather easily (the\n", + "framework is similar to what we developed for logistic\n", + "regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Problems with the Simpler Approach\n", + "\n", + "\n", + "There are however problems with this approach, although it looks\n", + "pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes.\n", + "\n", + "\n", + "For small\n", + "gaps between the entries, we may also end up needing many iterations\n", + "before the solutions converge and if the data cannot be separated\n", + "properly into two distinct classes, we may not experience a converge\n", + "at all.\n", + "\n", + "## A better approach\n", + "\n", + "A better approach is rather to try to define a large margin between\n", + "the two classes (if they are well separated from the beginning).\n", + "\n", + "Thus, we wish to find a margin $M$ with $\\boldsymbol{w}$ normalized to\n", + "$\\vert\\vert \\boldsymbol{w}\\vert\\vert =1$ subject to the condition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, p.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "All points are thus at a signed distance from the decision boundary defined by the line $L$. The parameters $b$ and $w_1$ and $w_2$ define this line. \n", + "\n", + "We seek thus the largest value $M$ defined by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{\\vert \\vert \\boldsymbol{w}\\vert\\vert}y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, n,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or just" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M\\vert \\vert \\boldsymbol{w}\\vert\\vert \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we scale the equation so that $\\vert \\vert \\boldsymbol{w}\\vert\\vert = 1/M$, we have to find the minimum of \n", + "$\\boldsymbol{w}^T\\boldsymbol{w}=\\vert \\vert \\boldsymbol{w}\\vert\\vert$ (the norm) subject to the condition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq 1 \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We have thus defined our margin as the invers of the norm of\n", + "$\\boldsymbol{w}$. We want to minimize the norm in order to have a as large as\n", + "possible margin $M$. Before we proceed, we need to remind ourselves\n", + "about Lagrangian multipliers.\n", + "\n", + "## A quick Reminder on Lagrangian Multipliers\n", + "\n", + "Consider a function of three independent variables $f(x,y,z)$ . For the function $f$ to be an\n", + "extreme we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df=0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A necessary and sufficient condition is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "due to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In many problems the variables $x,y,z$ are often subject to constraints (such as those above for the margin)\n", + "so that they are no longer all independent. It is possible at least in principle to use each \n", + "constraint to eliminate one variable\n", + "and to proceed with a new and smaller set of independent varables.\n", + "\n", + "The use of so-called Lagrangian multipliers is an alternative technique when the elimination\n", + "of variables is incovenient or undesirable. Assume that we have an equation of constraint on \n", + "the variables $x,y,z$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\phi(x,y,z) = 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "d\\phi = \\frac{\\partial \\phi}{\\partial x}dx+\\frac{\\partial \\phi}{\\partial y}dy+\\frac{\\partial \\phi}{\\partial z}dz =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we cannot set anymore" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "if $df=0$ is wanted\n", + "because there are now only two independent variables! Assume $x$ and $y$ are the independent \n", + "variables.\n", + "Then $dz$ is no longer arbitrary.\n", + "\n", + "## Adding the Multiplier\n", + "\n", + "However, we can add to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "a multiplum of $d\\phi$, viz. $\\lambda d\\phi$, resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df+\\lambda d\\phi = (\\frac{\\partial f}{\\partial z}+\\lambda\n", + "\\frac{\\partial \\phi}{\\partial x})dx+(\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y})dy+\n", + "(\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z})dz =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Our multiplier is chosen so that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z} =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We need to remember that we took $dx$ and $dy$ to be arbitrary and thus we must have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x}+\\lambda\\frac{\\partial \\phi}{\\partial x} =0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y} =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When all these equations are satisfied, $df=0$. We have four unknowns, $x,y,z$ and\n", + "$\\lambda$. Actually we want only $x,y,z$, $\\lambda$ needs not to be determined, \n", + "it is therefore often called\n", + "Lagrange's undetermined multiplier.\n", + "If we have a set of constraints $\\phi_k$ we have the equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x_i}+\\sum_k\\lambda_k\\frac{\\partial \\phi_k}{\\partial x_i} =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Setting up the Problem\n", + "In order to solve the above problem, we define the following Lagrangian function to be minimized" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}(\\lambda,b,\\boldsymbol{w})=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-1\\right],\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\lambda_i$ is a so-called Lagrange multiplier subject to the condition $\\lambda_i \\geq 0$.\n", + "\n", + "Taking the derivatives with respect to $b$ and $\\boldsymbol{w}$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inserting these constraints into the equation for ${\\cal L}$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to the constraints $\\lambda_i\\geq 0$ and $\\sum_i\\lambda_iy_i=0$. \n", + "We must in addition satisfy the [Karush-Kuhn-Tucker](https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions) (KKT) condition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -1\\right] \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. If $\\lambda_i > 0$, then $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1$ and we say that $x_i$ is on the boundary.\n", + "\n", + "2. If $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)> 1$, we say $x_i$ is not on the boundary and we set $\\lambda_i=0$. \n", + "\n", + "When $\\lambda_i > 0$, the vectors $\\boldsymbol{x}_i$ are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin $M$. \n", + "\n", + "## The problem to solve\n", + "\n", + "We can rewrite" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and its constraints in terms of a matrix-vector problem where we minimize w.r.t. $\\lambda$ the following problem" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1\\boldsymbol{x}_1^T\\boldsymbol{x}_1 & y_1y_2\\boldsymbol{x}_1^T\\boldsymbol{x}_2 & \\dots & \\dots & y_1y_n\\boldsymbol{x}_1^T\\boldsymbol{x}_n \\\\\n", + "y_2y_1\\boldsymbol{x}_2^T\\boldsymbol{x}_1 & y_2y_2\\boldsymbol{x}_2^T\\boldsymbol{x}_2 & \\dots & \\dots & y_1y_n\\boldsymbol{x}_2^T\\boldsymbol{x}_n \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "y_ny_1\\boldsymbol{x}_n^T\\boldsymbol{x}_1 & y_ny_2\\boldsymbol{x}_n^T\\boldsymbol{x}_2 & \\dots & \\dots & y_ny_n\\boldsymbol{x}_n^T\\boldsymbol{x}_n \\\\\n", + "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{1}\\boldsymbol{\\lambda},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", + "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", + "\n", + "\n", + "## The last steps\n", + "\n", + "Solving the above problem, yields the values of $\\lambda_i$.\n", + "To find the coefficients of your hyperplane we need simply to compute" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{w}=\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With our vector $\\boldsymbol{w}$ we can in turn find the value of the intercept $b$ (here in two dimensions) via" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b = \\frac{1}{y_i}-\\boldsymbol{w}^T\\boldsymbol{x}_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or if we write it out in terms of the support vectors only, with $N_s$ being their number, we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b = \\frac{1}{N_s}\\sum_{j\\in N_s}\\left(y_j-\\sum_{i=1}^n\\lambda_iy_i\\boldsymbol{x}_i^T\\boldsymbol{x}_j\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With our hyperplane coefficients we can use our classifier to assign any observation by simply using" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i = \\mathrm{sign}(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Below we discuss how to find the optimal values of $\\lambda_i$. Before we proceed however, we discuss now the so-called soft classifier. \n", + "\n", + "## A soft classifier\n", + "\n", + "Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.\n", + "\n", + "Suppose now that classes overlap in feature space, as shown in the\n", + "figure here. One way to deal with this problem before we define the\n", + "so-called **kernel approach**, is to allow a kind of slack in the sense\n", + "that we allow some points to be on the wrong side of the margin.\n", + "\n", + "We introduce thus the so-called **slack** variables $\\boldsymbol{\\xi} =[\\xi_1,x_2,\\dots,x_n]$ and \n", + "modify our previous equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with the requirement $\\xi_i\\geq 0$. The total violation is now $\\sum_i\\xi$. \n", + "The value $\\xi_i$ in the constraint the last constraint corresponds to the amount by which the prediction\n", + "$y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1$ is on the wrong side of its margin. Hence by bounding the sum $\\sum_i \\xi_i$,\n", + "we bound the total amount by which predictions fall on the wrong side of their margins.\n", + "\n", + "Misclassifications occur when $\\xi_i > 1$. Thus bounding the total sum by some value $C$ bounds in turn the total number of\n", + "misclassifications.\n", + "\n", + "## Soft optmization problem\n", + "\n", + "\n", + "This has in turn the consequences that we change our optmization problem to finding the minimum of" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-(1-\\xi_)\\right]+C\\sum_{i=1}^n\\xi_i-\\sum_{i=1}^n\\gamma_i\\xi_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i \\hspace{0.1cm}\\forall i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with the requirement $\\xi_i\\geq 0$.\n", + "\n", + "Taking the derivatives with respect to $b$ and $\\boldsymbol{w}$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\lambda_i = C-\\gamma_i \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inserting these constraints into the equation for ${\\cal L}$ we obtain the same equation as before" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "but now subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ and $0\\leq\\lambda_i \\leq C$. \n", + "We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "5\n", + "0\n", + " \n", + "<\n", + "<\n", + "<\n", + "!\n", + "!\n", + "M\n", + "A\n", + "T\n", + "H\n", + "_\n", + "B\n", + "L\n", + "O\n", + "C\n", + "K" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\gamma_i\\xi_i = 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -(1-\\xi_) \\geq 0 \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Kernels and non-linearity\n", + "\n", + "The cases we have studied till now, were all characterized by two classes\n", + "with a close to linear separability. The classifiers we have described\n", + "so far find linear boundaries in our input feature space. It is\n", + "possible to make our procedure more flexible by exploring the feature\n", + "space using other basis expansions such as higher-order polynomials,\n", + "wavelets, splines etc.\n", + "\n", + "If our feature space is not easy to separate, as shown in the figure\n", + "here, we can achieve a better separation by introducing more complex\n", + "basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to \n", + "obtain a separation between the classes which is almost linear. \n", + "\n", + "The change of basis, from $x\\rightarrow z=\\phi(x)$ leads to the same type of equations to be solved, except that\n", + "we need to introduce for example a polynomial transformation to a two-dimensional training set." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import os\n", + "\n", + "np.random.seed(42)\n", + "\n", + "# To plot pretty figures\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "from sklearn import datasets\n", + "\n", + "\n", + "\n", + "X1D = np.linspace(-4, 4, 9).reshape(-1, 1)\n", + "X2D = np.c_[X1D, X1D**2]\n", + "y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.plot(X1D[:, 0][y==0], np.zeros(4), \"bs\")\n", + "plt.plot(X1D[:, 0][y==1], np.zeros(5), \"g^\")\n", + "plt.gca().get_yaxis().set_ticks([])\n", + "plt.xlabel(r\"$x_1$\", fontsize=20)\n", + "plt.axis([-4.5, 4.5, -0.2, 0.2])\n", + "\n", + "plt.subplot(122)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.axvline(x=0, color='k')\n", + "plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], \"bs\")\n", + "plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], \"g^\")\n", + "plt.xlabel(r\"$x_1$\", fontsize=20)\n", + "plt.ylabel(r\"$x_2$\", fontsize=20, rotation=0)\n", + "plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])\n", + "plt.plot([-4.5, 4.5], [6.5, 6.5], \"r--\", linewidth=3)\n", + "plt.axis([-4.5, 4.5, -1, 17])\n", + "plt.subplots_adjust(right=1)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The equations\n", + "\n", + "Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with $x_i$ and $y_i$ as variables)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "z = \\phi(x_i) =\\left(x_i^2, y_i^2, \\sqrt{2}x_iy_i\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{z}_i^T\\boldsymbol{z}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$, and for the support vectors" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{z}_i+b)= 1 \\hspace{0.1cm}\\forall i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "from which we also find $b$.\n", + "To compute $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we define the kernel $K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\boldsymbol{z}_i^T\\boldsymbol{z}_j= \\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the above example, the kernel reads" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=[x_i^2, y_i^2, \\sqrt{2}x_iy_i]^T\\begin{bmatrix} x_j^2 \\\\ y_j^2 \\\\ \\sqrt{2}x_jy_j \\end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We note that this is nothing but the dot product of the two original\n", + "vectors $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$. Instead of thus computing the\n", + "product in the Lagrangian of $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we simply compute\n", + "the dot product $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$.\n", + "\n", + "\n", + "This leads to the so-called\n", + "kernel trick and the result leads to the same as if we went through\n", + "the trouble of performing the transformation\n", + "$\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j)$ during the SVM calculations.\n", + "\n", + "\n", + "## The problem to solve\n", + "Using our definition of the kernel We can rewrite again the Lagrangian" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{z}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ in terms of a convex optimization problem" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n", + "y_2y_1K(\\boldsymbol{x}_2,\\boldsymbol{x}_1) & y_2y_2(\\boldsymbol{x}_2,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_2,\\boldsymbol{x}_n) \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "y_ny_1K(\\boldsymbol{x}_n,\\boldsymbol{x}_1) & y_ny_2K(\\boldsymbol{x}_n\\boldsymbol{x}_2) & \\dots & \\dots & y_ny_nK(\\boldsymbol{x}_n,\\boldsymbol{x}_n) \\\\\n", + "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{1}\\boldsymbol{\\lambda},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", + "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", + "If we add the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$.\n", + "\n", + "We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{\\lambda}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{\\lambda}^T\\boldsymbol{P}\\boldsymbol{\\lambda}+\\boldsymbol{q}^T\\boldsymbol{\\lambda},\\\\ \\nonumber\n", + " &\\mathrm{subject\\hspace{0.1cm}to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h} \\hspace{0.2cm} \\wedge \\boldsymbol{A}\\boldsymbol{\\lambda}=f.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Below we discuss how to solve these equations. Here we note that the matrix $\\boldsymbol{P}$ has matrix elements $p_{ij}=y_iy_jK(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$.\n", + "Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$ leads to $f=0$ and $\\boldsymbol{A}=\\boldsymbol{y}$. How to set up the matrix $\\boldsymbol{G}$ is discussed later. Here note that the inequalities $0\\leq \\lambda_i \\leq C$ can be split up into\n", + "$0\\leq \\lambda_i$ and $\\lambda_i \\leq C$. These two inequalities define then the matrix $\\boldsymbol{G}$ and the vector $\\boldsymbol{h}$.\n", + "\n", + "\n", + "## Different kernels and Mercer's theorem\n", + "\n", + "There are several popular kernels being used. These are\n", + "1. Linear: $K(\\boldsymbol{x},\\boldsymbol{y})=\\boldsymbol{x}^T\\boldsymbol{y}$,\n", + "\n", + "2. Polynomial: $K(\\boldsymbol{x},\\boldsymbol{y})=(\\boldsymbol{x}^T\\boldsymbol{y}+\\gamma)^d$,\n", + "\n", + "3. Gaussian Radial Basis Function: $K(\\boldsymbol{x},\\boldsymbol{y})=\\exp{\\left(-\\gamma\\vert\\vert\\boldsymbol{x}-\\boldsymbol{y}\\vert\\vert^2\\right)}$,\n", + "\n", + "4. Tanh: $K(\\boldsymbol{x},\\boldsymbol{y})=\\tanh{(\\boldsymbol{x}^T\\boldsymbol{y}+\\gamma)}$,\n", + "\n", + "and many other ones.\n", + "\n", + "An important theorem for us is [Mercer's\n", + "theorem](https://en.wikipedia.org/wiki/Mercer%27s_theorem). The\n", + "theorem states that if a kernel function $K$ is symmetric, continuous\n", + "and leads to a positive semi-definite matrix $\\boldsymbol{P}$ then there\n", + "exists a function $\\phi$ that maps $\\boldsymbol{x}_i$ and $\\boldsymbol{x}_j$ into\n", + "another space (possibly with much higher dimensions) such that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So you can use $K$ as a kernel since you know $\\phi$ exists, even if\n", + "you don’t know what $\\phi$ is. \n", + "\n", + "Note that some frequently used kernels (such as the Sigmoid kernel)\n", + "don’t respect all of Mercer’s conditions, yet they generally work well\n", + "in practice.\n", + "\n", + "\n", + "## The moons example" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from __future__ import division, print_function, unicode_literals\n", + "\n", + "import numpy as np\n", + "np.random.seed(42)\n", + "\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "from sklearn import datasets\n", + "\n", + "\n", + "\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.svm import LinearSVC\n", + "\n", + "\n", + "from sklearn.datasets import make_moons\n", + "X, y = make_moons(n_samples=100, noise=0.15, random_state=42)\n", + "\n", + "def plot_dataset(X, y, axes):\n", + " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"bs\")\n", + " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"g^\")\n", + " plt.axis(axes)\n", + " plt.grid(True, which='both')\n", + " plt.xlabel(r\"$x_1$\", fontsize=20)\n", + " plt.ylabel(r\"$x_2$\", fontsize=20, rotation=0)\n", + "\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "plt.show()\n", + "\n", + "from sklearn.datasets import make_moons\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "\n", + "polynomial_svm_clf = Pipeline([\n", + " (\"poly_features\", PolynomialFeatures(degree=3)),\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", LinearSVC(C=10, loss=\"hinge\", random_state=42))\n", + " ])\n", + "\n", + "polynomial_svm_clf.fit(X, y)\n", + "\n", + "def plot_predictions(clf, axes):\n", + " x0s = np.linspace(axes[0], axes[1], 100)\n", + " x1s = np.linspace(axes[2], axes[3], 100)\n", + " x0, x1 = np.meshgrid(x0s, x1s)\n", + " X = np.c_[x0.ravel(), x1.ravel()]\n", + " y_pred = clf.predict(X).reshape(x0.shape)\n", + " y_decision = clf.decision_function(X).reshape(x0.shape)\n", + " plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)\n", + " plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)\n", + "\n", + "plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "\n", + "plt.show()\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "\n", + "poly_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"poly\", degree=3, coef0=1, C=5))\n", + " ])\n", + "poly_kernel_svm_clf.fit(X, y)\n", + "\n", + "poly100_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"poly\", degree=10, coef0=100, C=5))\n", + " ])\n", + "poly100_kernel_svm_clf.fit(X, y)\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "plt.title(r\"$d=3, r=1, C=5$\", fontsize=18)\n", + "\n", + "plt.subplot(122)\n", + "plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "plt.title(r\"$d=10, r=100, C=5$\", fontsize=18)\n", + "\n", + "plt.show()\n", + "\n", + "def gaussian_rbf(x, landmark, gamma):\n", + " return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)\n", + "\n", + "gamma = 0.3\n", + "\n", + "x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)\n", + "x2s = gaussian_rbf(x1s, -2, gamma)\n", + "x3s = gaussian_rbf(x1s, 1, gamma)\n", + "\n", + "XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]\n", + "yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c=\"red\")\n", + "plt.plot(X1D[:, 0][yk==0], np.zeros(4), \"bs\")\n", + "plt.plot(X1D[:, 0][yk==1], np.zeros(5), \"g^\")\n", + "plt.plot(x1s, x2s, \"g--\")\n", + "plt.plot(x1s, x3s, \"b:\")\n", + "plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])\n", + "plt.xlabel(r\"$x_1$\", fontsize=20)\n", + "plt.ylabel(r\"Similarity\", fontsize=14)\n", + "plt.annotate(r'$\\mathbf{x}$',\n", + " xy=(X1D[3, 0], 0),\n", + " xytext=(-0.5, 0.20),\n", + " ha=\"center\",\n", + " arrowprops=dict(facecolor='black', shrink=0.1),\n", + " fontsize=18,\n", + " )\n", + "plt.text(-2, 0.9, \"$x_2$\", ha=\"center\", fontsize=20)\n", + "plt.text(1, 0.9, \"$x_3$\", ha=\"center\", fontsize=20)\n", + "plt.axis([-4.5, 4.5, -0.1, 1.1])\n", + "\n", + "plt.subplot(122)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.axvline(x=0, color='k')\n", + "plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], \"bs\")\n", + "plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], \"g^\")\n", + "plt.xlabel(r\"$x_2$\", fontsize=20)\n", + "plt.ylabel(r\"$x_3$ \", fontsize=20, rotation=0)\n", + "plt.annotate(r'$\\phi\\left(\\mathbf{x}\\right)$',\n", + " xy=(XK[3, 0], XK[3, 1]),\n", + " xytext=(0.65, 0.50),\n", + " ha=\"center\",\n", + " arrowprops=dict(facecolor='black', shrink=0.1),\n", + " fontsize=18,\n", + " )\n", + "plt.plot([-0.1, 1.1], [0.57, -0.1], \"r--\", linewidth=3)\n", + "plt.axis([-0.1, 1.1, -0.1, 1.1])\n", + " \n", + "plt.subplots_adjust(right=1)\n", + "\n", + "plt.show()\n", + "\n", + "\n", + "x1_example = X1D[3, 0]\n", + "for landmark in (-2, 1):\n", + " k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)\n", + " print(\"Phi({}, {}) = {}\".format(x1_example, landmark, k))\n", + "\n", + "rbf_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"rbf\", gamma=5, C=0.001))\n", + " ])\n", + "rbf_kernel_svm_clf.fit(X, y)\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "\n", + "gamma1, gamma2 = 0.1, 5\n", + "C1, C2 = 0.001, 1000\n", + "hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)\n", + "\n", + "svm_clfs = []\n", + "for gamma, C in hyperparams:\n", + " rbf_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"rbf\", gamma=gamma, C=C))\n", + " ])\n", + " rbf_kernel_svm_clf.fit(X, y)\n", + " svm_clfs.append(rbf_kernel_svm_clf)\n", + "\n", + "plt.figure(figsize=(11, 7))\n", + "\n", + "for i, svm_clf in enumerate(svm_clfs):\n", + " plt.subplot(221 + i)\n", + " plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])\n", + " plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + " gamma, C = hyperparams[i]\n", + " plt.title(r\"$\\gamma = {}, C = {}$\".format(gamma, C), fontsize=16)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mathematical optimization of convex functions\n", + "\n", + "A mathematical (quadratic) optimization problem, or just optimization problem, has the form" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{\\lambda}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{\\lambda}^T\\boldsymbol{P}\\boldsymbol{\\lambda}+\\boldsymbol{q}^T\\boldsymbol{\\lambda},\\\\ \\nonumber\n", + " &\\mathrm{subject\\hspace{0.1cm}to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h} \\wedge \\boldsymbol{A}\\boldsymbol{\\lambda}=f.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to some constraints for say a selected set $i=1,2,\\dots, n$.\n", + "In our case we are optimizing with respect to the Lagrangian multipliers $\\lambda_i$, and the\n", + "vector $\\boldsymbol{\\lambda}=[\\lambda_1, \\lambda_2,\\dots, \\lambda_n]$ is the optimization variable we are dealing with.\n", + "\n", + "In our case we are particularly interested in a class of optimization problems called convex optmization problems. \n", + "In our discussion on gradient descent methods we discussed at length the definition of a convex function. \n", + "\n", + "Convex optimization problems play a central role in applied mathematics and we recommend strongly [Boyd and Vandenberghe's text on the topics](http://web.stanford.edu/~boyd/cvxbook/).\n", + "\n", + "\n", + "\n", + "## How do we solve these problems?\n", + "\n", + "If we use Python as programming language and wish to venture beyond\n", + "**scikit-learn**, **tensorflow** and similar software which makes our\n", + "lives so much easier, we need to dive into the wonderful world of\n", + "quadratic programming. We can, if we wish, solve the minimization\n", + "problem using say standard gradient methods or conjugate gradient\n", + "methods. However, these methods tend to exhibit a rather slow\n", + "converge. So, welcome to the promised land of quadratic programming.\n", + "\n", + "The functions we need are contained in the quadratic programming package **CVXOPT** and we need to import it together with **numpy** as" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy\n", + "import cvxopt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This will make our life much easier. You don't need t write your own optimizer.\n", + "\n", + "\n", + "## A simple example\n", + "\n", + "We remind ourselves about the general problem we want to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{x}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{P}\\boldsymbol{x}+\\boldsymbol{q}^T\\boldsymbol{x},\\\\ \\nonumber\n", + " &\\mathrm{subject\\hspace{0.1cm} to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{x} \\preceq \\boldsymbol{h} \\wedge \\boldsymbol{A}\\boldsymbol{x}=f.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{x}\\hspace{0.2cm} \\frac{1}{2}x^2+5x+3y \\\\ \\nonumber\n", + " &\\mathrm{subject to} \\\\ \\nonumber\n", + " &x, y \\geq 0 \\\\ \\nonumber\n", + " &x+3y \\geq 15 \\\\ \\nonumber\n", + " &2x+5y \\leq 100 \\\\ \\nonumber\n", + " &3x+4y \\leq 80. \\\\ \\nonumber\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2}\\begin{bmatrix} x\\\\ y \\end{bmatrix}^T \\begin{bmatrix} 1 & 0\\\\ 0 & 0 \\end{bmatrix} \\begin{bmatrix} x \\\\ y \\end{bmatrix} + \\begin{bmatrix}3\\\\ 4 \\end{bmatrix}^T \\begin{bmatrix}x \\\\ y \\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Similarly, we can now set up the inequalities (we need to change $\\geq$ to $\\leq$ by multiplying with $-1$ on bot sides) as the following matrix-vector equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{bmatrix} -1 & 0 \\\\ 0 & -1 \\\\ -1 & -3 \\\\ 2 & 5 \\\\ 3 & 4\\end{bmatrix}\\begin{bmatrix} x \\\\ y\\end{bmatrix} \\preceq \\begin{bmatrix}0 \\\\ 0\\\\ -15 \\\\ 100 \\\\ 80\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We have collapsed all the inequalities into a single matrix $\\boldsymbol{G}$. We see also that our matrix" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{P} =\\begin{bmatrix} 1 & 0\\\\ 0 & 0 \\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is clearly positive semi-definite (all eigenvalues larger or equal zero). \n", + "Finally, the vector $\\boldsymbol{h}$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{h} = \\begin{bmatrix}0 \\\\ 0\\\\ -15 \\\\ 100 \\\\ 80\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since we don't have any equalities the matrix $\\boldsymbol{A}$ is set to zero\n", + "The following code solves the equations for us" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Import the necessary packages\n", + "import numpy\n", + "from cvxopt import matrix\n", + "from cvxopt import solvers\n", + "P = matrix(numpy.diag([1,0]), tc=’d’)\n", + "q = matrix(numpy.array([3,4]), tc=’d’)\n", + "G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)\n", + "h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)\n", + "# Construct the QP, invoke solver\n", + "sol = solvers.qp(P,q,G,h)\n", + "# Extract optimal value and solution\n", + "sol[’x’] \n", + "sol[’primal objective’]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Back to the more realistic cases\n", + "\n", + "We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the **slack** parameter $C$ we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n", + "y_2y_1K(\\boldsymbol{x}_2,\\boldsymbol{x}_1) & y_2y_2K(\\boldsymbol{x}_2,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_2,\\boldsymbol{x}_n) \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "y_ny_1K(\\boldsymbol{x}_n,\\boldsymbol{x}_1) & y_ny_2K(\\boldsymbol{x}_n\\boldsymbol{x}_2) & \\dots & \\dots & y_ny_nK(\\boldsymbol{x}_n,\\boldsymbol{x}_n) \\\\\n", + "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{I}\\boldsymbol{\\lambda},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", + "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", + "With the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$.\n", + "\n", + "**code will be added**" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/doc/pub/week47/html/._week47-bs000.html b/doc/pub/week47/html/._week47-bs000.html new file mode 100644 index 000000000..98a4b1977 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs000.html @@ -0,0 +1,224 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +

 

 

 

+ + + + + + +
+

Week 47: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs001.html b/doc/pub/week47/html/._week47-bs001.html new file mode 100644 index 000000000..3227c5bab --- /dev/null +++ b/doc/pub/week47/html/._week47-bs001.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs002.html b/doc/pub/week47/html/._week47-bs002.html new file mode 100644 index 000000000..a548ff7ea --- /dev/null +++ b/doc/pub/week47/html/._week47-bs002.html @@ -0,0 +1,283 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs003.html b/doc/pub/week47/html/._week47-bs003.html new file mode 100644 index 000000000..5f506ea07 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs003.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +$$ +b+w_1x_1+w_2x_2=0, +$$ + +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs004.html b/doc/pub/week47/html/._week47-bs004.html new file mode 100644 index 000000000..ab28ae589 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs004.html @@ -0,0 +1,240 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ + +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ + +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ + +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ + +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ + +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs005.html b/doc/pub/week47/html/._week47-bs005.html new file mode 100644 index 000000000..e592d7f37 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs005.html @@ -0,0 +1,226 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs006.html b/doc/pub/week47/html/._week47-bs006.html new file mode 100644 index 000000000..279880a32 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs006.html @@ -0,0 +1,222 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Getting into the details

+ +

+Let us define the function +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs007.html b/doc/pub/week47/html/._week47-bs007.html new file mode 100644 index 000000000..578b42b7b --- /dev/null +++ b/doc/pub/week47/html/._week47-bs007.html @@ -0,0 +1,226 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ + +and +$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs008.html b/doc/pub/week47/html/._week47-bs008.html new file mode 100644 index 000000000..b41b77b9d --- /dev/null +++ b/doc/pub/week47/html/._week47-bs008.html @@ -0,0 +1,220 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ + +and +$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ + +where \( \eta \) is our by now well-known learning rate. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs009.html b/doc/pub/week47/html/._week47-bs009.html new file mode 100644 index 000000000..ee9128291 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs009.html @@ -0,0 +1,217 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs010.html b/doc/pub/week47/html/._week47-bs010.html new file mode 100644 index 000000000..3d3019a64 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs010.html @@ -0,0 +1,220 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs011.html b/doc/pub/week47/html/._week47-bs011.html new file mode 100644 index 000000000..2838d27e8 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs011.html @@ -0,0 +1,246 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ + +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ + +or just +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ + +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ + +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs012.html b/doc/pub/week47/html/._week47-bs012.html new file mode 100644 index 000000000..60f17ed0b --- /dev/null +++ b/doc/pub/week47/html/._week47-bs012.html @@ -0,0 +1,254 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +$$ +df=0. +$$ + +A necessary and sufficient condition is +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +due to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ + +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +$$ +\phi(x,y,z) = 0, +$$ + + resulting in +$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ + +Now we cannot set anymore +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs013.html b/doc/pub/week47/html/._week47-bs013.html new file mode 100644 index 000000000..2e5306ac0 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs013.html @@ -0,0 +1,247 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Adding the Multiplier

+ +

+However, we can add to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ + +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ + +Our multiplier is chosen so that +$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ + +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ + +and +$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ + +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs014.html b/doc/pub/week47/html/._week47-bs014.html new file mode 100644 index 000000000..83f59fcb3 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs014.html @@ -0,0 +1,245 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ + +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ + + +

    +
  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +
  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs015.html b/doc/pub/week47/html/._week47-bs015.html new file mode 100644 index 000000000..9ef26d30d --- /dev/null +++ b/doc/pub/week47/html/._week47-bs015.html @@ -0,0 +1,228 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The problem to solve

+ +

+We can rewrite +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs016.html b/doc/pub/week47/html/._week47-bs016.html new file mode 100644 index 000000000..349e5ba87 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs016.html @@ -0,0 +1,238 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +resulting in +$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ + +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ + +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs017.html b/doc/pub/week47/html/._week47-bs017.html new file mode 100644 index 000000000..e4ac520da --- /dev/null +++ b/doc/pub/week47/html/._week47-bs017.html @@ -0,0 +1,239 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ + +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs018.html b/doc/pub/week47/html/._week47-bs018.html new file mode 100644 index 000000000..950a843c5 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs018.html @@ -0,0 +1,256 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ + +subject to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ + +and +$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +and +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs019.html b/doc/pub/week47/html/._week47-bs019.html new file mode 100644 index 000000000..5466386e7 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs019.html @@ -0,0 +1,274 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs020.html b/doc/pub/week47/html/._week47-bs020.html new file mode 100644 index 000000000..d569f9c6e --- /dev/null +++ b/doc/pub/week47/html/._week47-bs020.html @@ -0,0 +1,245 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ + +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +For the above example, the kernel reads +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ + +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs021.html b/doc/pub/week47/html/._week47-bs021.html new file mode 100644 index 000000000..3740fcf70 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs021.html @@ -0,0 +1,235 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs022.html b/doc/pub/week47/html/._week47-bs022.html new file mode 100644 index 000000000..c94f39f0d --- /dev/null +++ b/doc/pub/week47/html/._week47-bs022.html @@ -0,0 +1,236 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +
  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +
  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +
  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +
  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs023.html b/doc/pub/week47/html/._week47-bs023.html new file mode 100644 index 000000000..a13f59672 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs023.html @@ -0,0 +1,393 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs024.html b/doc/pub/week47/html/._week47-bs024.html new file mode 100644 index 000000000..250925cbc --- /dev/null +++ b/doc/pub/week47/html/._week47-bs024.html @@ -0,0 +1,221 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs025.html b/doc/pub/week47/html/._week47-bs025.html new file mode 100644 index 000000000..f36eae7cd --- /dev/null +++ b/doc/pub/week47/html/._week47-bs025.html @@ -0,0 +1,221 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. + +

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs026.html b/doc/pub/week47/html/._week47-bs026.html new file mode 100644 index 000000000..937c97777 --- /dev/null +++ b/doc/pub/week47/html/._week47-bs026.html @@ -0,0 +1,262 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

A simple example

+ +

+We remind ourselves about the general problem we want to solve +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ + +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ + +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ + +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ + +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=’d’)
+q = matrix(numpy.array([3,4]), tc=’d’)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[’x’] 
+sol[’primal objective’]
+
+

+

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/._week47-bs027.html b/doc/pub/week47/html/._week47-bs027.html new file mode 100644 index 000000000..f92cb624d --- /dev/null +++ b/doc/pub/week47/html/._week47-bs027.html @@ -0,0 +1,216 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + +

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added + +

+ +

+ +

+ + +
+ + + + + + + +
+ +
+ + + + + + diff --git a/doc/pub/week47/html/reveal.js/.gitignore b/doc/pub/week47/html/reveal.js/.gitignore new file mode 100644 index 000000000..a5df3133d --- /dev/null +++ b/doc/pub/week47/html/reveal.js/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +.svn +log/*.log +tmp/** +node_modules/ +.sass-cache +css/reveal.min.css +js/reveal.min.js diff --git a/doc/pub/week47/html/reveal.js/.travis.yml b/doc/pub/week47/html/reveal.js/.travis.yml new file mode 100644 index 000000000..165d9ae9f --- /dev/null +++ b/doc/pub/week47/html/reveal.js/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.10 +before_script: + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/week47/html/reveal.js/CONTRIBUTING.md b/doc/pub/week47/html/reveal.js/CONTRIBUTING.md new file mode 100644 index 000000000..c2091e88f --- /dev/null +++ b/doc/pub/week47/html/reveal.js/CONTRIBUTING.md @@ -0,0 +1,23 @@ +## Contributing + +Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. + + +### Personal Support +If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). + + +### Bug Reports +When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. + + +### Pull Requests +- Should follow the coding style of the file you work in, most importantly: + - Tabs to indent + - Single-quoted strings +- Should be made towards the **dev branch** +- Should be submitted from a feature/topic branch (not your master) + + +### Plugins +Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/pub/week47/html/reveal.js/Gruntfile.js b/doc/pub/week47/html/reveal.js/Gruntfile.js new file mode 100644 index 000000000..b257e8f32 --- /dev/null +++ b/doc/pub/week47/html/reveal.js/Gruntfile.js @@ -0,0 +1,140 @@ +/* global module:false */ +module.exports = function(grunt) { + var port = grunt.option('port') || 8000; + // Project configuration + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + meta: { + banner: + '/*!\n' + + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + + ' * http://lab.hakim.se/reveal-js\n' + + ' * MIT licensed\n' + + ' *\n' + + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + + ' */' + }, + + qunit: { + files: [ 'test/*.html' ] + }, + + uglify: { + options: { + banner: '<%= meta.banner %>\n' + }, + build: { + src: 'js/reveal.js', + dest: 'js/reveal.min.js' + } + }, + + cssmin: { + compress: { + files: { + 'css/reveal.min.css': [ 'css/reveal.css' ] + } + } + }, + + sass: { + main: { + files: { + 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', + 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', + 'css/theme/cbc.css': 'css/theme/source/cbc.scss', + 'css/theme/default.css': 'css/theme/source/default.scss', + 'css/theme/beige.css': 'css/theme/source/beige.scss', + 'css/theme/night.css': 'css/theme/source/night.scss', + 'css/theme/serif.css': 'css/theme/source/serif.scss', + 'css/theme/simple.css': 'css/theme/source/simple.scss', + 'css/theme/sky.css': 'css/theme/source/sky.scss', + 'css/theme/moon.css': 'css/theme/source/moon.scss', + 'css/theme/solarized.css': 'css/theme/source/solarized.scss', + 'css/theme/blood.css': 'css/theme/source/blood.scss' + } + } + }, + + jshint: { + options: { + curly: false, + eqeqeq: true, + immed: true, + latedef: true, + newcap: true, + noarg: true, + sub: true, + undef: true, + eqnull: true, + browser: true, + expr: true, + globals: { + head: false, + module: false, + console: false, + unescape: false + } + }, + files: [ 'Gruntfile.js', 'js/reveal.js' ] + }, + + connect: { + server: { + options: { + port: port, + base: '.' + } + } + }, + + zip: { + 'reveal-js-presentation.zip': [ + 'index.html', + 'css/**', + 'js/**', + 'lib/**', + 'images/**', + 'plugin/**' + ] + }, + + watch: { + main: { + files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], + tasks: 'default' + }, + theme: { + files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], + tasks: 'themes' + } + } + + }); + + // Dependencies + grunt.loadNpmTasks( 'grunt-contrib-qunit' ); + grunt.loadNpmTasks( 'grunt-contrib-jshint' ); + grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); + grunt.loadNpmTasks( 'grunt-contrib-uglify' ); + grunt.loadNpmTasks( 'grunt-contrib-watch' ); + grunt.loadNpmTasks( 'grunt-contrib-sass' ); + grunt.loadNpmTasks( 'grunt-contrib-connect' ); + grunt.loadNpmTasks( 'grunt-zip' ); + + // Default task + grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); + + // Theme task + grunt.registerTask( 'themes', [ 'sass' ] ); + + // Package presentation to archive + grunt.registerTask( 'package', [ 'default', 'zip' ] ); + + // Serve presentation locally + grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); + + // Run tests + grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); + +}; diff --git a/doc/pub/week47/html/reveal.js/LICENSE b/doc/pub/week47/html/reveal.js/LICENSE new file mode 100644 index 000000000..09623076f --- /dev/null +++ b/doc/pub/week47/html/reveal.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Hakim El Hattab, http://hakim.se + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/doc/pub/week47/html/reveal.js/README.md b/doc/pub/week47/html/reveal.js/README.md new file mode 100644 index 000000000..573b19597 --- /dev/null +++ b/doc/pub/week47/html/reveal.js/README.md @@ -0,0 +1,1052 @@ +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) + +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). + +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. + + +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. +- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. +- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! +- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. +- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. + +## Online Editor + +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). + + +## Instructions + +### Markup + +Markup hierarchy needs to be ``
`` where the ``
`` represents one slide and can be repeated indefinitely. If you place multiple ``
``'s inside of another ``
`` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: + +```html +
+
+
Single Horizontal Slide
+
+
Vertical Slide 1
+
Vertical Slide 2
+
+
+
+``` + +### Markdown + +It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
``` elements and wrap the contents in a ``` +
+``` + +#### External Markdown + +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. + +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). + +```html +
+
+``` + +#### Element Attributes + +Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. + +```html +
+ +
+``` + +#### Slide Attributes + +Special syntax (in html comment) is available for adding attributes to the slide `
` elements generated by your Markdown. + +```html +
+ +
+``` + + +### Configuration + +At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. + +```javascript +Reveal.initialize({ + + // Display controls in the bottom right corner + controls: true, + + // Display a presentation progress bar + progress: true, + + // Display the page number of the current slide + slideNumber: false, + + // Push each slide change to the browser history + history: false, + + // Enable keyboard shortcuts for navigation + keyboard: true, + + // Enable the slide overview mode + overview: true, + + // Vertical centering of slides + center: true, + + // Enables touch navigation on devices with touch input + touch: true, + + // Loop the presentation + loop: false, + + // Change the presentation direction to be RTL + rtl: false, + + // Turns fragments on and off globally + fragments: true, + + // Flags if the presentation is running in an embedded mode, + // i.e. contained within a limited portion of the screen + embedded: false, + + // Flags if we should show a help overlay when the questionmark + // key is pressed + help: true, + + // Number of milliseconds between automatically proceeding to the + // next slide, disabled when set to 0, this value can be overwritten + // by using a data-autoslide attribute on your slides + autoSlide: 0, + + // Stop auto-sliding after user input + autoSlideStoppable: true, + + // Enable slide navigation via mouse wheel + mouseWheel: false, + + // Hides the address bar on mobile devices + hideAddressBar: true, + + // Opens links in an iframe preview overlay + previewLinks: false, + + // Transition style + transition: 'default', // none/fade/slide/convex/concave/zoom + + // Transition speed + transitionSpeed: 'default', // default/fast/slow + + // Transition style for full page slide backgrounds + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom + + // Number of slides away from the current that are visible + viewDistance: 3, + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" + + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' + +}); +``` + + +The configuration can be updated after initialization using the ```configure``` method: + +```javascript +// Turn autoSlide off +Reveal.configure({ autoSlide: 0 }); + +// Start auto-sliding every 5s +Reveal.configure({ autoSlide: 5000 }); +``` + + +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + +### Presentation Size + +All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. + +See below for a list of configuration options related to sizing, including default values: + +```javascript +Reveal.initialize({ + + ... + + // The "normal" size of the presentation, aspect ratio will be preserved + // when the presentation is scaled to fit different resolutions. Can be + // specified using percentage units. + width: 960, + height: 700, + + // Factor of the display size that should remain empty around the content + margin: 0.1, + + // Bounds for smallest/largest possible scale to apply to content + minScale: 0.2, + maxScale: 1.5 + +}); +``` + + +### Auto-sliding + +Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: + +```javascript +// Slide every five seconds +Reveal.configure({ + autoSlide: 5000 +}); +``` +When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. + +You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: + +```html +
+

After 2 seconds the first fragment will be shown.

+

After 10 seconds the next fragment will be shown.

+

Now, the fragment is displayed for 2 seconds before the next slide is shown.

+
+``` + +Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. + + +### Keyboard Bindings + +If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: + +```javascript +Reveal.configure({ + keyboard: { + 13: 'next', // go to the next slide when the ENTER key is pressed + 27: function() {}, // do something custom when ESC is pressed + 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) + } +}); +``` + +### Lazy Loading + +When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. + +To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. + +```html +
+ + + +
+``` + + +### API + +The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: + +```javascript +// Navigation +Reveal.slide( indexh, indexv, indexf ); +Reveal.left(); +Reveal.right(); +Reveal.up(); +Reveal.down(); +Reveal.prev(); +Reveal.next(); +Reveal.prevFragment(); +Reveal.nextFragment(); + +// Toggle presentation states, optionally pass true/false to force on/off +Reveal.toggleOverview(); +Reveal.togglePause(); +Reveal.toggleAutoSlide(); + +// Change a config value at runtime +Reveal.configure({ controls: true }); + +// Returns the present configuration options +Reveal.getConfig(); + +// Fetch the current scale of the presentation +Reveal.getScale(); + +// Retrieves the previous and current slide elements +Reveal.getPreviousSlide(); +Reveal.getCurrentSlide(); + +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); + +// State checks +Reveal.isFirstSlide(); +Reveal.isLastSlide(); +Reveal.isOverview(); +Reveal.isPaused(); +Reveal.isAutoSliding(); +``` + +### Slide Changed Event + +A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. + +Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'slidechanged', function( event ) { + // event.previousSlide, event.currentSlide, event.indexh, event.indexv +} ); +``` + +### Presentation State + +The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. + +```javascript +Reveal.slide( 1 ); +// we're on slide 1 + +var state = Reveal.getState(); + +Reveal.slide( 3 ); +// we're on slide 3 + +Reveal.setState( state ); +// we're back on slide 1 +``` + +### Slide States + +If you set ``data-state="somestate"`` on a slide ``
``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. + +Furthermore you can also listen to these changes in state via JavaScript: + +```javascript +Reveal.addEventListener( 'somestate', function() { + // TODO: Sprinkle magic +}, false ); +``` + +### Slide Backgrounds + +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. + +```html +
+

All CSS color formats are supported, like rgba() or hsl().

+
+
+

This slide will have a full-size background image.

+
+
+

This background image will be sized to 100px and repeated.

+
+
+

Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

+
+
+

Embeds a web page as a background. Note that the page won't be interactive.

+
+``` + +Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. + + +### Parallax Background + +If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). + +```javascript +Reveal.initialize({ + + // Parallax background image + parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" + + // Parallax background size + parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) + + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically + parallaxBackgroundHorizontal: 200, + parallaxBackgroundVertical: 50 + +}); +``` + +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). + + + +### Slide Transitions +The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: + +```html +
+

This slide will override the presentation transition and zoom!

+
+ +
+

Choose from three transition speeds: default, fast or slow!

+
+``` + +You can also use different in and out transitions for the same slide: + +```html +
+ The train goes on … +
+
+ and on … +
+
+ and stops. +
+
+ (Passengers entering and leaving) +
+
+ And it starts again. +
+``` + + +Note that this does not work with the page and cube transitions. + + +### Internal links + +It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
```): + +```html +Link +Link +``` + +You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. + +```html + + + + + + +``` + + +### Fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments + +The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: + +```html +
+

grow

+

shrink

+

fade-out

+

visible only once

+

blue only once

+

highlight-red

+

highlight-green

+

highlight-blue

+
+``` + +Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. + +```html +
+ + I'll fade in, then out + +
+``` + +The display order of fragments can be controlled using the ```data-fragment-index``` attribute. + +```html +
+

Appears last

+

Appears first

+

Appears second

+
+``` + +### Fragment events + +When a slide fragment is either shown or hidden reveal.js will dispatch an event. + +Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. + +```javascript +Reveal.addEventListener( 'fragmentshown', function( event ) { + // event.fragment = the fragment DOM element +} ); +Reveal.addEventListener( 'fragmenthidden', function( event ) { + // event.fragment = the fragment DOM element +} ); +``` + +### Code syntax highlighting + +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. + +```html +
+

+(def lazy-fib
+  (concat
+   [0 1]
+   ((fn rfib [a b]
+        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
+	
+
+``` + +### Slide number +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. + +```javascript +// Shows the slide number using default formatting +Reveal.configure({ slideNumber: true }); + +// Slide number formatting can be configured using these variables: +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); + +``` + + +### Overview mode + +Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, +as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: + +```javascript +Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); +Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); + +// Toggle the overview mode programmatically +Reveal.toggleOverview(); +``` + +### Fullscreen mode +Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. + + +### Embedded media +Embedded HTML5 `
+ +
+ +

 

 

 

+ + + + + + +
+

Week 47: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+ + +

Read »

+ + +
+ +

+ +

+ + +
+ + + + + + + +
+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week47/html/week47-reveal.html b/doc/pub/week47/html/week47-reveal.html new file mode 100644 index 000000000..c13cb8752 --- /dev/null +++ b/doc/pub/week47/html/week47-reveal.html @@ -0,0 +1,1619 @@ + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + + + + + + + + + + +
+ + + + +

Week 47: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

 
+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

 
+

Sep 16, 2020

+
+

+ +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+
+ + +
+

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. +

+ + +
+

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+
+ + +
+

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +

 
+$$ +b+w_1x_1+w_2x_2=0, +$$ +

 
+ +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +

 
+$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ +

 
+

+ + +
+

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +

 
+$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ +

 
+ +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +

 
+$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ +

 
+ +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +

 
+$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ +

 
+ +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +

 
+$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ +

 
+ +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +

 
+$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ +

 
+ +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. +

+ + +
+

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. +

+ + +
+

Getting into the details

+ +

+Let us define the function +

 
+$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ +

 
+ +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +

 
+$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ +

 
+

+ + +
+

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +

 
+$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ +

 
+ +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +

 
+$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ +

 
+ +and +

 
+$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ +

 
+

+ + +
+

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +

 
+$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ +

 
+ +and +

 
+$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ +

 
+ +where \( \eta \) is our by now well-known learning rate. +

+ + +
+

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+
+ + +
+

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. +

+ + +
+

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ +

 
+ +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +

 
+$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ +

 
+ +or just +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ +

 
+ +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ +

 
+ +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. +

+ + +
+

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +

 
+$$ +df=0. +$$ +

 
+ +A necessary and sufficient condition is +

 
+$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ +

 
+ +due to +

 
+$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ +

 
+ +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +

 
+$$ +\phi(x,y,z) = 0, +$$ +

 
+ + resulting in +

 
+$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ +

 
+ +Now we cannot set anymore +

 
+$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ +

 
+ +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. +

+ + +
+

Adding the Multiplier

+ +

+However, we can add to +

 
+$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ +

 
+ +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +

 
+$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ +

 
+ +Our multiplier is chosen so that +

 
+$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ +

 
+ +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +

 
+$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ +

 
+ +and +

 
+$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ +

 
+ +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +

 
+$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ +

 
+

+ + +
+

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +

 
+$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ +

 
+ +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

 
+$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ +

 
+ +and +

 
+$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ +

 
+ +Inserting these constraints into the equation for \( {\cal L} \) we obtain +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ +

 
+ +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +

 
+$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ +

 
+ + +

    +

  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +

  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+

+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). +

+ + +
+

The problem to solve

+ +

+We can rewrite +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ +

 
+ +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +

 
+$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ +

 
+ +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

+ + +
+

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +

 
+$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ +

 
+ +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ +

 
+ +resulting in +

 
+$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ +

 
+ +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +

 
+$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ +

 
+ +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +

 
+$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ +

 
+ +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. +

+ + +
+

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ +

 
+ +to +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ +

 
+ +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. +

+ + +
+

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +

 
+$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ +

 
+ +subject to +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ +

 
+ +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

 
+$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ +

 
+ +and +

 
+$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ +

 
+ +and +

 
+$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ +

 
+ +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ +

 
+ +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +

 
+$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ +

 
+ +

 
+$$ +\gamma_i\xi_i = 0, +$$ +

 
+ +and +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ +

 
+

+ + +
+

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+
+ + +
+

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +

 
+$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ +

 
+ +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ +

 
+ +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +

 
+$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ +

 
+ +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +

 
+$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ +

 
+ +For the above example, the kernel reads +

 
+$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ +

 
+ +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. +

+ + +
+

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +

 
+$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ +

 
+ +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +

 
+$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ +

 
+ +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +

 
+$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ +

 
+ +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). +

+ + +
+

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +

  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +

  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +

  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +

  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+

+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +

 
+$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ +

 
+ +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. +

+ + +
+

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+
+ + +
+

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +

 
+$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ +

 
+ +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. +

+ + +
+

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. +

+ + +
+

A simple example

+ +

+We remind ourselves about the general problem we want to solve +

 
+$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ +

 
+ +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +

 
+$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ +

 
+ +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +

 
+$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ +

 
+ +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +

 
+$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ +

 
+ +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +

 
+$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ +

 
+ +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +

 
+$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ +

 
+ +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=d)
+q = matrix(numpy.array([3,4]), tc=d)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=d)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=d)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[x] 
+sol[primal objective]
+
+
+ + +
+

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +

 
+$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ +

 
+ +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added +

+ + + +
+
+ + + + + + + + + + + + diff --git a/doc/pub/week47/html/week47-solarized.html b/doc/pub/week47/html/week47-solarized.html new file mode 100644 index 000000000..f75482c1e --- /dev/null +++ b/doc/pub/week47/html/week47-solarized.html @@ -0,0 +1,1295 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Week 47: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. + +

+









+ +

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+

+









+ +

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +$$ +b+w_1x_1+w_2x_2=0, +$$ + +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ + +

+









+ +

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ + +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ + +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ + +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ + +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ + +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. + +

+ + +

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. + +

+









+ +

Getting into the details

+ +

+Let us define the function +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ + +

+









+ +

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ + +and +$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ + +

+









+ +

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ + +and +$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ + +where \( \eta \) is our by now well-known learning rate. + +

+









+ +

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+

+









+ +

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. + +

+









+ +

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ + +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ + +or just +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ + +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ + +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. + +

+









+ +

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +$$ +df=0. +$$ + +A necessary and sufficient condition is +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +due to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ + +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +$$ +\phi(x,y,z) = 0, +$$ + + resulting in +$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ + +Now we cannot set anymore +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. + +

+









+ +

Adding the Multiplier

+ +

+However, we can add to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ + +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ + +Our multiplier is chosen so that +$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ + +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ + +and +$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ + +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ + +

+









+ +

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ + +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ + + +

    +
  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +
  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). + +

+









+ +

The problem to solve

+ +

+We can rewrite +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). + +

+









+ +

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +resulting in +$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ + +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ + +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. + +

+









+ +

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ + +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. + +

+









+ +

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ + +subject to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ + +and +$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +and +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ + +

+









+ +

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+

+









+ +

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ + +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +For the above example, the kernel reads +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ + +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. + +

+









+ +

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). + +

+









+ +

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +
  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +
  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +
  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +
  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. + +

+









+ +

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+

+









+ +

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. + +

+









+ +

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. + +

+









+ +

A simple example

+ +

+We remind ourselves about the general problem we want to solve +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ + +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ + +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ + +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ + +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=d)
+q = matrix(numpy.array([3,4]), tc=d)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=d)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=d)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[x] 
+sol[primal objective]
+
+

+









+ +

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added + +

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week47/html/week47.html b/doc/pub/week47/html/week47.html new file mode 100644 index 000000000..a08ae3053 --- /dev/null +++ b/doc/pub/week47/html/week47.html @@ -0,0 +1,1300 @@ + + + + + + + + +Week 47: Support Vector Machines + + + + + + + + + + + + + + + + + + + + + + + +

Week 47: Support Vector Machines

+ +

+ + +

+Morten Hjorth-Jensen [1, 2] +
+ +

+ + +

[1] Department of Physics, University of Oslo
+
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
+
+

+

Sep 16, 2020

+
+

+









+ +

Support Vector Machines, overarching aims

+ +

+A Support Vector Machine (SVM) is a very powerful and versatile +Machine Learning method, capable of performing linear or nonlinear +classification, regression, and even outlier detection. It is one of +the most popular models in Machine Learning, and anyone interested in +Machine Learning should have it in their toolbox. SVMs are +particularly well suited for classification of complex but small-sized or +medium-sized datasets. + +

+The case with two well-separated classes only can be understood in an +intuitive way in terms of lines in a two-dimensional space separating +the two classes (see figure below). + +

+The basic mathematics behind the SVM is however less familiar to most of us. +It relies on the definition of hyperplanes and the +definition of a margin which separates classes (in case of +classification problems) of variables. It is also used for regression +problems. + +

+With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. + +

+









+ +

Hyperplanes and all that

+ +

+The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. + +

+We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

+ + +

from sklearn import datasets
+from sklearn.svm import SVC, LinearSVC
+from sklearn.linear_model import SGDClassifier
+from sklearn.preprocessing import StandardScaler
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+iris = datasets.load_iris()
+X = iris["data"][:, (2, 3)]  # petal length, petal width
+y = iris["target"]
+
+setosa_or_versicolor = (y == 0) | (y == 1)
+X = X[setosa_or_versicolor]
+y = y[setosa_or_versicolor]
+
+
+
+C = 5
+alpha = 1 / (C * len(X))
+
+lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
+svm_clf = SVC(kernel="linear", C=C)
+sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
+                        max_iter=100000, random_state=42)
+
+scaler = StandardScaler()
+X_scaled = scaler.fit_transform(X)
+
+lin_clf.fit(X_scaled, y)
+svm_clf.fit(X_scaled, y)
+sgd_clf.fit(X_scaled, y)
+
+print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
+print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
+print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
+
+# Compute the slope and bias of each decision boundary
+w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
+b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
+w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
+b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
+w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
+b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
+
+# Transform the decision boundary lines back to the original scale
+line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
+line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
+line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
+
+# Plot all three decision boundaries
+plt.figure(figsize=(11, 4))
+plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
+plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
+plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
+plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
+plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
+plt.xlabel("Petal length", fontsize=14)
+plt.ylabel("Petal width", fontsize=14)
+plt.legend(loc="upper center", fontsize=14)
+plt.axis([0, 5.5, 0, 2])
+
+plt.show()
+
+

+









+ +

What is a hyperplane?

+ +

+The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. + +

+In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. + +

+In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +$$ +b+w_1x_1+w_2x_2=0, +$$ + +

+where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as + +$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ + +

+









+ +

A \( p \)-dimensional space of features

+ +

+We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ + +If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ + +If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ + +if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ + +for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. + +

+Equivalently, for the two classes of observations we have +$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ + +

+When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. + +

+ + +

The two-dimensional case

+ +

+Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. + +

+What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. + +

+Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. + +

+









+ +

Getting into the details

+ +

+Let us define the function +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. + +

+Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). + +

+The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ + +

+









+ +

First attempt at a minimization approach

+ +

+How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function + +$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

+We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ + +and +$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ + +

+









+ +

Solving the equations

+ +

+We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ + +and +$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ + +where \( \eta \) is our by now well-known learning rate. + +

+









+ +

Code Example

+ +

+The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

+ + +


+
+

+









+ +

Problems with the Simpler Approach

+ +

+There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. + +

+For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. + +

+









+ +

A better approach

+ +

+A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). + +

+Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition + +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ + +All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. + +

+We seek thus the largest value \( M \) defined by +$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ + +or just +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ + +If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ + +

+We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. + +

+









+ +

A quick Reminder on Lagrangian Multipliers

+ +

+Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +$$ +df=0. +$$ + +A necessary and sufficient condition is +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +due to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ + +In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. + +

+The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +$$ +\phi(x,y,z) = 0, +$$ + + resulting in +$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ + +Now we cannot set anymore +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. + +

+









+ +

Adding the Multiplier

+ +

+However, we can add to +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ + +a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ + +Our multiplier is chosen so that +$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ + +

+We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ + +and +$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ + +When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ + +

+









+ +

Setting up the Problem

+In order to solve the above problem, we define the following Lagrangian function to be minimized +$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ + +where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ + + +

    +
  1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
  2. +
  3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
  4. +
+ +When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). + +

+









+ +

The problem to solve

+ +

+We can rewrite +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). + +

+









+ +

The last steps

+ +

+Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +resulting in +$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ + +or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ + +With our hyperplane coefficients we can use our classifier to assign any observation by simply using +$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. + +

+









+ +

A soft classifier

+ +

+Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. + +

+Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. + +

+We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ + +with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. + +

+Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. + +

+









+ +

Soft optmization problem

+ +

+This has in turn the consequences that we change our optmization problem to finding the minimum of +$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ + +subject to +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +with the requirement \( \xi_i\geq 0 \). + +

+Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +and +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ + +and +$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ + +Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +and +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ + +

+









+ +

Kernels and non-linearity

+ +

+The cases we have studied till now, were all characterized by two classes +with a close to linear separability. The classifiers we have described +so far find linear boundaries in our input feature space. It is +possible to make our procedure more flexible by exploring the feature +space using other basis expansions such as higher-order polynomials, +wavelets, splines etc. + +

+If our feature space is not easy to separate, as shown in the figure +here, we can achieve a better separation by introducing more complex +basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to +obtain a separation between the classes which is almost linear. + +

+The change of basis, from \( x\rightarrow z=\phi(x) \) leads to the same type of equations to be solved, except that +we need to introduce for example a polynomial transformation to a two-dimensional training set. + +

+ + +

import numpy as np
+import os
+
+np.random.seed(42)
+
+# To plot pretty figures
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
+X2D = np.c_[X1D, X1D**2]
+y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
+plt.gca().get_yaxis().set_ticks([])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.axis([-4.5, 4.5, -0.2, 0.2])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
+plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
+plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
+plt.axis([-4.5, 4.5, -1, 17])
+plt.subplots_adjust(right=1)
+plt.show()
+
+

+









+ +

The equations

+ +

+Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with \( x_i \) and \( y_i \) as variables) +$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ + +

+With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +For the above example, the kernel reads +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2. +$$ + +

+We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). + +

+This leads to the so-called +kernel trick and the result leads to the same as if we went through +the trouble of performing the transformation +\( \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. + +

+









+ +

The problem to solve

+Using our definition of the kernel We can rewrite again the Lagrangian +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ + +subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +If we add the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{G} \) is discussed later. Here note that the inequalities \( 0\leq \lambda_i \leq C \) can be split up into +\( 0\leq \lambda_i \) and \( \lambda_i \leq C \). These two inequalities define then the matrix \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). + +

+









+ +

Different kernels and Mercer's theorem

+ +

+There are several popular kernels being used. These are + +

    +
  1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
  2. +
  3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
  4. +
  5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
  6. +
  7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
  8. +
+ +and many other ones. + +

+An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that + +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

+So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. + +

+Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. + +

+









+ +

The moons example

+

+ + +

from __future__ import division, print_function, unicode_literals
+
+import numpy as np
+np.random.seed(42)
+
+import matplotlib
+import matplotlib.pyplot as plt
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
+
+
+from sklearn.svm import SVC
+from sklearn import datasets
+
+
+
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import StandardScaler
+from sklearn.svm import LinearSVC
+
+
+from sklearn.datasets import make_moons
+X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
+
+def plot_dataset(X, y, axes):
+    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
+    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
+    plt.axis(axes)
+    plt.grid(True, which='both')
+    plt.xlabel(r"$x_1$", fontsize=20)
+    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
+
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.show()
+
+from sklearn.datasets import make_moons
+from sklearn.pipeline import Pipeline
+from sklearn.preprocessing import PolynomialFeatures
+
+polynomial_svm_clf = Pipeline([
+        ("poly_features", PolynomialFeatures(degree=3)),
+        ("scaler", StandardScaler()),
+        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
+    ])
+
+polynomial_svm_clf.fit(X, y)
+
+def plot_predictions(clf, axes):
+    x0s = np.linspace(axes[0], axes[1], 100)
+    x1s = np.linspace(axes[2], axes[3], 100)
+    x0, x1 = np.meshgrid(x0s, x1s)
+    X = np.c_[x0.ravel(), x1.ravel()]
+    y_pred = clf.predict(X).reshape(x0.shape)
+    y_decision = clf.decision_function(X).reshape(x0.shape)
+    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
+    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
+
+plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+
+plt.show()
+
+
+from sklearn.svm import SVC
+
+poly_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
+    ])
+poly_kernel_svm_clf.fit(X, y)
+
+poly100_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
+    ])
+poly100_kernel_svm_clf.fit(X, y)
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=3, r=1, C=5$", fontsize=18)
+
+plt.subplot(122)
+plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
+plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+plt.title(r"$d=10, r=100, C=5$", fontsize=18)
+
+plt.show()
+
+def gaussian_rbf(x, landmark, gamma):
+    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
+
+gamma = 0.3
+
+x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
+x2s = gaussian_rbf(x1s, -2, gamma)
+x3s = gaussian_rbf(x1s, 1, gamma)
+
+XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
+yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
+
+plt.figure(figsize=(11, 4))
+
+plt.subplot(121)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
+plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
+plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
+plt.plot(x1s, x2s, "g--")
+plt.plot(x1s, x3s, "b:")
+plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
+plt.xlabel(r"$x_1$", fontsize=20)
+plt.ylabel(r"Similarity", fontsize=14)
+plt.annotate(r'$\mathbf{x}$',
+             xy=(X1D[3, 0], 0),
+             xytext=(-0.5, 0.20),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
+plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
+plt.axis([-4.5, 4.5, -0.1, 1.1])
+
+plt.subplot(122)
+plt.grid(True, which='both')
+plt.axhline(y=0, color='k')
+plt.axvline(x=0, color='k')
+plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
+plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
+plt.xlabel(r"$x_2$", fontsize=20)
+plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
+plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
+             xy=(XK[3, 0], XK[3, 1]),
+             xytext=(0.65, 0.50),
+             ha="center",
+             arrowprops=dict(facecolor='black', shrink=0.1),
+             fontsize=18,
+            )
+plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
+plt.axis([-0.1, 1.1, -0.1, 1.1])
+    
+plt.subplots_adjust(right=1)
+
+plt.show()
+
+
+x1_example = X1D[3, 0]
+for landmark in (-2, 1):
+    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
+    print("Phi({}, {}) = {}".format(x1_example, landmark, k))
+
+rbf_kernel_svm_clf = Pipeline([
+        ("scaler", StandardScaler()),
+        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
+    ])
+rbf_kernel_svm_clf.fit(X, y)
+
+
+from sklearn.svm import SVC
+
+gamma1, gamma2 = 0.1, 5
+C1, C2 = 0.001, 1000
+hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
+
+svm_clfs = []
+for gamma, C in hyperparams:
+    rbf_kernel_svm_clf = Pipeline([
+            ("scaler", StandardScaler()),
+            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
+        ])
+    rbf_kernel_svm_clf.fit(X, y)
+    svm_clfs.append(rbf_kernel_svm_clf)
+
+plt.figure(figsize=(11, 7))
+
+for i, svm_clf in enumerate(svm_clfs):
+    plt.subplot(221 + i)
+    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
+    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
+    gamma, C = hyperparams[i]
+    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
+
+plt.show()
+
+

+









+ +

Mathematical optimization of convex functions

+ +

+A mathematical (quadratic) optimization problem, or just optimization problem, has the form +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +subject to some constraints for say a selected set \( i=1,2,\dots, n \). +In our case we are optimizing with respect to the Lagrangian multipliers \( \lambda_i \), and the +vector \( \boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n] \) is the optimization variable we are dealing with. + +

+In our case we are particularly interested in a class of optimization problems called convex optmization problems. +In our discussion on gradient descent methods we discussed at length the definition of a convex function. + +

+Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics. + +

+









+ +

How do we solve these problems?

+ +

+If we use Python as programming language and wish to venture beyond +scikit-learn, tensorflow and similar software which makes our +lives so much easier, we need to dive into the wonderful world of +quadratic programming. We can, if we wish, solve the minimization +problem using say standard gradient methods or conjugate gradient +methods. However, these methods tend to exhibit a rather slow +converge. So, welcome to the promised land of quadratic programming. + +

+The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as + +

+ + +

import numpy
+import cvxopt
+
+

+This will make our life much easier. You don't need t write your own optimizer. + +

+









+ +

A simple example

+ +

+We remind ourselves about the general problem we want to solve +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ + +

+Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{subject to} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +$$ + +The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +$$ +\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +$$ + +Similarly, we can now set up the inequalities (we need to change \( \geq \) to \( \leq \) by multiplying with \( -1 \) on bot sides) as the following matrix-vector equation +$$ +\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ + +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +

+Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

+ + +

# Import the necessary packages
+import numpy
+from cvxopt import matrix
+from cvxopt import solvers
+P = matrix(numpy.diag([1,0]), tc=’d’)
+q = matrix(numpy.array([3,4]), tc=’d’)
+G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)
+h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)
+# Construct the QP, invoke solver
+sol = solvers.qp(P,q,G,h)
+# Extract optimal value and solution
+sol[’x’] 
+sol[’primal objective’]
+
+

+









+ +

Back to the more realistic cases

+ +

+We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the slack parameter \( C \) we have +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ + +subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). + +

+code will be added + +

+ + + + +

+ © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
+ + + + + + diff --git a/doc/pub/week47/ipynb/ipynb-week47-src.tar.gz b/doc/pub/week47/ipynb/ipynb-week47-src.tar.gz new file mode 100644 index 000000000..8b2c4fca1 Binary files /dev/null and b/doc/pub/week47/ipynb/ipynb-week47-src.tar.gz differ diff --git a/doc/pub/week47/ipynb/week47.ipynb b/doc/pub/week47/ipynb/week47.ipynb new file mode 100644 index 000000000..9ae4852e3 --- /dev/null +++ b/doc/pub/week47/ipynb/week47.ipynb @@ -0,0 +1,1894 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "# Week 47: Support Vector Machines\n", + "\n", + " \n", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", + "\n", + "Date: **Sep 16, 2020**\n", + "\n", + "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "\n", + "\n", + "\n", + "## Support Vector Machines, overarching aims\n", + "\n", + "A Support Vector Machine (SVM) is a very powerful and versatile\n", + "Machine Learning method, capable of performing linear or nonlinear\n", + "classification, regression, and even outlier detection. It is one of\n", + "the most popular models in Machine Learning, and anyone interested in\n", + "Machine Learning should have it in their toolbox. SVMs are\n", + "particularly well suited for classification of complex but small-sized or\n", + "medium-sized datasets. \n", + "\n", + "The case with two well-separated classes only can be understood in an\n", + "intuitive way in terms of lines in a two-dimensional space separating\n", + "the two classes (see figure below).\n", + "\n", + "The basic mathematics behind the SVM is however less familiar to most of us. \n", + "It relies on the definition of hyperplanes and the\n", + "definition of a **margin** which separates classes (in case of\n", + "classification problems) of variables. It is also used for regression\n", + "problems.\n", + "\n", + "With SVMs we distinguish between hard margin and soft margins. The\n", + "latter introduces a so-called softening parameter to be discussed\n", + "below. We distinguish also between linear and non-linear\n", + "approaches. The latter are the most frequent ones since it is rather\n", + "unlikely that we can separate classes easily by say straight lines.\n", + "\n", + "## Hyperplanes and all that\n", + "\n", + "The theory behind support vector machines (SVM hereafter) is based on\n", + "the mathematical description of so-called hyperplanes. Let us start\n", + "with a two-dimensional case. This will also allow us to introduce our\n", + "first SVM examples. These will be tailored to the case of two specific\n", + "classes, as displayed in the figure here based on the usage of the petal data.\n", + "\n", + "We assume here that our data set can be well separated into two\n", + "domains, where a straight line does the job in the separating the two\n", + "classes. Here the two classes are represented by either squares or\n", + "circles." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "from sklearn import datasets\n", + "from sklearn.svm import SVC, LinearSVC\n", + "from sklearn.linear_model import SGDClassifier\n", + "from sklearn.preprocessing import StandardScaler\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "iris = datasets.load_iris()\n", + "X = iris[\"data\"][:, (2, 3)] # petal length, petal width\n", + "y = iris[\"target\"]\n", + "\n", + "setosa_or_versicolor = (y == 0) | (y == 1)\n", + "X = X[setosa_or_versicolor]\n", + "y = y[setosa_or_versicolor]\n", + "\n", + "\n", + "\n", + "C = 5\n", + "alpha = 1 / (C * len(X))\n", + "\n", + "lin_clf = LinearSVC(loss=\"hinge\", C=C, random_state=42)\n", + "svm_clf = SVC(kernel=\"linear\", C=C)\n", + "sgd_clf = SGDClassifier(loss=\"hinge\", learning_rate=\"constant\", eta0=0.001, alpha=alpha,\n", + " max_iter=100000, random_state=42)\n", + "\n", + "scaler = StandardScaler()\n", + "X_scaled = scaler.fit_transform(X)\n", + "\n", + "lin_clf.fit(X_scaled, y)\n", + "svm_clf.fit(X_scaled, y)\n", + "sgd_clf.fit(X_scaled, y)\n", + "\n", + "print(\"LinearSVC: \", lin_clf.intercept_, lin_clf.coef_)\n", + "print(\"SVC: \", svm_clf.intercept_, svm_clf.coef_)\n", + "print(\"SGDClassifier(alpha={:.5f}):\".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)\n", + "\n", + "# Compute the slope and bias of each decision boundary\n", + "w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]\n", + "b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]\n", + "w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]\n", + "b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]\n", + "w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]\n", + "b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]\n", + "\n", + "# Transform the decision boundary lines back to the original scale\n", + "line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])\n", + "line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])\n", + "line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])\n", + "\n", + "# Plot all three decision boundaries\n", + "plt.figure(figsize=(11, 4))\n", + "plt.plot(line1[:, 0], line1[:, 1], \"k:\", label=\"LinearSVC\")\n", + "plt.plot(line2[:, 0], line2[:, 1], \"b--\", linewidth=2, label=\"SVC\")\n", + "plt.plot(line3[:, 0], line3[:, 1], \"r-\", label=\"SGDClassifier\")\n", + "plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\") # label=\"Iris-Versicolor\"\n", + "plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\") # label=\"Iris-Setosa\"\n", + "plt.xlabel(\"Petal length\", fontsize=14)\n", + "plt.ylabel(\"Petal width\", fontsize=14)\n", + "plt.legend(loc=\"upper center\", fontsize=14)\n", + "plt.axis([0, 5.5, 0, 2])\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is a hyperplane?\n", + "\n", + "The aim of the SVM algorithm is to find a hyperplane in a\n", + "$p$-dimensional space, where $p$ is the number of features that\n", + "distinctly classifies the data points.\n", + "\n", + "In a $p$-dimensional space, a hyperplane is what we call an affine subspace of dimension of $p-1$.\n", + "As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is \n", + "a two-dimensional subspace, or stated simply, a plane. \n", + "\n", + "In two dimensions, with the variables $x_1$ and $x_2$, the hyperplane is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+w_1x_1+w_2x_2=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $b$ is the intercept and $w_1$ and $w_2$ define the elements of a vector orthogonal to the line \n", + "$b+w_1x_1+w_2x_2=0$. \n", + "In two dimensions we define the vectors $\\boldsymbol{x} =[x1,x2]$ and $\\boldsymbol{w}=[w1,w2]$. \n", + "We can then rewrite the above equation as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{x}^T\\boldsymbol{w}+b=0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A $p$-dimensional space of features\n", + "\n", + "We limit ourselves to two classes of outputs $y_i$ and assign these classes the values $y_i = \\pm 1$. \n", + "In a $p$-dimensional space of say $p$ features we have a hyperplane defines as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+wx_1+w_2x_2+\\dots +w_px_p=0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we define a \n", + "matrix $\\boldsymbol{X}=\\left[\\boldsymbol{x}_1,\\boldsymbol{x}_2,\\dots, \\boldsymbol{x}_p\\right]$\n", + "of dimension $n\\times p$, where $n$ represents the observations for each feature and each vector $x_i$ is a column vector of the matrix $\\boldsymbol{X}$," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{x}_i = \\begin{bmatrix} x_{i1} \\\\ x_{i2} \\\\ \\dots \\\\ \\dots \\\\ x_{ip} \\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If the above condition is not met for a given vector $\\boldsymbol{x}_i$ we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} >0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "if our output $y_i=1$.\n", + "In this case we say that $\\boldsymbol{x}_i$ lies on one of the sides of the hyperplane and if" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} < 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "for the class of observations $y_i=-1$, \n", + "then $\\boldsymbol{x}_i$ lies on the other side. \n", + "\n", + "Equivalently, for the two classes of observations we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i\\left(b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip}\\right) > 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.\n", + "\n", + "\n", + "## The two-dimensional case\n", + "\n", + "Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional\n", + "plane. To separate the two classes of data points, there are many\n", + "possible lines (hyperplanes if you prefer a more strict naming) \n", + "that could be chosen. Our objective is to find a\n", + "plane that has the maximum margin, i.e the maximum distance between\n", + "data points of both classes. Maximizing the margin distance provides\n", + "some reinforcement so that future data points can be classified with\n", + "more confidence.\n", + "\n", + "What a linear classifier attempts to accomplish is to split the\n", + "feature space into two half spaces by placing a hyperplane between the\n", + "data points. This hyperplane will be our decision boundary. All\n", + "points on one side of the plane will belong to class one and all points\n", + "on the other side of the plane will belong to the second class two.\n", + "\n", + "Unfortunately there are many ways in which we can place a hyperplane\n", + "to divide the data. Below is an example of two candidate hyperplanes\n", + "for our data sample.\n", + "\n", + "## Getting into the details\n", + "\n", + "Let us define the function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "f(x) = \\boldsymbol{w}^T\\boldsymbol{x}+b = 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "as the function that determines the line $L$ that separates two classes (our two features), see the figure here. \n", + "\n", + "\n", + "Any point defined by $\\boldsymbol{x}_i$ and $\\boldsymbol{x}_2$ on the line $L$ will satisfy $\\boldsymbol{w}^T(\\boldsymbol{x}_1-\\boldsymbol{x}_2)=0$. \n", + "\n", + "The signed distance $\\delta$ from any point defined by a vector $\\boldsymbol{x}$ and a point $\\boldsymbol{x}_0$ on the line $L$ is then" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\delta = \\frac{1}{\\vert\\vert \\boldsymbol{w}\\vert\\vert}(\\boldsymbol{w}^T\\boldsymbol{x}+b).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## First attempt at a minimization approach\n", + "\n", + "How do we find the parameter $b$ and the vector $\\boldsymbol{w}$? What we could\n", + "do is to define a cost function which now contains the set of all\n", + "misclassified points $M$ and attempt to minimize this function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{w},b) = -\\sum_{i\\in M} y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could now for example define all values $y_i =1$ as misclassified in case we have $\\boldsymbol{w}^T\\boldsymbol{x}_i+b < 0$ and the opposite if we have $y_i=-1$. Taking the derivatives gives us" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial C}{\\partial b} = -\\sum_{i\\in M} y_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial C}{\\partial \\boldsymbol{w}} = -\\sum_{i\\in M} y_ix_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Solving the equations\n", + "\n", + "We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b \\leftarrow b +\\eta \\frac{\\partial C}{\\partial b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{w} \\leftarrow \\boldsymbol{w} +\\eta \\frac{\\partial C}{\\partial \\boldsymbol{w}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\eta$ is our by now well-known learning rate. \n", + "\n", + "\n", + "## Code Example\n", + "\n", + "The equations we discussed above can be coded rather easily (the\n", + "framework is similar to what we developed for logistic\n", + "regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Problems with the Simpler Approach\n", + "\n", + "\n", + "There are however problems with this approach, although it looks\n", + "pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes.\n", + "\n", + "\n", + "For small\n", + "gaps between the entries, we may also end up needing many iterations\n", + "before the solutions converge and if the data cannot be separated\n", + "properly into two distinct classes, we may not experience a converge\n", + "at all.\n", + "\n", + "## A better approach\n", + "\n", + "A better approach is rather to try to define a large margin between\n", + "the two classes (if they are well separated from the beginning).\n", + "\n", + "Thus, we wish to find a margin $M$ with $\\boldsymbol{w}$ normalized to\n", + "$\\vert\\vert \\boldsymbol{w}\\vert\\vert =1$ subject to the condition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, p.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "All points are thus at a signed distance from the decision boundary defined by the line $L$. The parameters $b$ and $w_1$ and $w_2$ define this line. \n", + "\n", + "We seek thus the largest value $M$ defined by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{\\vert \\vert \\boldsymbol{w}\\vert\\vert}y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, n,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or just" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M\\vert \\vert \\boldsymbol{w}\\vert\\vert \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we scale the equation so that $\\vert \\vert \\boldsymbol{w}\\vert\\vert = 1/M$, we have to find the minimum of \n", + "$\\boldsymbol{w}^T\\boldsymbol{w}=\\vert \\vert \\boldsymbol{w}\\vert\\vert$ (the norm) subject to the condition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq 1 \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We have thus defined our margin as the invers of the norm of\n", + "$\\boldsymbol{w}$. We want to minimize the norm in order to have a as large as\n", + "possible margin $M$. Before we proceed, we need to remind ourselves\n", + "about Lagrangian multipliers.\n", + "\n", + "## A quick Reminder on Lagrangian Multipliers\n", + "\n", + "Consider a function of three independent variables $f(x,y,z)$ . For the function $f$ to be an\n", + "extreme we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df=0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A necessary and sufficient condition is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "due to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In many problems the variables $x,y,z$ are often subject to constraints (such as those above for the margin)\n", + "so that they are no longer all independent. It is possible at least in principle to use each \n", + "constraint to eliminate one variable\n", + "and to proceed with a new and smaller set of independent varables.\n", + "\n", + "The use of so-called Lagrangian multipliers is an alternative technique when the elimination\n", + "of variables is incovenient or undesirable. Assume that we have an equation of constraint on \n", + "the variables $x,y,z$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\phi(x,y,z) = 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "d\\phi = \\frac{\\partial \\phi}{\\partial x}dx+\\frac{\\partial \\phi}{\\partial y}dy+\\frac{\\partial \\phi}{\\partial z}dz =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we cannot set anymore" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "if $df=0$ is wanted\n", + "because there are now only two independent variables! Assume $x$ and $y$ are the independent \n", + "variables.\n", + "Then $dz$ is no longer arbitrary.\n", + "\n", + "## Adding the Multiplier\n", + "\n", + "However, we can add to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "a multiplum of $d\\phi$, viz. $\\lambda d\\phi$, resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "df+\\lambda d\\phi = (\\frac{\\partial f}{\\partial z}+\\lambda\n", + "\\frac{\\partial \\phi}{\\partial x})dx+(\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y})dy+\n", + "(\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z})dz =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Our multiplier is chosen so that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z} =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We need to remember that we took $dx$ and $dy$ to be arbitrary and thus we must have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x}+\\lambda\\frac{\\partial \\phi}{\\partial x} =0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y} =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When all these equations are satisfied, $df=0$. We have four unknowns, $x,y,z$ and\n", + "$\\lambda$. Actually we want only $x,y,z$, $\\lambda$ needs not to be determined, \n", + "it is therefore often called\n", + "Lagrange's undetermined multiplier.\n", + "If we have a set of constraints $\\phi_k$ we have the equations" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial f}{\\partial x_i}+\\sum_k\\lambda_k\\frac{\\partial \\phi_k}{\\partial x_i} =0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Setting up the Problem\n", + "In order to solve the above problem, we define the following Lagrangian function to be minimized" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}(\\lambda,b,\\boldsymbol{w})=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-1\\right],\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\lambda_i$ is a so-called Lagrange multiplier subject to the condition $\\lambda_i \\geq 0$.\n", + "\n", + "Taking the derivatives with respect to $b$ and $\\boldsymbol{w}$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inserting these constraints into the equation for ${\\cal L}$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to the constraints $\\lambda_i\\geq 0$ and $\\sum_i\\lambda_iy_i=0$. \n", + "We must in addition satisfy the [Karush-Kuhn-Tucker](https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions) (KKT) condition" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -1\\right] \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. If $\\lambda_i > 0$, then $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1$ and we say that $x_i$ is on the boundary.\n", + "\n", + "2. If $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)> 1$, we say $x_i$ is not on the boundary and we set $\\lambda_i=0$. \n", + "\n", + "When $\\lambda_i > 0$, the vectors $\\boldsymbol{x}_i$ are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin $M$. \n", + "\n", + "## The problem to solve\n", + "\n", + "We can rewrite" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and its constraints in terms of a matrix-vector problem where we minimize w.r.t. $\\lambda$ the following problem" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1\\boldsymbol{x}_1^T\\boldsymbol{x}_1 & y_1y_2\\boldsymbol{x}_1^T\\boldsymbol{x}_2 & \\dots & \\dots & y_1y_n\\boldsymbol{x}_1^T\\boldsymbol{x}_n \\\\\n", + "y_2y_1\\boldsymbol{x}_2^T\\boldsymbol{x}_1 & y_2y_2\\boldsymbol{x}_2^T\\boldsymbol{x}_2 & \\dots & \\dots & y_1y_n\\boldsymbol{x}_2^T\\boldsymbol{x}_n \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "y_ny_1\\boldsymbol{x}_n^T\\boldsymbol{x}_1 & y_ny_2\\boldsymbol{x}_n^T\\boldsymbol{x}_2 & \\dots & \\dots & y_ny_n\\boldsymbol{x}_n^T\\boldsymbol{x}_n \\\\\n", + "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{1}\\boldsymbol{\\lambda},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", + "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", + "\n", + "\n", + "## The last steps\n", + "\n", + "Solving the above problem, yields the values of $\\lambda_i$.\n", + "To find the coefficients of your hyperplane we need simply to compute" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{w}=\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With our vector $\\boldsymbol{w}$ we can in turn find the value of the intercept $b$ (here in two dimensions) via" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b = \\frac{1}{y_i}-\\boldsymbol{w}^T\\boldsymbol{x}_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or if we write it out in terms of the support vectors only, with $N_s$ being their number, we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "b = \\frac{1}{N_s}\\sum_{j\\in N_s}\\left(y_j-\\sum_{i=1}^n\\lambda_iy_i\\boldsymbol{x}_i^T\\boldsymbol{x}_j\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With our hyperplane coefficients we can use our classifier to assign any observation by simply using" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i = \\mathrm{sign}(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Below we discuss how to find the optimal values of $\\lambda_i$. Before we proceed however, we discuss now the so-called soft classifier. \n", + "\n", + "## A soft classifier\n", + "\n", + "Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.\n", + "\n", + "Suppose now that classes overlap in feature space, as shown in the\n", + "figure here. One way to deal with this problem before we define the\n", + "so-called **kernel approach**, is to allow a kind of slack in the sense\n", + "that we allow some points to be on the wrong side of the margin.\n", + "\n", + "We introduce thus the so-called **slack** variables $\\boldsymbol{\\xi} =[\\xi_1,x_2,\\dots,x_n]$ and \n", + "modify our previous equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with the requirement $\\xi_i\\geq 0$. The total violation is now $\\sum_i\\xi$. \n", + "The value $\\xi_i$ in the constraint the last constraint corresponds to the amount by which the prediction\n", + "$y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1$ is on the wrong side of its margin. Hence by bounding the sum $\\sum_i \\xi_i$,\n", + "we bound the total amount by which predictions fall on the wrong side of their margins.\n", + "\n", + "Misclassifications occur when $\\xi_i > 1$. Thus bounding the total sum by some value $C$ bounds in turn the total number of\n", + "misclassifications.\n", + "\n", + "## Soft optmization problem\n", + "\n", + "\n", + "This has in turn the consequences that we change our optmization problem to finding the minimum of" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-(1-\\xi_)\\right]+C\\sum_{i=1}^n\\xi_i-\\sum_{i=1}^n\\gamma_i\\xi_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i \\hspace{0.1cm}\\forall i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with the requirement $\\xi_i\\geq 0$.\n", + "\n", + "Taking the derivatives with respect to $b$ and $\\boldsymbol{w}$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial {\\cal L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\lambda_i = C-\\gamma_i \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Inserting these constraints into the equation for ${\\cal L}$ we obtain the same equation as before" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "but now subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ and $0\\leq\\lambda_i \\leq C$. \n", + "We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "5\n", + "0\n", + " \n", + "<\n", + "<\n", + "<\n", + "!\n", + "!\n", + "M\n", + "A\n", + "T\n", + "H\n", + "_\n", + "B\n", + "L\n", + "O\n", + "C\n", + "K" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\gamma_i\\xi_i = 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -(1-\\xi_) \\geq 0 \\hspace{0.1cm}\\forall i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Kernels and non-linearity\n", + "\n", + "The cases we have studied till now, were all characterized by two classes\n", + "with a close to linear separability. The classifiers we have described\n", + "so far find linear boundaries in our input feature space. It is\n", + "possible to make our procedure more flexible by exploring the feature\n", + "space using other basis expansions such as higher-order polynomials,\n", + "wavelets, splines etc.\n", + "\n", + "If our feature space is not easy to separate, as shown in the figure\n", + "here, we can achieve a better separation by introducing more complex\n", + "basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to \n", + "obtain a separation between the classes which is almost linear. \n", + "\n", + "The change of basis, from $x\\rightarrow z=\\phi(x)$ leads to the same type of equations to be solved, except that\n", + "we need to introduce for example a polynomial transformation to a two-dimensional training set." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import os\n", + "\n", + "np.random.seed(42)\n", + "\n", + "# To plot pretty figures\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "from sklearn import datasets\n", + "\n", + "\n", + "\n", + "X1D = np.linspace(-4, 4, 9).reshape(-1, 1)\n", + "X2D = np.c_[X1D, X1D**2]\n", + "y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.plot(X1D[:, 0][y==0], np.zeros(4), \"bs\")\n", + "plt.plot(X1D[:, 0][y==1], np.zeros(5), \"g^\")\n", + "plt.gca().get_yaxis().set_ticks([])\n", + "plt.xlabel(r\"$x_1$\", fontsize=20)\n", + "plt.axis([-4.5, 4.5, -0.2, 0.2])\n", + "\n", + "plt.subplot(122)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.axvline(x=0, color='k')\n", + "plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], \"bs\")\n", + "plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], \"g^\")\n", + "plt.xlabel(r\"$x_1$\", fontsize=20)\n", + "plt.ylabel(r\"$x_2$\", fontsize=20, rotation=0)\n", + "plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])\n", + "plt.plot([-4.5, 4.5], [6.5, 6.5], \"r--\", linewidth=3)\n", + "plt.axis([-4.5, 4.5, -1, 17])\n", + "plt.subplots_adjust(right=1)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The equations\n", + "\n", + "Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with $x_i$ and $y_i$ as variables)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "z = \\phi(x_i) =\\left(x_i^2, y_i^2, \\sqrt{2}x_iy_i\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{z}_i^T\\boldsymbol{z}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$, and for the support vectors" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i(\\boldsymbol{w}^T\\boldsymbol{z}_i+b)= 1 \\hspace{0.1cm}\\forall i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "from which we also find $b$.\n", + "To compute $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we define the kernel $K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\boldsymbol{z}_i^T\\boldsymbol{z}_j= \\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the above example, the kernel reads" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=[x_i^2, y_i^2, \\sqrt{2}x_iy_i]^T\\begin{bmatrix} x_j^2 \\\\ y_j^2 \\\\ \\sqrt{2}x_jy_j \\end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We note that this is nothing but the dot product of the two original\n", + "vectors $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$. Instead of thus computing the\n", + "product in the Lagrangian of $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we simply compute\n", + "the dot product $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$.\n", + "\n", + "\n", + "This leads to the so-called\n", + "kernel trick and the result leads to the same as if we went through\n", + "the trouble of performing the transformation\n", + "$\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j)$ during the SVM calculations.\n", + "\n", + "\n", + "## The problem to solve\n", + "Using our definition of the kernel We can rewrite again the Lagrangian" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{z}_j,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ in terms of a convex optimization problem" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n", + "y_2y_1K(\\boldsymbol{x}_2,\\boldsymbol{x}_1) & y_2y_2(\\boldsymbol{x}_2,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_2,\\boldsymbol{x}_n) \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "y_ny_1K(\\boldsymbol{x}_n,\\boldsymbol{x}_1) & y_ny_2K(\\boldsymbol{x}_n\\boldsymbol{x}_2) & \\dots & \\dots & y_ny_nK(\\boldsymbol{x}_n,\\boldsymbol{x}_n) \\\\\n", + "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{1}\\boldsymbol{\\lambda},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", + "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", + "If we add the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$.\n", + "\n", + "We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{\\lambda}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{\\lambda}^T\\boldsymbol{P}\\boldsymbol{\\lambda}+\\boldsymbol{q}^T\\boldsymbol{\\lambda},\\\\ \\nonumber\n", + " &\\mathrm{subject\\hspace{0.1cm}to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h} \\hspace{0.2cm} \\wedge \\boldsymbol{A}\\boldsymbol{\\lambda}=f.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Below we discuss how to solve these equations. Here we note that the matrix $\\boldsymbol{P}$ has matrix elements $p_{ij}=y_iy_jK(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$.\n", + "Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$ leads to $f=0$ and $\\boldsymbol{A}=\\boldsymbol{y}$. How to set up the matrix $\\boldsymbol{G}$ is discussed later. Here note that the inequalities $0\\leq \\lambda_i \\leq C$ can be split up into\n", + "$0\\leq \\lambda_i$ and $\\lambda_i \\leq C$. These two inequalities define then the matrix $\\boldsymbol{G}$ and the vector $\\boldsymbol{h}$.\n", + "\n", + "\n", + "## Different kernels and Mercer's theorem\n", + "\n", + "There are several popular kernels being used. These are\n", + "1. Linear: $K(\\boldsymbol{x},\\boldsymbol{y})=\\boldsymbol{x}^T\\boldsymbol{y}$,\n", + "\n", + "2. Polynomial: $K(\\boldsymbol{x},\\boldsymbol{y})=(\\boldsymbol{x}^T\\boldsymbol{y}+\\gamma)^d$,\n", + "\n", + "3. Gaussian Radial Basis Function: $K(\\boldsymbol{x},\\boldsymbol{y})=\\exp{\\left(-\\gamma\\vert\\vert\\boldsymbol{x}-\\boldsymbol{y}\\vert\\vert^2\\right)}$,\n", + "\n", + "4. Tanh: $K(\\boldsymbol{x},\\boldsymbol{y})=\\tanh{(\\boldsymbol{x}^T\\boldsymbol{y}+\\gamma)}$,\n", + "\n", + "and many other ones.\n", + "\n", + "An important theorem for us is [Mercer's\n", + "theorem](https://en.wikipedia.org/wiki/Mercer%27s_theorem). The\n", + "theorem states that if a kernel function $K$ is symmetric, continuous\n", + "and leads to a positive semi-definite matrix $\\boldsymbol{P}$ then there\n", + "exists a function $\\phi$ that maps $\\boldsymbol{x}_i$ and $\\boldsymbol{x}_j$ into\n", + "another space (possibly with much higher dimensions) such that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So you can use $K$ as a kernel since you know $\\phi$ exists, even if\n", + "you don’t know what $\\phi$ is. \n", + "\n", + "Note that some frequently used kernels (such as the Sigmoid kernel)\n", + "don’t respect all of Mercer’s conditions, yet they generally work well\n", + "in practice.\n", + "\n", + "\n", + "## The moons example" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from __future__ import division, print_function, unicode_literals\n", + "\n", + "import numpy as np\n", + "np.random.seed(42)\n", + "\n", + "import matplotlib\n", + "import matplotlib.pyplot as plt\n", + "plt.rcParams['axes.labelsize'] = 14\n", + "plt.rcParams['xtick.labelsize'] = 12\n", + "plt.rcParams['ytick.labelsize'] = 12\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "from sklearn import datasets\n", + "\n", + "\n", + "\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.preprocessing import StandardScaler\n", + "from sklearn.svm import LinearSVC\n", + "\n", + "\n", + "from sklearn.datasets import make_moons\n", + "X, y = make_moons(n_samples=100, noise=0.15, random_state=42)\n", + "\n", + "def plot_dataset(X, y, axes):\n", + " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"bs\")\n", + " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"g^\")\n", + " plt.axis(axes)\n", + " plt.grid(True, which='both')\n", + " plt.xlabel(r\"$x_1$\", fontsize=20)\n", + " plt.ylabel(r\"$x_2$\", fontsize=20, rotation=0)\n", + "\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "plt.show()\n", + "\n", + "from sklearn.datasets import make_moons\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "\n", + "polynomial_svm_clf = Pipeline([\n", + " (\"poly_features\", PolynomialFeatures(degree=3)),\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", LinearSVC(C=10, loss=\"hinge\", random_state=42))\n", + " ])\n", + "\n", + "polynomial_svm_clf.fit(X, y)\n", + "\n", + "def plot_predictions(clf, axes):\n", + " x0s = np.linspace(axes[0], axes[1], 100)\n", + " x1s = np.linspace(axes[2], axes[3], 100)\n", + " x0, x1 = np.meshgrid(x0s, x1s)\n", + " X = np.c_[x0.ravel(), x1.ravel()]\n", + " y_pred = clf.predict(X).reshape(x0.shape)\n", + " y_decision = clf.decision_function(X).reshape(x0.shape)\n", + " plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)\n", + " plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)\n", + "\n", + "plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "\n", + "plt.show()\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "\n", + "poly_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"poly\", degree=3, coef0=1, C=5))\n", + " ])\n", + "poly_kernel_svm_clf.fit(X, y)\n", + "\n", + "poly100_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"poly\", degree=10, coef0=100, C=5))\n", + " ])\n", + "poly100_kernel_svm_clf.fit(X, y)\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "plt.title(r\"$d=3, r=1, C=5$\", fontsize=18)\n", + "\n", + "plt.subplot(122)\n", + "plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])\n", + "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + "plt.title(r\"$d=10, r=100, C=5$\", fontsize=18)\n", + "\n", + "plt.show()\n", + "\n", + "def gaussian_rbf(x, landmark, gamma):\n", + " return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)\n", + "\n", + "gamma = 0.3\n", + "\n", + "x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)\n", + "x2s = gaussian_rbf(x1s, -2, gamma)\n", + "x3s = gaussian_rbf(x1s, 1, gamma)\n", + "\n", + "XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]\n", + "yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])\n", + "\n", + "plt.figure(figsize=(11, 4))\n", + "\n", + "plt.subplot(121)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c=\"red\")\n", + "plt.plot(X1D[:, 0][yk==0], np.zeros(4), \"bs\")\n", + "plt.plot(X1D[:, 0][yk==1], np.zeros(5), \"g^\")\n", + "plt.plot(x1s, x2s, \"g--\")\n", + "plt.plot(x1s, x3s, \"b:\")\n", + "plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])\n", + "plt.xlabel(r\"$x_1$\", fontsize=20)\n", + "plt.ylabel(r\"Similarity\", fontsize=14)\n", + "plt.annotate(r'$\\mathbf{x}$',\n", + " xy=(X1D[3, 0], 0),\n", + " xytext=(-0.5, 0.20),\n", + " ha=\"center\",\n", + " arrowprops=dict(facecolor='black', shrink=0.1),\n", + " fontsize=18,\n", + " )\n", + "plt.text(-2, 0.9, \"$x_2$\", ha=\"center\", fontsize=20)\n", + "plt.text(1, 0.9, \"$x_3$\", ha=\"center\", fontsize=20)\n", + "plt.axis([-4.5, 4.5, -0.1, 1.1])\n", + "\n", + "plt.subplot(122)\n", + "plt.grid(True, which='both')\n", + "plt.axhline(y=0, color='k')\n", + "plt.axvline(x=0, color='k')\n", + "plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], \"bs\")\n", + "plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], \"g^\")\n", + "plt.xlabel(r\"$x_2$\", fontsize=20)\n", + "plt.ylabel(r\"$x_3$ \", fontsize=20, rotation=0)\n", + "plt.annotate(r'$\\phi\\left(\\mathbf{x}\\right)$',\n", + " xy=(XK[3, 0], XK[3, 1]),\n", + " xytext=(0.65, 0.50),\n", + " ha=\"center\",\n", + " arrowprops=dict(facecolor='black', shrink=0.1),\n", + " fontsize=18,\n", + " )\n", + "plt.plot([-0.1, 1.1], [0.57, -0.1], \"r--\", linewidth=3)\n", + "plt.axis([-0.1, 1.1, -0.1, 1.1])\n", + " \n", + "plt.subplots_adjust(right=1)\n", + "\n", + "plt.show()\n", + "\n", + "\n", + "x1_example = X1D[3, 0]\n", + "for landmark in (-2, 1):\n", + " k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)\n", + " print(\"Phi({}, {}) = {}\".format(x1_example, landmark, k))\n", + "\n", + "rbf_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"rbf\", gamma=5, C=0.001))\n", + " ])\n", + "rbf_kernel_svm_clf.fit(X, y)\n", + "\n", + "\n", + "from sklearn.svm import SVC\n", + "\n", + "gamma1, gamma2 = 0.1, 5\n", + "C1, C2 = 0.001, 1000\n", + "hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)\n", + "\n", + "svm_clfs = []\n", + "for gamma, C in hyperparams:\n", + " rbf_kernel_svm_clf = Pipeline([\n", + " (\"scaler\", StandardScaler()),\n", + " (\"svm_clf\", SVC(kernel=\"rbf\", gamma=gamma, C=C))\n", + " ])\n", + " rbf_kernel_svm_clf.fit(X, y)\n", + " svm_clfs.append(rbf_kernel_svm_clf)\n", + "\n", + "plt.figure(figsize=(11, 7))\n", + "\n", + "for i, svm_clf in enumerate(svm_clfs):\n", + " plt.subplot(221 + i)\n", + " plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])\n", + " plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", + " gamma, C = hyperparams[i]\n", + " plt.title(r\"$\\gamma = {}, C = {}$\".format(gamma, C), fontsize=16)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Mathematical optimization of convex functions\n", + "\n", + "A mathematical (quadratic) optimization problem, or just optimization problem, has the form" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{\\lambda}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{\\lambda}^T\\boldsymbol{P}\\boldsymbol{\\lambda}+\\boldsymbol{q}^T\\boldsymbol{\\lambda},\\\\ \\nonumber\n", + " &\\mathrm{subject\\hspace{0.1cm}to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h} \\wedge \\boldsymbol{A}\\boldsymbol{\\lambda}=f.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to some constraints for say a selected set $i=1,2,\\dots, n$.\n", + "In our case we are optimizing with respect to the Lagrangian multipliers $\\lambda_i$, and the\n", + "vector $\\boldsymbol{\\lambda}=[\\lambda_1, \\lambda_2,\\dots, \\lambda_n]$ is the optimization variable we are dealing with.\n", + "\n", + "In our case we are particularly interested in a class of optimization problems called convex optmization problems. \n", + "In our discussion on gradient descent methods we discussed at length the definition of a convex function. \n", + "\n", + "Convex optimization problems play a central role in applied mathematics and we recommend strongly [Boyd and Vandenberghe's text on the topics](http://web.stanford.edu/~boyd/cvxbook/).\n", + "\n", + "\n", + "\n", + "## How do we solve these problems?\n", + "\n", + "If we use Python as programming language and wish to venture beyond\n", + "**scikit-learn**, **tensorflow** and similar software which makes our\n", + "lives so much easier, we need to dive into the wonderful world of\n", + "quadratic programming. We can, if we wish, solve the minimization\n", + "problem using say standard gradient methods or conjugate gradient\n", + "methods. However, these methods tend to exhibit a rather slow\n", + "converge. So, welcome to the promised land of quadratic programming.\n", + "\n", + "The functions we need are contained in the quadratic programming package **CVXOPT** and we need to import it together with **numpy** as" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy\n", + "import cvxopt" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This will make our life much easier. You don't need t write your own optimizer.\n", + "\n", + "\n", + "## A simple example\n", + "\n", + "We remind ourselves about the general problem we want to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{x}\\hspace{0.2cm} \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{P}\\boldsymbol{x}+\\boldsymbol{q}^T\\boldsymbol{x},\\\\ \\nonumber\n", + " &\\mathrm{subject\\hspace{0.1cm} to} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{x} \\preceq \\boldsymbol{h} \\wedge \\boldsymbol{A}\\boldsymbol{x}=f.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + " &\\mathrm{min}_{x}\\hspace{0.2cm} \\frac{1}{2}x^2+5x+3y \\\\ \\nonumber\n", + " &\\mathrm{subject to} \\\\ \\nonumber\n", + " &x, y \\geq 0 \\\\ \\nonumber\n", + " &x+3y \\geq 15 \\\\ \\nonumber\n", + " &2x+5y \\leq 100 \\\\ \\nonumber\n", + " &3x+4y \\leq 80. \\\\ \\nonumber\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2}\\begin{bmatrix} x\\\\ y \\end{bmatrix}^T \\begin{bmatrix} 1 & 0\\\\ 0 & 0 \\end{bmatrix} \\begin{bmatrix} x \\\\ y \\end{bmatrix} + \\begin{bmatrix}3\\\\ 4 \\end{bmatrix}^T \\begin{bmatrix}x \\\\ y \\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Similarly, we can now set up the inequalities (we need to change $\\geq$ to $\\leq$ by multiplying with $-1$ on bot sides) as the following matrix-vector equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{bmatrix} -1 & 0 \\\\ 0 & -1 \\\\ -1 & -3 \\\\ 2 & 5 \\\\ 3 & 4\\end{bmatrix}\\begin{bmatrix} x \\\\ y\\end{bmatrix} \\preceq \\begin{bmatrix}0 \\\\ 0\\\\ -15 \\\\ 100 \\\\ 80\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We have collapsed all the inequalities into a single matrix $\\boldsymbol{G}$. We see also that our matrix" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{P} =\\begin{bmatrix} 1 & 0\\\\ 0 & 0 \\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is clearly positive semi-definite (all eigenvalues larger or equal zero). \n", + "Finally, the vector $\\boldsymbol{h}$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{h} = \\begin{bmatrix}0 \\\\ 0\\\\ -15 \\\\ 100 \\\\ 80\\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since we don't have any equalities the matrix $\\boldsymbol{A}$ is set to zero\n", + "The following code solves the equations for us" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Import the necessary packages\n", + "import numpy\n", + "from cvxopt import matrix\n", + "from cvxopt import solvers\n", + "P = matrix(numpy.diag([1,0]), tc=’d’)\n", + "q = matrix(numpy.array([3,4]), tc=’d’)\n", + "G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=’d’)\n", + "h = matrix(numpy.array([0,0,-15,100,80]), tc=’d’)\n", + "# Construct the QP, invoke solver\n", + "sol = solvers.qp(P,q,G,h)\n", + "# Extract optimal value and solution\n", + "sol[’x’] \n", + "sol[’primal objective’]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Back to the more realistic cases\n", + "\n", + "We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the **slack** parameter $C$ we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n", + "y_2y_1K(\\boldsymbol{x}_2,\\boldsymbol{x}_1) & y_2y_2K(\\boldsymbol{x}_2,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_2,\\boldsymbol{x}_n) \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "\\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", + "y_ny_1K(\\boldsymbol{x}_n,\\boldsymbol{x}_1) & y_ny_2K(\\boldsymbol{x}_n\\boldsymbol{x}_2) & \\dots & \\dots & y_ny_nK(\\boldsymbol{x}_n,\\boldsymbol{x}_n) \\\\\n", + "\\end{bmatrix}\\boldsymbol{\\lambda}-\\mathbb{I}\\boldsymbol{\\lambda},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", + "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", + "With the slack constants this leads to the additional constraint $0\\leq \\lambda_i \\leq C$.\n", + "\n", + "**code will be added**" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +}