diff --git a/doc/pub/week48/html/week48-bs.html b/doc/pub/week48/html/week48-bs.html index 16ea128bc..ce7e9f3ae 100644 --- a/doc/pub/week48/html/week48-bs.html +++ b/doc/pub/week48/html/week48-bs.html @@ -1,31 +1,28 @@ - + - Week 48: Support Vector Machines and Summary of course - + - - - @@ -166,8 +250,6 @@ MathJax.Hub.Config({ - - -
-

 

 

 

- - - -
-

Week 48: Support Vector Machines and Summary of course

- -

- -

-Morten Hjorth-Jensen [1, 2] +

Week 48: Support Vector Machines and Summary of course

+
+ + +
+Morten Hjorth-Jensen +
+ +
+Department of Physics, University of Oslo, Norway
- -

- - -

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

-

-

Nov 29, 2020

+
+

Nov 21, 2024

+

-

+

Read »

@@ -306,29 +386,22 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 65
  • +
  • 71
  • »
  • -
    - - -
    - © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week48/html/week48-reveal.html b/doc/pub/week48/html/week48-reveal.html index 068a9388c..234889bce 100644 --- a/doc/pub/week48/html/week48-reveal.html +++ b/doc/pub/week48/html/week48-reveal.html @@ -1,19 +1,18 @@ + - + + - + - Week 48: Support Vector Machines and Summary of course - - - - - - - + @@ -55,36 +54,81 @@ document.getElementsByTagName( 'head' )[0].appendChild( link ); - - - @@ -186,736 +277,988 @@ MathJax.Hub.Config({ - - - - - -

    Week 48: Support Vector Machines and Summary of course

    - -

    - -

    -Morten Hjorth-Jensen [1, 2] +

    Week 48: Support Vector Machines and Summary of course

    +
    + + +
    +Morten Hjorth-Jensen +
    + +
    +Department of Physics, University of Oslo, Norway
    - -

    - - -

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

    -

    -

    Nov 29, 2020

    +
    +

    Nov 21, 2024

    +

    -

    +









    +

    Overview of week 48

    -

    Overview of week 48

    +









    +

    Plan for week 47

    +
    +Lab sessions on Tuesday and Wednesday +

    +
    + -See also Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones) of Hastie et al contains also a good discussion. - +
    +Plans for the lecture Monday 25 November, with video suggestions etc

    +

      +
    1. Bossting and gradient boosting and ensemble models
    2. +
    3. Summary of course
    4. +
    5. Readings and Videos: +
        +
      1. These lecture notes at https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week47/ipynb/week48.ipynb
      2. +
      3. See also lecture notes from week 47 at https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week46/ipynb/week47.ipynb. The lecture on Monday starts with a repetition on AdaBoost before we move over to gradient boosting with examples + +
      4. +
      5. Video on Decision trees https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn
      6. +
      7. Video on boosting methods https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai
      8. +
      9. Video on AdaBoost https://www.youtube.com/watch?v=LsK-xG1cLYA
      10. +
      11. Video on Gradient boost, part 1, parts 2-4 follow thereafter https://www.youtube.com/watch?v=3CC4N4z3GJc
      12. +
      13. Decision Trees: Rashcka et al chapter 3 pages 86-98, and chapter 7 on Ensemble methods, Voting and Bagging and Gradient Boosting. See also lecture from STK-IN4300, lecture 7 at https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf.
      14. +
      +
    +
    + +









    +

    Boosting, a Bird's Eye View

    -

    Thursday

    +

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

    -

    -We finalize our discussion on Support Vector Machines with an emphasis on kernel transformations and applications to regression. The following video attempts at giving an overview on this part. See also the follow-up video. +

    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

    -

    Friday

    +

    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), +$$ -

    -Friday's lecture is split in two parts. It starts with a summary of -what we have done this semester and continues with perspectives for future studies and -modern research projects in machine learning. +

    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

    -

    Support Vector Machines, overarching aims

    - -

    -As discussed last week, -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. - -

    -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. I recommend you take a look at the lectures from last week on the binary classification problem. - -

    -









    - -

    Kernels and non-linearity

    - -

    -The cases we studied last week 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 -generated by the code below, we can achieve a better separation by introducing a more complex -basis functions. The ideal would be, as shown by the code example below, to, -via a specific transformation to obtain a separation between the -classes that is almost linear. See also Figures 12.2 and 12.3 of Hastie et al.. - -

    -We can achieve a better separation by introducing more complex -basis functions. The ideal would be (see Figures 12.2 and 12.3) 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 define a vector \( \boldsymbol{x}_i=[x_i,y_i] \) and have -$$ -\boldsymbol{z}_i^T = \phi(\boldsymbol{x}_i)^T =\left[1, \sqrt{2}x_i, \sqrt{2}y_i, 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{z}_i^T\boldsymbol{w}+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)=[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i]\begin{bmatrix} 1\\ \sqrt{2}x_j \\ \sqrt{2}y_j \\ x_j^2\\ y_i^2\\ \sqrt{2}x_jy_j \end{bmatrix}=1+2x_ix_j+2y_iy_j+(x_ix_j)^2+(y_iy_j)^2+2x_ix_jy_iy_j. -$$ - -

    -We note that this dot product can be rewritten as -$$ -K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[1+\boldsymbol{x}_i^T\boldsymbol{x}_j]^d, -$$ - -where \( d=2 \) in our case and \( \boldsymbol{x}_i=[x_i,y_i] \) and \( \boldsymbol{x}_j=[x_j,y_j] \). -To compute the last equation is however inefficient from a computational stand. -Instead of computing the last equation for the kernel, we simply compute -the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). -This leads to the so-called -kernel trick. - -

    -









    - -

    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{z}_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 \). - -

    -









    - -

    Tailoring the equations to the usage of CVXOPT

    - -

    -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{s.t} \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 +

    The way we proceed is as follows (here we specialize to the squared-error cost function)

      -
    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. +
    9. 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) \).
    10. +
    11. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    12. +
    13. 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) \)
      +
    +

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

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











    +

    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.

    -

    The moons example (Adapted from Geron, chapter 5)

    -

    -

    from __future__ import division, print_function, unicode_literals
    +
    +
    +
    +
    +
    +
    from sklearn.ensemble import AdaBoostClassifier
     
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=2), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.01, random_state=42)
    +ada_clf.fit(X_train, y_train)
    +y_pred = ada_clf.predict(X_test)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = ada_clf.predict_proba(X_test)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Making an ADAboost code yourself

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +
    +class DecisionStump:
    +    def fit(self, X, y, weights):
    +        m, n = X.shape
    +        self.alpha = 0
    +        self.threshold = None
    +        self.polarity = 1
    +
    +        min_error = float('inf')
    +
    +        for feature in range(n):
    +            feature_values = np.unique(X[:, feature])
    +
    +            for threshold in feature_values:
    +                for polarity in [1, -1]:
    +                    predictions = np.ones(m)
    +                    predictions[X[:, feature] < threshold] = -1
    +                    predictions *= polarity
    +
    +                    error = sum(weights[predictions != y])
    +
    +                    if error < min_error:
    +                        min_error = error
    +                        self.alpha = 0.5 * np.log((1 - error) / (error + 1e-10))
    +                        self.threshold = threshold
    +                        self.feature_index = feature
    +                        self.polarity = polarity
    +
    +    def predict(self, X):
    +        m = X.shape[0]
    +        predictions = np.ones(m)
    +        if self.polarity == 1:
    +            predictions[X[:, self.feature_index] < self.threshold] = -1
    +        else:
    +            predictions[X[:, self.feature_index] >= self.threshold] = -1
    +        return predictions
    +
    +class AdaBoost:
    +    def fit(self, X, y, n_estimators):
    +        m = X.shape[0]
    +        self.alphas = []
    +        self.models = []
    +
    +        weights = np.ones(m) / m
    +
    +        for _ in range(n_estimators):
    +            stump = DecisionStump()
    +            stump.fit(X, y, weights)
    +            predictions = stump.predict(X)
    +
    +            error = sum(weights[predictions != y])
    +            if error == 0:
    +                break
    +
    +            self.models.append(stump)
    +            self.alphas.append(stump.alpha)
    +
    +            weights *= np.exp(-stump.alpha * y * predictions)
    +            weights /= np.sum(weights)
    +
    +    def predict(self, X):
    +        final_predictions = np.zeros(X.shape[0])
    +        for alpha, model in zip(self.alphas, self.models):
    +            final_predictions += alpha * model.predict(X)
    +        return np.sign(final_predictions)
    +
    +# Example dataset (X, y)
    +X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
    +y = np.array([-1, -1, -1, -1, 1, 1, 1, 1, 1, 1])  # Labels must be -1 or 1
    +
    +# Train AdaBoost
    +ada = AdaBoost()
    +ada.fit(X, y, n_estimators=10)
    +
    +# Predictions
    +predictions = ada.predict(X)
    +print("Predictions:", predictions)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Gradient boosting: Basics with Steepest Descent/Functional Gradient 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

    + +

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, +so we do not learn a function that can generalize. However, we can modify the algorithm by +fitting a weak learner to approximate the negative gradient signal. +

    + +

    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)+h_m(u_m,x) \);
      6. +
      +
    4. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    5. +
    +









    +

    Gradient Boosting, Examples of Regression

    + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
     import numpy as np
    -np.random.seed(42)
    +from sklearn.model_selection import train_test_split
    +from sklearn.ensemble import GradientBoostingRegressor
    +import scikitplot as skplt
    +from sklearn.metrics import mean_squared_error
     
    -import matplotlib
    -import matplotlib.pyplot as plt
    -plt.rcParams['axes.labelsize'] = 14
    -plt.rcParams['xtick.labelsize'] = 12
    -plt.rcParams['ytick.labelsize'] = 12
    +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)
    +
    +for degree in range(1,maxdegree):
    +    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
    +    model.fit(X_train,y_train)
    +    y_pred = model.predict(X_test)
    +    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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -from sklearn.svm import SVC -from sklearn import datasets +









    +

    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()
     
    -from sklearn.pipeline import Pipeline
    +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
    -from sklearn.svm import LinearSVC
    +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 Gradient boosting and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
     
    -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])
    +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()
    -
    -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])
    -
    +y_probas = gd_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +save_fig("gdclassiffierroc")
     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)
    -
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +save_fig("gdclassiffiercgain")
     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() -
    -











    +

    XGBoost: Extreme Gradient Boosting

    -

    Mathematical optimization of convex functions

    +

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

    -

    -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*} -$$ +

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

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

    It is now the algorithm which wins essentially all ML competitions!!!

    -

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











    +

    Regression Case

    -

    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 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 to write your own optimizer. +

    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +import xgboost as xgb
    +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)
    +
    +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,y_train)
    +    y_pred = model.predict(X_test)
    +    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

    -

    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{s.t.} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. -\end{align*} -$$ - -Note: we use s.t. for subject to. - -

    -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{s.t.} \\ \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}5\\ 3 \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 -

    +

    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 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']
    -
    -

    -









    +

    +
    +
    +
    +
    +
    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()
     
    -

    Back to the more realistic cases

    +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) -

    -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}, -$$ +xg_clf = xgb.XGBClassifier() +xg_clf.fit(X_train_scaled,y_train) -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 \). +y_test = xg_clf.predict(X_test_scaled) -

    -









    +print("Test set accuracy with Gradient Boosting and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) -

    Setting up the matrices and the problem

    - -

    -We have the general problem -$$ -\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{s.t.} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. -\end{align*} -$$ +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() -

      -
    1. With a given kernel we can thus define the matrix \( \boldsymbol{P} \).
    2. -
    3. 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.
    4. -
    5. The vector \( \boldsymbol{q} \) has all elements equal to \( -1 \).
    6. -
    7. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \).
    8. -
    9. To set up the matrix \( \boldsymbol{G} \) we 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} \).
    10. -
    +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() +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +









    +

    Gradient boosting, making our own code for a regression case

    -

    Setting up \( \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \)

    -

    -We have two constraints, \( 0\le \lambda_i \) and \( \lambda_i \le C \). To do this we multiply the ones with the constraint -\( \ge \) with \( -1 \) in order to get \( \le \). It means that the problem \( \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \) -can be written as -$$ -\begin{bmatrix} -1& 0 & 0 & \dots & 0 \\ -0& -1 & 0 & \dots & 0 \\ -0& 0 & -1 & \dots & 0 \\ -\dots& \dots & \dots & \dots & \dots \\ -0& 0 & 0 & \dots & -1 \\ -1 & 0 & 0 & \dots & 0 \\ -0& 1 & 0 & \dots & 0 \\ -0& 0 & 1 & \dots & 0 \\ -\dots& \dots & \dots & \dots & \dots \\ -0& 0 & 0 & \dots & 1 \\ -\end{bmatrix} -\begin{bmatrix} \lambda_1 \\ -\lambda_2 \\ -\lambda_3 \\ -\dots \\ -\lambda_n \\ -\end{bmatrix} \preceq -\begin{bmatrix} 0 \\ -0 \\ -0 \\ -\dots \\ -0 \\ -C \\ -C \\ -C \\ -\dots \\ -C \\ -\end{bmatrix}. -$$ + +

    +
    +
    +
    +
    +
    import numpy as np
    +class DecisionTreeRegressor:
    +    def __init__(self, max_depth=3):
    +        self.max_depth = max_depth
    +        self.tree = None
    +    def fit(self, X, y):
    +        self.tree = self._grow_tree(X, y)
    +    def _grow_tree(self, X, y, depth=0):
    +        n_samples, n_features = X.shape
    +        if depth < self.max_depth:
    +            best_feature, best_threshold = self._best_split(X, y)
    +            if best_feature is not None:
    +                left_indices = X[:, best_feature] < best_threshold
    +                right_indices = X[:, best_feature] >= best_threshold
    +                left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1)
    +                right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1)
    +                return (best_feature, best_threshold, left_child, right_child)
    +        return np.mean(y)
    +    def _best_split(self, X, y):
    +        best_mse = float('inf')
    +        best_feature, best_threshold = None, None
    +        n_samples, n_features = X.shape
    +        
    +        for feature in range(n_features):
    +            thresholds = np.unique(X[:, feature])
    +            for threshold in thresholds:
    +                left_indices = X[:, feature] < threshold
    +                right_indices = X[:, feature] >= threshold
    +                if len(y[left_indices]) > 0 and len(y[right_indices]) > 0:
    +                    left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2)
    +                    right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2)
    +                    mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples
    +                    
    +                    if mse < best_mse:
    +                        best_mse = mse
    +                        best_feature = feature
    +                        best_threshold = threshold
    +        return best_feature, best_threshold
    +    def predict(self, X):
    +        return np.array([self._predict_sample(sample, self.tree) for sample in X])
    +    def _predict_sample(self, sample, node):
    +        if isinstance(node, tuple):
    +            feature, threshold, left_child, right_child = node
    +            if sample[feature] < threshold:
    +                return self._predict_sample(sample, left_child)
    +            else:
    +                return self._predict_sample(sample, right_child)
    +        return node
    +class GradientBoostingRegressor:
    +    def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3):
    +        self.n_estimators = n_estimators
    +        self.learning_rate = learning_rate
    +        self.max_depth = max_depth
    +        self.models = []
    +    def fit(self, X, y):
    +        y_pred = np.zeros(y.shape)
    +        for _ in range(self.n_estimators):
    +            residuals = y - y_pred
    +            model = DecisionTreeRegressor(max_depth=self.max_depth)
    +            model.fit(X, residuals)
    +            y_pred += self.learning_rate * model.predict(X)
    +            self.models.append(model)
    +    def predict(self, X):
    +        y_pred = np.zeros(X.shape[0])
    +        for model in self.models:
    +            y_pred += self.learning_rate * model.predict(X)
    +        return y_pred
    +# Example usage
    +if __name__ == "__main__":
    +    # Sample data
    +    X = np.array([[1], [2], [3], [4], [5]])
    +    y = np.array([1.5, 1.7, 3.5, 3.7, 5.0])
    +    model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2)
    +    model.fit(X, y)
    +    predictions = model.predict(X)
    +    print("Predictions:", predictions)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    -And then we are ready to go. -











    +

    Summary of course

    -

    SVMs and Regression and multiclass classification

    - -

    -More text will be added here. See also Hastie et al. section 12.3. - -











    +

    What? Me worry? No final exam in this course!

    +

    +
    +

    +
    +

    -

    Summary of course

    - -











    +

    Topics we have covered this year

    -

    What? Me worry? No final exam in this course!

    -



    - -

    -









    - -

    Topics we have covered this year

    - -

    -The course has two central parts +

    The course has two central parts

    1. Statistical analysis and optimization of data
    2. Machine learning
    -









    +

    Statistical analysis and optimization of data

    -

    Statistical analysis and optimization of data

    - -

    -The following topics have been discussed: - +

    The following topics have been discussed:

    1. Basic concepts, expectation values, variance, covariance, correlation functions and errors;
    2. Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;
    3. @@ -925,57 +1268,42 @@ The following topics have been discussed:
    4. Practical optimization using Singular-value decomposition and least squares for parameterizing data.
    5. Principal Component Analysis to reduce the number of features.
    -









    +

    Machine learning

    -

    Machine learning

    - -

    -The following topics will be covered - +

    The following topics will be covered

    1. Linear methods for regression and classification: -
      1. Ordinary Least Squares
      2. Ridge regression
      3. Lasso regression
      4. Logistic regression
      -
    2. Neural networks and deep learning: -
      1. Feed Forward Neural Networks
      2. Convolutional Neural Networks
      3. Recurrent Neural Networks
      -
    3. Decisions trees and ensemble methods: -
      1. Decision trees
      2. Bagging and voting
      3. Random forests
      4. Boosting and gradient boosting
      -
    4. Support vector machines -
      1. Binary classification and multiclass classification
      2. Kernel methods
      3. Regression
      -
    -









    +

    Learning outcomes and overarching aims of this course

    -

    Learning outcomes and overarching aims of this course

    - -

    -The course introduces a variety of central algorithms and methods +

    The course introduces a variety of central algorithms and methods essential for studies of data analysis and machine learning. The course is project based and through the various projects, normally three, you will be exposed to fundamental research problems @@ -984,6 +1312,7 @@ results. The students will learn to develop and structure large codes for studying these systems, get acquainted with computing facilities and learn to handle large scientific projects. A good scientific and ethical conduct is emphasized throughout the course. +

    -









    - -

    Perspective on Machine Learning

    +

    Perspective on Machine Learning

    1. Rapidly emerging application area
    2. @@ -1006,20 +1333,16 @@ ethical conduct is emphasized throughout the course.
    3. Requires education/retraining for more widespread adoption
    4. A lot of “word-of-mouth” development methods
    - -Huge amounts of data sets require automation, classical analysis tools often inadequate. +

    Huge amounts of data sets require automation, classical analysis tools often inadequate. High energy physics hit this wall in the 90’s. In 2009 single top quark production was determined via Boosted decision trees, Bayesian Neural Networks, etc. +

    -











    +

    Machine Learning Research

    -

    Machine Learning Research

    - -

    -Where to find recent results: - +

    Where to find recent results:

    1. Conference proceedings, arXiv and blog posts!
    2. NIPS: Neural Information Processing Systems
    3. @@ -1028,10 +1351,8 @@ Where to find recent results:
    4. Journal of Machine Learning Research
    5. Follow ML on ArXiv
    -









    - -

    Starting your Machine Learning Project

    +

    Starting your Machine Learning Project

    1. Identify problem type: classification, regression
    2. @@ -1040,111 +1361,82 @@ Where to find recent results:
    3. Consider your data carefully again! Think of data representation more carefully.
    4. Based on your results, feedback loop to earliest possible point
    -









    - -

    Choose a Model and Algorithm

    +

    Choose a Model and Algorithm

    1. Supervised?
    2. Start with the simplest model that fits your problem
    3. Start with minimal processing of data
    -









    - -

    Preparing Your Data

    +

    Preparing Your Data

    1. Shuffle your data
    2. Mean center your data
    3. - -
    4. Normalize the variance
    5. - -
    6. Whitening
    7. - -
    8. When to do train/test split?
    -









    - -

    Which Activation and Weights to Choose in Neural Networks

    +

    Which Activation and Weights to Choose in Neural Networks

    1. RELU? ELU?
    2. Sigmoid or Tanh?
    3. Set all weights to 0?
    4. - -
    5. Set all weights to random values?
    6. - -
    -









    - -

    Optimization Methods and Hyperparameters

    - +

    Optimization Methods and Hyperparameters

    1. Stochastic gradient descent -
      1. Stochastic gradient descent + momentum
      -
    2. State-of-the-art approaches:
    3. - -
    - -Which regularization and hyperparameters? \( L_1 \) or \( L_2 \), soft +

    Which regularization and hyperparameters? \( L_1 \) or \( L_2 \), soft classifiers, depths of trees and many other. Need to explore a large set of hyperparameters and regularization methods. +

    -











    +

    Resampling

    -

    Resampling

    - -

    -When do we resample? +

    When do we resample?

    1. Bootstrap
    2. Cross-validation
    3. Jackknife and many other
    -









    +

    Other courses on Data science and Machine Learning at UiO

    -

    Other courses on Data science and Machine Learning at UiO

    - -

    -The link here https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/ gives an excellent overview of courses on Machine learning at UiO. +

    The link here https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/ gives an excellent overview of courses on Machine learning at UiO.

    1. STK2100 Machine learning and statistical methods for prediction and classification.
    2. @@ -1156,58 +1448,51 @@ The link here IN5400/INF5860 – Machine Learning for Image Analysis. An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too.
    3. TEK5040 – Dyp læring for autonome systemer. The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments.
    -









    - -

    Additional courses of interest

    +

    Additional courses of interest

    1. STK4051 Computational Statistics
    2. STK4021 Applied Bayesian Analysis and Numerical Methods
    -









    +

    What's the future like?

    -

    What's the future like?

    - -

    -Based on multi-layer nonlinear neural networks, deep learning can +

    Based on multi-layer nonlinear neural networks, deep learning can learn directly from raw data, automatically extract and abstract features from layer to layer, and then achieve the goal of regression, classification, or ranking. Deep learning has made breakthroughs in computer vision, speech processing and natural language, and reached or even surpassed human level. The success of deep learning is mainly due to the three factors: big data, big model, and big computing. +

    -

    -In the past few decades, many different architectures of deep neural +

    In the past few decades, many different architectures of deep neural networks have been proposed, such as - +

    1. Convolutional neural networks, which are mostly used in image and video data processing, and have also been applied to sequential data such as text processing;
    2. Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing;
    3. Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning.
    -









    +

    Types of Machine Learning, a repetition

    -

    Types of Machine Learning, a repetition

    - -

    -The approaches to machine learning are many, but are often split into two main categories. +

    The approaches to machine learning are many, but are often split into two main categories. In supervised learning we know the answer to a problem, and let the computer deduce the logic behind it. On the other hand, unsupervised learning is a method for finding patterns and relationship in data sets without any prior knowledge of the system. Some authours also operate with a third category, namely reinforcement learning. This is a paradigm of learning inspired by behavioural psychology, where learning is achieved by trial-and-error, solely from rewards and punishment. +

    -

    -Another way to categorize machine learning tasks is to consider the desired output of a system. +

    Another way to categorize machine learning tasks is to consider the desired output of a system. Some of the most common tasks are: +

    -











    +

    Why Boltzmann machines?

    -

    Why Boltzmann machines?

    - -

    -What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately. +

    What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately. One of the major reasons is that they can be stacked layer-wise to build deep neural networks that capture complicated statistics. +

    -

    -The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images. +

    The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images.

    -

    -Furthermore, they have been used to solve complicated quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models. +

    Furthermore, they have been used to solve complicated quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models.

    -











    +

    Boltzmann Machines

    -

    Boltzmann Machines

    - -

    -Why use a generative model rather than the more well known discriminative deep neural networks (DNN)? +

    Why use a generative model rather than the more well known discriminative deep neural networks (DNN)?

    -









    - -

    Some similarities and differences from DNNs

    +

    Some similarities and differences from DNNs

    1. Both use gradient-descent based learning procedures for minimizing cost functions
    2. Energy based models don't use backpropagation and automatic differentiation for computing gradients, instead turning to Markov Chain Monte Carlo methods.
    3. DNNs often have several hidden layers. A restricted Boltzmann machine has only one hidden layer, however several RBMs can be stacked to make up Deep Belief Networks, of which they constitute the building blocks.
    +

    History: The RBM was developed by amongst others Geoffrey Hinton, called by some the "Godfather of Deep Learning", working with the University of Toronto and Google.

    -History: The RBM was developed by amongst others Geoffrey Hinton, called by some the "Godfather of Deep Learning", working with the University of Toronto and Google. - -











    +

    Boltzmann machines (BM)

    -

    Boltzmann machines (BM)

    - -

    -A BM is what we would call an undirected probabilistic graphical model +

    A BM is what we would call an undirected probabilistic graphical model with stochastic continuous or discrete units. +

    -It is interpreted as a stochastic recurrent neural network where the +

    It is interpreted as a stochastic recurrent neural network where the state of each unit(neurons/nodes) depends on the units it is connected to. The weights in the network represent thus the strength of the interaction between various units/nodes. +

    -It turns into a Hopfield network if we choose deterministic rather +

    It turns into a Hopfield network if we choose deterministic rather than stochastic units. In contrast to a Hopfield network, a BM is a so-called generative model. It allows us to generate new samples from the learned distribution. +

    -











    +

    A standard BM setup

    -

    A standard BM setup

    - -

    -A standard BM network is divided into a set of observable and visible units \( \hat{x} \) and a set of unknown hidden units/nodes \( \hat{h} \). +

    A standard BM network is divided into a set of observable and visible units \( \hat{x} \) and a set of unknown hidden units/nodes \( \hat{h} \).

    -

    -Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to \( 1 \). +

    Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to \( 1 \).

    -

    -BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning +

    BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning

    -

    -However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS. +

    However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS. Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below. +

    -











    +

    The structure of the RBM network

    -

    The structure of the RBM network

    +

    +
    +

    +
    +

    -

    -



    - -











    +

    The network

    -

    The network

    - -

    The network layers: -

    1. A function \( \mathbf{x} \) that represents the visible layer, a vector of \( M \) elements (nodes). This layer represents both what the RBM might be given as training input, and what we want it to be able to reconstruct. This might for example be given by the pixels of an image or coefficients representing speech, or the coordinates of a quantum mechanical state function.
    2. The function \( \mathbf{h} \) represents the hidden, or latent, layer. A vector of \( N \) elements (nodes). Also called "feature detectors".
    -









    +

    Goals

    -

    Goals

    - -

    -The goal of the hidden layer is to increase the model's expressive +

    The goal of the hidden layer is to increase the model's expressive power. We encode complex interactions between visible variables by introducing additional, hidden variables that interact with visible degrees of freedom in a simple manner, yet still reproduce the complex correlations between visible degrees in the data once marginalized over (integrated out). +

    -

    The network parameters, to be optimized/learned: -

    1. \( \mathbf{a} \) represents the visible bias, a vector of same length as \( \mathbf{x} \).
    2. \( \mathbf{b} \) represents the hidden bias, a vector of same lenght as \( \mathbf{h} \).
    3. \( W \) represents the interaction weights, a matrix of size \( M\times N \).
    -









    +

    Joint distribution

    -

    Joint distribution

    - -

    -The restricted Boltzmann machine is described by a Boltzmann distribution +

    The restricted Boltzmann machine is described by a Boltzmann distribution

    $$ \begin{align} P_{rbm}(\mathbf{x},\mathbf{h}) = \frac{1}{Z} e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})}, @@ -1385,7 +1643,7 @@ $$ \end{align} $$ -where \( Z \) is the normalization constant or partition function, defined as +

    where \( Z \) is the normalization constant or partition function, defined as

    $$ \begin{align} Z = \int \int e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})} d\mathbf{x} d\mathbf{h}. @@ -1393,49 +1651,39 @@ $$ \end{align} $$ -It is common to ignore \( T_0 \) by setting it to one. +

    It is common to ignore \( T_0 \) by setting it to one.

    -











    +

    Network Elements, the energy function

    -

    Network Elements, the energy function

    - -

    -The function \( E(\mathbf{x},\mathbf{h}) \) gives the energy of a +

    The function \( E(\mathbf{x},\mathbf{h}) \) gives the energy of a configuration (pair of vectors) \( (\mathbf{x}, \mathbf{h}) \). The lower the energy of a configuration, the higher the probability of it. This function also depends on the parameters \( \mathbf{a} \), \( \mathbf{b} \) and \( W \). Thus, when we adjust them during the learning procedure, we are adjusting the energy function to best fit our problem. +

    -

    -An expression for the energy function is +

    An expression for the energy function is

    $$ E(\hat{x},\hat{h}) = -\sum_{ia}^{NA}b_i^a \alpha_i^a(x_i)-\sum_{jd}^{MD}c_j^d \beta_j^d(h_j)-\sum_{ijad}^{NAMD}b_i^a \alpha_i^a(x_i)c_j^d \beta_j^d(h_j)w_{ij}^{ad}. $$ -

    -Here \( \beta_j^d(h_j) \) and \( \alpha_i^a(x_j) \) are so-called transfer functions that map a given input value to a desired feature value. The labels \( a \) and \( d \) denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. Note that there is no connection between nodes in a layer. +

    Here \( \beta_j^d(h_j) \) and \( \alpha_i^a(x_j) \) are so-called transfer functions that map a given input value to a desired feature value. The labels \( a \) and \( d \) denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. Note that there is no connection between nodes in a layer.

    -

    -The quantities \( b \) and \( c \) can be interpreted as the visible and hidden biases, respectively. +

    The quantities \( b \) and \( c \) can be interpreted as the visible and hidden biases, respectively.

    -

    -The connection between the nodes in the two layers is given by the weights \( w_{ij} \). +

    The connection between the nodes in the two layers is given by the weights \( w_{ij} \).

    -











    +

    Defining different types of RBMs

    +

    There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function \( E(\mathbf{x},\mathbf{h}) \).

    -

    Defining different types of RBMs

    -There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function \( E(\mathbf{x},\mathbf{h}) \). - -

    Binary-Binary RBM:

    -

    -RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows: +

    RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows:

    $$ \begin{align} E(\mathbf{x}, \mathbf{h}) = - \sum_i^M x_i a_i- \sum_j^N b_j h_j - \sum_{i,j}^{M,N} x_i w_{ij} h_j, @@ -1443,15 +1691,14 @@ $$ \end{align} $$ -where the binary values taken on by the nodes are most commonly 0 and 1. +

    where the binary values taken on by the nodes are most commonly 0 and 1.

    Gaussian-Binary RBM:

    -

    -Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary: +

    Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary:

    $$ \begin{align} E(\mathbf{x}, \mathbf{h}) = \sum_i^M \frac{(x_i - a_i)^2}{2\sigma_i^2} - \sum_j^N b_j h_j - \sum_{i,j}^{M,N} \frac{x_i w_{ij} h_j}{\sigma_i^2}. @@ -1461,45 +1708,36 @@ $$
    -











    - -

    More about RBMs

    - +

    More about RBMs

    1. Useful when we model continuous data (i.e., we wish \( \mathbf{x} \) to be continuous)
    2. Requires a smaller learning rate, since there's no upper bound to the value a component might take in the reconstruction
    - -Other types of units include: - +

    Other types of units include:

    1. Softmax and multinomial units
    2. Gaussian visible and hidden units
    3. Binomial units
    4. Rectified linear units
    +

    To read more, see Lectures on Boltzmann machines in Physics.

    -To read more, see Lectures on Boltzmann machines in Physics. - -











    +

    Autoencoders: Overarching view

    -

    Autoencoders: Overarching view

    - -

    -Autoencoders are artificial neural networks capable of learning +

    Autoencoders are artificial neural networks capable of learning efficient representations of the input data (these representations are called codings) without any supervision (i.e., the training set is unlabeled). These codings typically have a much lower dimensionality than the input data, making -autoencoders useful for dimensionality reduction. +autoencoders useful for dimensionality reduction. +

    -

    -More importantly, autoencoders act as powerful feature detectors, and +

    More importantly, autoencoders act as powerful feature detectors, and they can be used for unsupervised pretraining of deep neural networks. +

    -

    -Lastly, they are capable of randomly generating new data that looks +

    Lastly, they are capable of randomly generating new data that looks very similar to the training data; this is called a generative model. For example, you could train an autoencoder on pictures of faces, and it would then be able to generate new faces. Surprisingly, @@ -1513,57 +1751,49 @@ autoencoder from trivially copying the inputs directly to the outputs, which forces it to learn efficient ways of representing the data. In short, the codings are byproducts of the autoencoder’s attempt to learn the identity function under some constraints. +

    -

    Video on autoencoders -

    -See also A. Geron's textbook, chapter 15. +

    See also A. Geron's textbook, chapter 15.

    -











    +

    Bayesian Machine Learning

    -

    Bayesian Machine Learning

    - -

    -This is an important topic if we aim at extracting a probability +

    This is an important topic if we aim at extracting a probability distribution. This gives us also a confidence interval and error estimates. +

    -

    -Bayesian machine learning allows us to encode our prior beliefs about +

    Bayesian machine learning allows us to encode our prior beliefs about what those models should look like, independent of what the data tells us. This is especially useful when we don’t have a ton of data to confidently learn our model. +

    -

    Video on Bayesian deep learning -

    -See also the slides here. +

    See also the slides here.

    -











    +

    Reinforcement Learning

    -

    Reinforcement Learning

    - -

    -Reinforcement Learning (RL) is one of the most exciting fields of +

    Reinforcement Learning (RL) is one of the most exciting fields of Machine Learning today, and also one of the oldest. It has been around since the 1950s, producing many interesting applications over the years. +

    -

    -It studies +

    It studies how agents take actions based on trial and error, so as to maximize some notion of cumulative reward in a dynamic system or environment. Due to its generality, the problem has also been studied in many other disciplines, such as game theory, control theory, operations research, information theory, multi-agent systems, swarm intelligence, statistics, and genetic algorithms. +

    -

    -In March 2016, AlphaGo, a computer program that plays the board game +

    In March 2016, AlphaGo, a computer program that plays the board game Go, beat Lee Sedol in a five-game match. This was the first time a computer Go program had beaten a 9-dan (highest rank) professional without handicaps. AlphaGo is based on deep convolutional neural @@ -1571,20 +1801,16 @@ networks and reinforcement learning. AlphaGo’s victory was a major milestone in artificial intelligence and it has also made reinforcement learning a hot research area in the field of machine learning. +

    -

    -Lecture on Reinforcement Learning. +

    Lecture on Reinforcement Learning.

    -

    -See also A. Geron's textbook, chapter 16. +

    See also A. Geron's textbook, chapter 16.

    -











    +

    Transfer learning

    -

    Transfer learning

    - -

    -The goal of transfer learning is to transfer the model or knowledge +

    The goal of transfer learning is to transfer the model or knowledge obtained from a source task to the target task, in order to resolve the issues of insufficient training data in the target task. The rationality of doing so lies in that usually the source and target @@ -1592,17 +1818,14 @@ tasks have inter-correlations, and therefore either the features, samples, or models in the source task might provide useful information for us to better solve the target task. Transfer learning is a hot research topic in recent years, with many problems still waiting to be studied. +

    -

    -Lecture on transfer learning. +

    Lecture on transfer learning.

    -











    +

    Adversarial learning

    -

    Adversarial learning

    - -

    -The conventional deep generative model has a potential problem: the +

    The conventional deep generative model has a potential problem: the model tends to generate extreme instances to maximize the probabilistic likelihood, which will hurt its performance. Adversarial learning utilizes the adversarial behaviors (e.g., generating @@ -1611,17 +1834,14 @@ robustness of the model and improve the quality of the generated data. In recent years, one of the most promising unsupervised learning technologies, generative adversarial networks (GAN), has already been successfully applied to image, speech, and text. +

    -

    -Lecture on adversial learning. +

    Lecture on adversial learning.

    -











    +

    Dual learning

    -

    Dual learning

    - -

    -Dual learning is a new learning paradigm, the basic idea of which is +

    Dual learning is a new learning paradigm, the basic idea of which is to use the primal-dual structure between machine learning tasks to obtain effective feedback/regularization, and guide and strengthen the learning process, thus reducing the requirement of large-scale labeled @@ -1630,42 +1850,35 @@ many problems in machine learning, including machine translation, image style conversion, question answering and generation, image classification and generation, text classification and generation, image-to-text, and text-to-image. +

    -











    +

    Distributed machine learning

    -

    Distributed machine learning

    - -

    -Distributed computation will speed up machine learning algorithms, +

    Distributed computation will speed up machine learning algorithms, significantly improve their efficiency, and thus enlarge their application. When distributed meets machine learning, more than just implementing the machine learning algorithms in parallel is required. +

    -











    +

    Meta learning

    -

    Meta learning

    - -

    -Meta learning is an emerging research direction in machine +

    Meta learning is an emerging research direction in machine learning. Roughly speaking, meta learning concerns learning how to learn, and focuses on the understanding and adaptation of the learning itself, instead of just completing a specific learning task. That is, a meta learner needs to be able to evaluate its own learning methods and adjust its own learning methods according to specific learning tasks. +

    -











    +

    The Challenges Facing Machine Learning

    -

    The Challenges Facing Machine Learning

    +

    While there has been much progress in machine learning, there are also challenges.

    -

    -While there has been much progress in machine learning, there are also challenges. - -

    -For example, the mainstream machine learning technologies are +

    For example, the mainstream machine learning technologies are black-box approaches, making us concerned about their potential risks. To tackle this challenge, we may want to make machine learning more explainable and controllable. As another example, the @@ -1680,27 +1893,23 @@ models for data fitting? Although there are many challenges, we are still very optimistic about the future of machine learning. As we look forward to the future, here are what we think the research hotspots in the next ten years will be. +

    -

    -See the article on Discovery of Physics From Data: Universal Laws and Discrepancies +

    See the article on Discovery of Physics From Data: Universal Laws and Discrepancies

    -











    +

    Explainable machine learning

    -

    Explainable machine learning

    - -

    -Machine learning, especially deep learning, evolves rapidly. The +

    Machine learning, especially deep learning, evolves rapidly. The ability gap between machine and human on many complex cognitive tasks becomes narrower and narrower. However, we are still in the very early stage in terms of explaining why those effective models work and how they work. +

    -

    -What is missing: the gap between correlation and causation. Standard Machine Learning is based on what e have called a frequentist approach. +

    What is missing: the gap between correlation and causation. Standard Machine Learning is based on what e have called a frequentist approach.

    -

    -Most +

    Most machine learning techniques, especially the statistical ones, depend highly on correlations in data sets to make predictions and analyses. In contrast, rational humans tend to reply on clear and trustworthy @@ -1708,48 +1917,41 @@ causality relations obtained via logical reasoning on real and clear facts. It is one of the core goals of explainable machine learning to transition from solving problems by data correlation to solving problems by logical reasoning. +

    -

    Bayesian Machine Learning is one of the exciting research directions in this field. -











    +

    Quantum machine learning

    -

    Quantum machine learning

    - -

    -Quantum machine learning is an emerging interdisciplinary research +

    Quantum machine learning is an emerging interdisciplinary research area at the intersection of quantum computing and machine learning. +

    -

    -Quantum computers use effects such as quantum coherence and quantum +

    Quantum computers use effects such as quantum coherence and quantum entanglement to process information, which is fundamentally different from classical computers. Quantum algorithms have surpassed the best classical algorithms in several problems (e.g., searching for an unsorted database, inverting a sparse matrix), which we call quantum acceleration. +

    -

    -When quantum computing meets machine learning, it can be a mutually +

    When quantum computing meets machine learning, it can be a mutually beneficial and reinforcing process, as it allows us to take advantage of quantum computing to improve the performance of classical machine learning algorithms. In addition, we can also use the machine learning algorithms (on classic computers) to analyze and improve quantum computing systems. +

    -

    -Lecture on Quantum ML. +

    Lecture on Quantum ML.

    -

    -Read interview with Maria Schuld on her work on Quantum Machine Learning. See also her recent textbook. +

    Read interview with Maria Schuld on her work on Quantum Machine Learning. See also her recent textbook.

    -











    +

    Quantum machine learning algorithms based on linear algebra

    -

    Quantum machine learning algorithms based on linear algebra

    - -

    -Many quantum machine learning algorithms are based on variants of +

    Many quantum machine learning algorithms are based on variants of quantum algorithms for solving linear equations, which can efficiently solve N-variable linear equations with complexity of O(log2 N) under certain conditions. The quantum matrix inversion algorithm can @@ -1761,28 +1963,24 @@ machine learning algorithms is data input—that is, how to initialize the quantum system with the entire data set. Although efficient data-input algorithms exist for certain situations, how to efficiently input data into a quantum system is as yet unknown for most cases. +

    -











    +

    Quantum reinforcement learning

    -

    Quantum reinforcement learning

    - -

    -In quantum reinforcement learning, a quantum agent interacts with the +

    In quantum reinforcement learning, a quantum agent interacts with the classical environment to obtain rewards from the environment, so as to adjust and improve its behavioral strategies. In some cases, it achieves quantum acceleration by the quantum processing capabilities of the agent or the possibility of exploring the environment through quantum superposition. Such algorithms have been proposed in superconducting circuits and systems of trapped ions. +

    -











    +

    Quantum deep learning

    -

    Quantum deep learning

    - -

    -Dedicated quantum information processors, such as quantum annealers +

    Dedicated quantum information processors, such as quantum annealers and programmable photonic circuits, are well suited for building deep quantum networks. The simplest deep quantum network is the Boltzmann machine. The classical Boltzmann machine consists of bits with tunable @@ -1794,14 +1992,12 @@ correspond to an adjustable Ising model. Then, by initializing the input neurons in the Boltzmann machine to a fixed state and allowing the system to heat up, we can read out the output qubits to get the result. +

    -











    +

    Social machine learning

    -

    Social machine learning

    - -

    -Machine learning aims to imitate how humans +

    Machine learning aims to imitate how humans learn. While we have developed successful machine learning algorithms, until now we have ignored one important fact: humans are social. Each of us is one part of the total society and it is difficult for us to @@ -1809,41 +2005,33 @@ live, learn, and improve ourselves, alone and isolated. Therefore, we should design machines with social properties. Can we let machines evolve by imitating human society so as to achieve more effective, intelligent, interpretable “social machine learning”? +

    -

    -And much more. +

    And much more.

    -











    +

    The last words?

    -

    The last words?

    - -

    -Early computer scientist Alan Kay said, The best way to predict the +

    Early computer scientist Alan Kay said, The best way to predict the future is to create it. Therefore, all machine learning practitioners, whether scholars or engineers, professors or students, need to work together to advance these important research topics. Together, we will not just predict the future, but create it. +

    -











    +

    Best wishes to you all and thanks so much for your heroic efforts this semester

    -

    Best wishes to you all and thanks so much for your heroic efforts this semester

    - -

    -



    - -

    +

    +

    +

    +
    +

    - -
    - © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week48/html/week48.html b/doc/pub/week48/html/week48.html index c375cc5f9..6004b819b 100644 --- a/doc/pub/week48/html/week48.html +++ b/doc/pub/week48/html/week48.html @@ -1,36 +1,105 @@ - + - Week 48: Support Vector Machines and Summary of course - - - - @@ -191,736 +354,988 @@ MathJax.Hub.Config({ - - - - - -

    Week 48: Support Vector Machines and Summary of course

    - -

    - -

    -Morten Hjorth-Jensen [1, 2] +

    Week 48: Support Vector Machines and Summary of course

    +
    + + +
    +Morten Hjorth-Jensen +
    + +
    +Department of Physics, University of Oslo, Norway
    - -

    - - -

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

    -

    -

    Nov 29, 2020

    +
    +

    Nov 21, 2024

    +

    -

    +









    +

    Overview of week 48

    -

    Overview of week 48

    +









    +

    Plan for week 47

    +
    +Lab sessions on Tuesday and Wednesday +

      -
    • Thursday: Support Vector Machines: Kernels, Classification and Regression. Video of Lecture.
    • -
    • Friday: Summary of course with perspectives for future studies. Video of Lecture.
    • +
    • Work and Discussion of project 3
    • +
    • Last weekly exercise,
    +
    + -See also Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones) of Hastie et al contains also a good discussion. - +
    +Plans for the lecture Monday 25 November, with video suggestions etc

    +

      +
    1. Bossting and gradient boosting and ensemble models
    2. +
    3. Summary of course
    4. +
    5. Readings and Videos: +
        +
      1. These lecture notes at https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week47/ipynb/week48.ipynb
      2. +
      3. See also lecture notes from week 47 at https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week46/ipynb/week47.ipynb. The lecture on Monday starts with a repetition on AdaBoost before we move over to gradient boosting with examples + +
      4. +
      5. Video on Decision trees https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn
      6. +
      7. Video on boosting methods https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai
      8. +
      9. Video on AdaBoost https://www.youtube.com/watch?v=LsK-xG1cLYA
      10. +
      11. Video on Gradient boost, part 1, parts 2-4 follow thereafter https://www.youtube.com/watch?v=3CC4N4z3GJc
      12. +
      13. Decision Trees: Rashcka et al chapter 3 pages 86-98, and chapter 7 on Ensemble methods, Voting and Bagging and Gradient Boosting. See also lecture from STK-IN4300, lecture 7 at https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf.
      14. +
      +
    +
    + +









    +

    Boosting, a Bird's Eye View

    -

    Thursday

    +

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

    -

    -We finalize our discussion on Support Vector Machines with an emphasis on kernel transformations and applications to regression. The following video attempts at giving an overview on this part. See also the follow-up video. +

    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

    -

    Friday

    +

    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), +$$ -

    -Friday's lecture is split in two parts. It starts with a summary of -what we have done this semester and continues with perspectives for future studies and -modern research projects in machine learning. +

    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

    -

    Support Vector Machines, overarching aims

    - -

    -As discussed last week, -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. - -

    -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. I recommend you take a look at the lectures from last week on the binary classification problem. - -

    -









    - -

    Kernels and non-linearity

    - -

    -The cases we studied last week 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 -generated by the code below, we can achieve a better separation by introducing a more complex -basis functions. The ideal would be, as shown by the code example below, to, -via a specific transformation to obtain a separation between the -classes that is almost linear. See also Figures 12.2 and 12.3 of Hastie et al.. - -

    -We can achieve a better separation by introducing more complex -basis functions. The ideal would be (see Figures 12.2 and 12.3) 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 define a vector \( \boldsymbol{x}_i=[x_i,y_i] \) and have -$$ -\boldsymbol{z}_i^T = \phi(\boldsymbol{x}_i)^T =\left[1, \sqrt{2}x_i, \sqrt{2}y_i, 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{z}_i^T\boldsymbol{w}+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)=[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i]\begin{bmatrix} 1\\ \sqrt{2}x_j \\ \sqrt{2}y_j \\ x_j^2\\ y_i^2\\ \sqrt{2}x_jy_j \end{bmatrix}=1+2x_ix_j+2y_iy_j+(x_ix_j)^2+(y_iy_j)^2+2x_ix_jy_iy_j. -$$ - -

    -We note that this dot product can be rewritten as -$$ -K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[1+\boldsymbol{x}_i^T\boldsymbol{x}_j]^d, -$$ - -where \( d=2 \) in our case and \( \boldsymbol{x}_i=[x_i,y_i] \) and \( \boldsymbol{x}_j=[x_j,y_j] \). -To compute the last equation is however inefficient from a computational stand. -Instead of computing the last equation for the kernel, we simply compute -the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). -This leads to the so-called -kernel trick. - -

    -









    - -

    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{z}_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 \). - -

    -









    - -

    Tailoring the equations to the usage of CVXOPT

    - -

    -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{s.t} \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 +

    The way we proceed is as follows (here we specialize to the squared-error cost function)

      -
    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. +
    9. 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) \).
    10. +
    11. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    12. +
    13. 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) \)
      +
    +

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

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











    +

    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.

    -

    The moons example (Adapted from Geron, chapter 5)

    -

    -

    from __future__ import division, print_function, unicode_literals
    +
    +
    +
    +
    +
    +
    from sklearn.ensemble import AdaBoostClassifier
     
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=2), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.01, random_state=42)
    +ada_clf.fit(X_train, y_train)
    +y_pred = ada_clf.predict(X_test)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = ada_clf.predict_proba(X_test)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Making an ADAboost code yourself

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +
    +class DecisionStump:
    +    def fit(self, X, y, weights):
    +        m, n = X.shape
    +        self.alpha = 0
    +        self.threshold = None
    +        self.polarity = 1
    +
    +        min_error = float('inf')
    +
    +        for feature in range(n):
    +            feature_values = np.unique(X[:, feature])
    +
    +            for threshold in feature_values:
    +                for polarity in [1, -1]:
    +                    predictions = np.ones(m)
    +                    predictions[X[:, feature] < threshold] = -1
    +                    predictions *= polarity
    +
    +                    error = sum(weights[predictions != y])
    +
    +                    if error < min_error:
    +                        min_error = error
    +                        self.alpha = 0.5 * np.log((1 - error) / (error + 1e-10))
    +                        self.threshold = threshold
    +                        self.feature_index = feature
    +                        self.polarity = polarity
    +
    +    def predict(self, X):
    +        m = X.shape[0]
    +        predictions = np.ones(m)
    +        if self.polarity == 1:
    +            predictions[X[:, self.feature_index] < self.threshold] = -1
    +        else:
    +            predictions[X[:, self.feature_index] >= self.threshold] = -1
    +        return predictions
    +
    +class AdaBoost:
    +    def fit(self, X, y, n_estimators):
    +        m = X.shape[0]
    +        self.alphas = []
    +        self.models = []
    +
    +        weights = np.ones(m) / m
    +
    +        for _ in range(n_estimators):
    +            stump = DecisionStump()
    +            stump.fit(X, y, weights)
    +            predictions = stump.predict(X)
    +
    +            error = sum(weights[predictions != y])
    +            if error == 0:
    +                break
    +
    +            self.models.append(stump)
    +            self.alphas.append(stump.alpha)
    +
    +            weights *= np.exp(-stump.alpha * y * predictions)
    +            weights /= np.sum(weights)
    +
    +    def predict(self, X):
    +        final_predictions = np.zeros(X.shape[0])
    +        for alpha, model in zip(self.alphas, self.models):
    +            final_predictions += alpha * model.predict(X)
    +        return np.sign(final_predictions)
    +
    +# Example dataset (X, y)
    +X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
    +y = np.array([-1, -1, -1, -1, 1, 1, 1, 1, 1, 1])  # Labels must be -1 or 1
    +
    +# Train AdaBoost
    +ada = AdaBoost()
    +ada.fit(X, y, n_estimators=10)
    +
    +# Predictions
    +predictions = ada.predict(X)
    +print("Predictions:", predictions)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Gradient boosting: Basics with Steepest Descent/Functional Gradient 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

    + +

    Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points, +so we do not learn a function that can generalize. However, we can modify the algorithm by +fitting a weak learner to approximate the negative gradient signal. +

    + +

    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)+h_m(u_m,x) \);
      6. +
      +
    4. The final estimate is then \( f_M(x) = \sum_{m=1}^M h_m(u_m,x) \).
    5. +
    +









    +

    Gradient Boosting, Examples of Regression

    + + +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
     import numpy as np
    -np.random.seed(42)
    +from sklearn.model_selection import train_test_split
    +from sklearn.ensemble import GradientBoostingRegressor
    +import scikitplot as skplt
    +from sklearn.metrics import mean_squared_error
     
    -import matplotlib
    -import matplotlib.pyplot as plt
    -plt.rcParams['axes.labelsize'] = 14
    -plt.rcParams['xtick.labelsize'] = 12
    -plt.rcParams['ytick.labelsize'] = 12
    +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)
    +
    +for degree in range(1,maxdegree):
    +    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
    +    model.fit(X_train,y_train)
    +    y_pred = model.predict(X_test)
    +    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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -from sklearn.svm import SVC -from sklearn import datasets +









    +

    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()
     
    -from sklearn.pipeline import Pipeline
    +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
    -from sklearn.svm import LinearSVC
    +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 Gradient boosting and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
     
    -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])
    +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()
    -
    -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])
    -
    +y_probas = gd_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +save_fig("gdclassiffierroc")
     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)
    -
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +save_fig("gdclassiffiercgain")
     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() -
    -











    +

    XGBoost: Extreme Gradient Boosting

    -

    Mathematical optimization of convex functions

    +

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

    -

    -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*} -$$ +

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

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

    It is now the algorithm which wins essentially all ML competitions!!!

    -

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











    +

    Regression Case

    -

    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 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 to write your own optimizer. +

    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +import xgboost as xgb
    +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)
    +
    +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,y_train)
    +    y_pred = model.predict(X_test)
    +    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

    -

    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{s.t.} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. -\end{align*} -$$ - -Note: we use s.t. for subject to. - -

    -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{s.t.} \\ \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}5\\ 3 \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 -

    +

    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 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']
    -
    -

    -









    +

    +
    +
    +
    +
    +
    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()
     
    -

    Back to the more realistic cases

    +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) -

    -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}, -$$ +xg_clf = xgb.XGBClassifier() +xg_clf.fit(X_train_scaled,y_train) -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 \). +y_test = xg_clf.predict(X_test_scaled) -

    -









    +print("Test set accuracy with Gradient Boosting and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) -

    Setting up the matrices and the problem

    - -

    -We have the general problem -$$ -\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{s.t.} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. -\end{align*} -$$ +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() -

      -
    1. With a given kernel we can thus define the matrix \( \boldsymbol{P} \).
    2. -
    3. 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.
    4. -
    5. The vector \( \boldsymbol{q} \) has all elements equal to \( -1 \).
    6. -
    7. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \).
    8. -
    9. To set up the matrix \( \boldsymbol{G} \) we 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} \).
    10. -
    +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() +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +









    +

    Gradient boosting, making our own code for a regression case

    -

    Setting up \( \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \)

    -

    -We have two constraints, \( 0\le \lambda_i \) and \( \lambda_i \le C \). To do this we multiply the ones with the constraint -\( \ge \) with \( -1 \) in order to get \( \le \). It means that the problem \( \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \) -can be written as -$$ -\begin{bmatrix} -1& 0 & 0 & \dots & 0 \\ -0& -1 & 0 & \dots & 0 \\ -0& 0 & -1 & \dots & 0 \\ -\dots& \dots & \dots & \dots & \dots \\ -0& 0 & 0 & \dots & -1 \\ -1 & 0 & 0 & \dots & 0 \\ -0& 1 & 0 & \dots & 0 \\ -0& 0 & 1 & \dots & 0 \\ -\dots& \dots & \dots & \dots & \dots \\ -0& 0 & 0 & \dots & 1 \\ -\end{bmatrix} -\begin{bmatrix} \lambda_1 \\ -\lambda_2 \\ -\lambda_3 \\ -\dots \\ -\lambda_n \\ -\end{bmatrix} \preceq -\begin{bmatrix} 0 \\ -0 \\ -0 \\ -\dots \\ -0 \\ -C \\ -C \\ -C \\ -\dots \\ -C \\ -\end{bmatrix}. -$$ + +

    +
    +
    +
    +
    +
    import numpy as np
    +class DecisionTreeRegressor:
    +    def __init__(self, max_depth=3):
    +        self.max_depth = max_depth
    +        self.tree = None
    +    def fit(self, X, y):
    +        self.tree = self._grow_tree(X, y)
    +    def _grow_tree(self, X, y, depth=0):
    +        n_samples, n_features = X.shape
    +        if depth < self.max_depth:
    +            best_feature, best_threshold = self._best_split(X, y)
    +            if best_feature is not None:
    +                left_indices = X[:, best_feature] < best_threshold
    +                right_indices = X[:, best_feature] >= best_threshold
    +                left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1)
    +                right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1)
    +                return (best_feature, best_threshold, left_child, right_child)
    +        return np.mean(y)
    +    def _best_split(self, X, y):
    +        best_mse = float('inf')
    +        best_feature, best_threshold = None, None
    +        n_samples, n_features = X.shape
    +        
    +        for feature in range(n_features):
    +            thresholds = np.unique(X[:, feature])
    +            for threshold in thresholds:
    +                left_indices = X[:, feature] < threshold
    +                right_indices = X[:, feature] >= threshold
    +                if len(y[left_indices]) > 0 and len(y[right_indices]) > 0:
    +                    left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2)
    +                    right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2)
    +                    mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples
    +                    
    +                    if mse < best_mse:
    +                        best_mse = mse
    +                        best_feature = feature
    +                        best_threshold = threshold
    +        return best_feature, best_threshold
    +    def predict(self, X):
    +        return np.array([self._predict_sample(sample, self.tree) for sample in X])
    +    def _predict_sample(self, sample, node):
    +        if isinstance(node, tuple):
    +            feature, threshold, left_child, right_child = node
    +            if sample[feature] < threshold:
    +                return self._predict_sample(sample, left_child)
    +            else:
    +                return self._predict_sample(sample, right_child)
    +        return node
    +class GradientBoostingRegressor:
    +    def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3):
    +        self.n_estimators = n_estimators
    +        self.learning_rate = learning_rate
    +        self.max_depth = max_depth
    +        self.models = []
    +    def fit(self, X, y):
    +        y_pred = np.zeros(y.shape)
    +        for _ in range(self.n_estimators):
    +            residuals = y - y_pred
    +            model = DecisionTreeRegressor(max_depth=self.max_depth)
    +            model.fit(X, residuals)
    +            y_pred += self.learning_rate * model.predict(X)
    +            self.models.append(model)
    +    def predict(self, X):
    +        y_pred = np.zeros(X.shape[0])
    +        for model in self.models:
    +            y_pred += self.learning_rate * model.predict(X)
    +        return y_pred
    +# Example usage
    +if __name__ == "__main__":
    +    # Sample data
    +    X = np.array([[1], [2], [3], [4], [5]])
    +    y = np.array([1.5, 1.7, 3.5, 3.7, 5.0])
    +    model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2)
    +    model.fit(X, y)
    +    predictions = model.predict(X)
    +    print("Predictions:", predictions)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    -And then we are ready to go. -











    +

    Summary of course

    -

    SVMs and Regression and multiclass classification

    - -

    -More text will be added here. See also Hastie et al. section 12.3. - -











    +

    What? Me worry? No final exam in this course!

    +

    +
    +

    +
    +

    -

    Summary of course

    - -











    +

    Topics we have covered this year

    -

    What? Me worry? No final exam in this course!

    -



    - -

    -









    - -

    Topics we have covered this year

    - -

    -The course has two central parts +

    The course has two central parts

    1. Statistical analysis and optimization of data
    2. Machine learning
    -









    +

    Statistical analysis and optimization of data

    -

    Statistical analysis and optimization of data

    - -

    -The following topics have been discussed: - +

    The following topics have been discussed:

    1. Basic concepts, expectation values, variance, covariance, correlation functions and errors;
    2. Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;
    3. @@ -930,57 +1345,42 @@ The following topics have been discussed:
    4. Practical optimization using Singular-value decomposition and least squares for parameterizing data.
    5. Principal Component Analysis to reduce the number of features.
    -









    +

    Machine learning

    -

    Machine learning

    - -

    -The following topics will be covered - +

    The following topics will be covered

    1. Linear methods for regression and classification: -
      1. Ordinary Least Squares
      2. Ridge regression
      3. Lasso regression
      4. Logistic regression
      -
    2. Neural networks and deep learning: -
      1. Feed Forward Neural Networks
      2. Convolutional Neural Networks
      3. Recurrent Neural Networks
      -
    3. Decisions trees and ensemble methods: -
      1. Decision trees
      2. Bagging and voting
      3. Random forests
      4. Boosting and gradient boosting
      -
    4. Support vector machines -
      1. Binary classification and multiclass classification
      2. Kernel methods
      3. Regression
      -
    -









    +

    Learning outcomes and overarching aims of this course

    -

    Learning outcomes and overarching aims of this course

    - -

    -The course introduces a variety of central algorithms and methods +

    The course introduces a variety of central algorithms and methods essential for studies of data analysis and machine learning. The course is project based and through the various projects, normally three, you will be exposed to fundamental research problems @@ -989,6 +1389,7 @@ results. The students will learn to develop and structure large codes for studying these systems, get acquainted with computing facilities and learn to handle large scientific projects. A good scientific and ethical conduct is emphasized throughout the course. +

    -









    - -

    Perspective on Machine Learning

    +

    Perspective on Machine Learning

    1. Rapidly emerging application area
    2. @@ -1011,20 +1410,16 @@ ethical conduct is emphasized throughout the course.
    3. Requires education/retraining for more widespread adoption
    4. A lot of “word-of-mouth” development methods
    - -Huge amounts of data sets require automation, classical analysis tools often inadequate. +

    Huge amounts of data sets require automation, classical analysis tools often inadequate. High energy physics hit this wall in the 90’s. In 2009 single top quark production was determined via Boosted decision trees, Bayesian Neural Networks, etc. +

    -











    +

    Machine Learning Research

    -

    Machine Learning Research

    - -

    -Where to find recent results: - +

    Where to find recent results:

    1. Conference proceedings, arXiv and blog posts!
    2. NIPS: Neural Information Processing Systems
    3. @@ -1033,10 +1428,8 @@ Where to find recent results:
    4. Journal of Machine Learning Research
    5. Follow ML on ArXiv
    -









    - -

    Starting your Machine Learning Project

    +

    Starting your Machine Learning Project

    1. Identify problem type: classification, regression
    2. @@ -1045,111 +1438,82 @@ Where to find recent results:
    3. Consider your data carefully again! Think of data representation more carefully.
    4. Based on your results, feedback loop to earliest possible point
    -









    - -

    Choose a Model and Algorithm

    +

    Choose a Model and Algorithm

    1. Supervised?
    2. Start with the simplest model that fits your problem
    3. Start with minimal processing of data
    -









    - -

    Preparing Your Data

    +

    Preparing Your Data

    1. Shuffle your data
    2. Mean center your data
    3. -
      • Why?
      -
    4. Normalize the variance
    5. -
      • Why?
      -
    6. Whitening
    7. -
      • Decorrelates data
      • Can be hit or miss
      -
    8. When to do train/test split?
    -









    - -

    Which Activation and Weights to Choose in Neural Networks

    +

    Which Activation and Weights to Choose in Neural Networks

    1. RELU? ELU?
    2. Sigmoid or Tanh?
    3. Set all weights to 0?
    4. -
      • Terrible idea
      -
    5. Set all weights to random values?
    6. -
      • Small random values
      -
    -









    - -

    Optimization Methods and Hyperparameters

    - +

    Optimization Methods and Hyperparameters

    1. Stochastic gradient descent -
      1. Stochastic gradient descent + momentum
      -
    2. State-of-the-art approaches:
    3. -
      • RMSProp
      • Adam
      • and more
      -
    - -Which regularization and hyperparameters? \( L_1 \) or \( L_2 \), soft +

    Which regularization and hyperparameters? \( L_1 \) or \( L_2 \), soft classifiers, depths of trees and many other. Need to explore a large set of hyperparameters and regularization methods. +

    -











    +

    Resampling

    -

    Resampling

    - -

    -When do we resample? +

    When do we resample?

    1. Bootstrap
    2. Cross-validation
    3. Jackknife and many other
    -









    +

    Other courses on Data science and Machine Learning at UiO

    -

    Other courses on Data science and Machine Learning at UiO

    - -

    -The link here https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/ gives an excellent overview of courses on Machine learning at UiO. +

    The link here https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/ gives an excellent overview of courses on Machine learning at UiO.

    1. STK2100 Machine learning and statistical methods for prediction and classification.
    2. @@ -1161,58 +1525,51 @@ The link here IN5400/INF5860 – Machine Learning for Image Analysis. An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too.
    3. TEK5040 – Dyp læring for autonome systemer. The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments.
    -









    - -

    Additional courses of interest

    +

    Additional courses of interest

    1. STK4051 Computational Statistics
    2. STK4021 Applied Bayesian Analysis and Numerical Methods
    -









    +

    What's the future like?

    -

    What's the future like?

    - -

    -Based on multi-layer nonlinear neural networks, deep learning can +

    Based on multi-layer nonlinear neural networks, deep learning can learn directly from raw data, automatically extract and abstract features from layer to layer, and then achieve the goal of regression, classification, or ranking. Deep learning has made breakthroughs in computer vision, speech processing and natural language, and reached or even surpassed human level. The success of deep learning is mainly due to the three factors: big data, big model, and big computing. +

    -

    -In the past few decades, many different architectures of deep neural +

    In the past few decades, many different architectures of deep neural networks have been proposed, such as - +

    1. Convolutional neural networks, which are mostly used in image and video data processing, and have also been applied to sequential data such as text processing;
    2. Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing;
    3. Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning.
    -









    +

    Types of Machine Learning, a repetition

    -

    Types of Machine Learning, a repetition

    - -

    -The approaches to machine learning are many, but are often split into two main categories. +

    The approaches to machine learning are many, but are often split into two main categories. In supervised learning we know the answer to a problem, and let the computer deduce the logic behind it. On the other hand, unsupervised learning is a method for finding patterns and relationship in data sets without any prior knowledge of the system. Some authours also operate with a third category, namely reinforcement learning. This is a paradigm of learning inspired by behavioural psychology, where learning is achieved by trial-and-error, solely from rewards and punishment. +

    -

    -Another way to categorize machine learning tasks is to consider the desired output of a system. +

    Another way to categorize machine learning tasks is to consider the desired output of a system. Some of the most common tasks are: +

    • Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.
    • @@ -1223,166 +1580,139 @@ Some of the most common tasks are:
    -











    +

    Why Boltzmann machines?

    -

    Why Boltzmann machines?

    - -

    -What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately. +

    What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately. One of the major reasons is that they can be stacked layer-wise to build deep neural networks that capture complicated statistics. +

    -

    -The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images. +

    The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images.

    -

    -Furthermore, they have been used to solve complicated quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models. +

    Furthermore, they have been used to solve complicated quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models.

    -











    +

    Boltzmann Machines

    -

    Boltzmann Machines

    - -

    -Why use a generative model rather than the more well known discriminative deep neural networks (DNN)? +

    Why use a generative model rather than the more well known discriminative deep neural networks (DNN)?

    -









    - -

    Some similarities and differences from DNNs

    +

    Some similarities and differences from DNNs

    1. Both use gradient-descent based learning procedures for minimizing cost functions
    2. Energy based models don't use backpropagation and automatic differentiation for computing gradients, instead turning to Markov Chain Monte Carlo methods.
    3. DNNs often have several hidden layers. A restricted Boltzmann machine has only one hidden layer, however several RBMs can be stacked to make up Deep Belief Networks, of which they constitute the building blocks.
    +

    History: The RBM was developed by amongst others Geoffrey Hinton, called by some the "Godfather of Deep Learning", working with the University of Toronto and Google.

    -History: The RBM was developed by amongst others Geoffrey Hinton, called by some the "Godfather of Deep Learning", working with the University of Toronto and Google. - -











    +

    Boltzmann machines (BM)

    -

    Boltzmann machines (BM)

    - -

    -A BM is what we would call an undirected probabilistic graphical model +

    A BM is what we would call an undirected probabilistic graphical model with stochastic continuous or discrete units. +

    -It is interpreted as a stochastic recurrent neural network where the +

    It is interpreted as a stochastic recurrent neural network where the state of each unit(neurons/nodes) depends on the units it is connected to. The weights in the network represent thus the strength of the interaction between various units/nodes. +

    -It turns into a Hopfield network if we choose deterministic rather +

    It turns into a Hopfield network if we choose deterministic rather than stochastic units. In contrast to a Hopfield network, a BM is a so-called generative model. It allows us to generate new samples from the learned distribution. +

    -











    +

    A standard BM setup

    -

    A standard BM setup

    - -

    -A standard BM network is divided into a set of observable and visible units \( \hat{x} \) and a set of unknown hidden units/nodes \( \hat{h} \). +

    A standard BM network is divided into a set of observable and visible units \( \hat{x} \) and a set of unknown hidden units/nodes \( \hat{h} \).

    -

    -Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to \( 1 \). +

    Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to \( 1 \).

    -

    -BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning +

    BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning

    -

    -However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS. +

    However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS. Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below. +

    -











    +

    The structure of the RBM network

    -

    The structure of the RBM network

    +

    +
    +

    +
    +

    -

    -



    - -











    +

    The network

    -

    The network

    - -

    The network layers: -

    1. A function \( \mathbf{x} \) that represents the visible layer, a vector of \( M \) elements (nodes). This layer represents both what the RBM might be given as training input, and what we want it to be able to reconstruct. This might for example be given by the pixels of an image or coefficients representing speech, or the coordinates of a quantum mechanical state function.
    2. The function \( \mathbf{h} \) represents the hidden, or latent, layer. A vector of \( N \) elements (nodes). Also called "feature detectors".
    -









    +

    Goals

    -

    Goals

    - -

    -The goal of the hidden layer is to increase the model's expressive +

    The goal of the hidden layer is to increase the model's expressive power. We encode complex interactions between visible variables by introducing additional, hidden variables that interact with visible degrees of freedom in a simple manner, yet still reproduce the complex correlations between visible degrees in the data once marginalized over (integrated out). +

    -

    The network parameters, to be optimized/learned: -

    1. \( \mathbf{a} \) represents the visible bias, a vector of same length as \( \mathbf{x} \).
    2. \( \mathbf{b} \) represents the hidden bias, a vector of same lenght as \( \mathbf{h} \).
    3. \( W \) represents the interaction weights, a matrix of size \( M\times N \).
    -









    +

    Joint distribution

    -

    Joint distribution

    - -

    -The restricted Boltzmann machine is described by a Boltzmann distribution +

    The restricted Boltzmann machine is described by a Boltzmann distribution

    $$ \begin{align} P_{rbm}(\mathbf{x},\mathbf{h}) = \frac{1}{Z} e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})}, @@ -1390,7 +1720,7 @@ $$ \end{align} $$ -where \( Z \) is the normalization constant or partition function, defined as +

    where \( Z \) is the normalization constant or partition function, defined as

    $$ \begin{align} Z = \int \int e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})} d\mathbf{x} d\mathbf{h}. @@ -1398,49 +1728,39 @@ $$ \end{align} $$ -It is common to ignore \( T_0 \) by setting it to one. +

    It is common to ignore \( T_0 \) by setting it to one.

    -











    +

    Network Elements, the energy function

    -

    Network Elements, the energy function

    - -

    -The function \( E(\mathbf{x},\mathbf{h}) \) gives the energy of a +

    The function \( E(\mathbf{x},\mathbf{h}) \) gives the energy of a configuration (pair of vectors) \( (\mathbf{x}, \mathbf{h}) \). The lower the energy of a configuration, the higher the probability of it. This function also depends on the parameters \( \mathbf{a} \), \( \mathbf{b} \) and \( W \). Thus, when we adjust them during the learning procedure, we are adjusting the energy function to best fit our problem. +

    -

    -An expression for the energy function is +

    An expression for the energy function is

    $$ E(\hat{x},\hat{h}) = -\sum_{ia}^{NA}b_i^a \alpha_i^a(x_i)-\sum_{jd}^{MD}c_j^d \beta_j^d(h_j)-\sum_{ijad}^{NAMD}b_i^a \alpha_i^a(x_i)c_j^d \beta_j^d(h_j)w_{ij}^{ad}. $$ -

    -Here \( \beta_j^d(h_j) \) and \( \alpha_i^a(x_j) \) are so-called transfer functions that map a given input value to a desired feature value. The labels \( a \) and \( d \) denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. Note that there is no connection between nodes in a layer. +

    Here \( \beta_j^d(h_j) \) and \( \alpha_i^a(x_j) \) are so-called transfer functions that map a given input value to a desired feature value. The labels \( a \) and \( d \) denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. Note that there is no connection between nodes in a layer.

    -

    -The quantities \( b \) and \( c \) can be interpreted as the visible and hidden biases, respectively. +

    The quantities \( b \) and \( c \) can be interpreted as the visible and hidden biases, respectively.

    -

    -The connection between the nodes in the two layers is given by the weights \( w_{ij} \). +

    The connection between the nodes in the two layers is given by the weights \( w_{ij} \).

    -











    +

    Defining different types of RBMs

    +

    There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function \( E(\mathbf{x},\mathbf{h}) \).

    -

    Defining different types of RBMs

    -There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function \( E(\mathbf{x},\mathbf{h}) \). - -

    Binary-Binary RBM:

    -

    -RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows: +

    RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows:

    $$ \begin{align} E(\mathbf{x}, \mathbf{h}) = - \sum_i^M x_i a_i- \sum_j^N b_j h_j - \sum_{i,j}^{M,N} x_i w_{ij} h_j, @@ -1448,15 +1768,14 @@ $$ \end{align} $$ -where the binary values taken on by the nodes are most commonly 0 and 1. +

    where the binary values taken on by the nodes are most commonly 0 and 1.

    Gaussian-Binary RBM:

    -

    -Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary: +

    Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary:

    $$ \begin{align} E(\mathbf{x}, \mathbf{h}) = \sum_i^M \frac{(x_i - a_i)^2}{2\sigma_i^2} - \sum_j^N b_j h_j - \sum_{i,j}^{M,N} \frac{x_i w_{ij} h_j}{\sigma_i^2}. @@ -1466,45 +1785,36 @@ $$
    -











    - -

    More about RBMs

    - +

    More about RBMs

    1. Useful when we model continuous data (i.e., we wish \( \mathbf{x} \) to be continuous)
    2. Requires a smaller learning rate, since there's no upper bound to the value a component might take in the reconstruction
    - -Other types of units include: - +

    Other types of units include:

    1. Softmax and multinomial units
    2. Gaussian visible and hidden units
    3. Binomial units
    4. Rectified linear units
    +

    To read more, see Lectures on Boltzmann machines in Physics.

    -To read more, see Lectures on Boltzmann machines in Physics. - -











    +

    Autoencoders: Overarching view

    -

    Autoencoders: Overarching view

    - -

    -Autoencoders are artificial neural networks capable of learning +

    Autoencoders are artificial neural networks capable of learning efficient representations of the input data (these representations are called codings) without any supervision (i.e., the training set is unlabeled). These codings typically have a much lower dimensionality than the input data, making -autoencoders useful for dimensionality reduction. +autoencoders useful for dimensionality reduction. +

    -

    -More importantly, autoencoders act as powerful feature detectors, and +

    More importantly, autoencoders act as powerful feature detectors, and they can be used for unsupervised pretraining of deep neural networks. +

    -

    -Lastly, they are capable of randomly generating new data that looks +

    Lastly, they are capable of randomly generating new data that looks very similar to the training data; this is called a generative model. For example, you could train an autoencoder on pictures of faces, and it would then be able to generate new faces. Surprisingly, @@ -1518,57 +1828,49 @@ autoencoder from trivially copying the inputs directly to the outputs, which forces it to learn efficient ways of representing the data. In short, the codings are byproducts of the autoencoder’s attempt to learn the identity function under some constraints. +

    -

    Video on autoencoders -

    -See also A. Geron's textbook, chapter 15. +

    See also A. Geron's textbook, chapter 15.

    -











    +

    Bayesian Machine Learning

    -

    Bayesian Machine Learning

    - -

    -This is an important topic if we aim at extracting a probability +

    This is an important topic if we aim at extracting a probability distribution. This gives us also a confidence interval and error estimates. +

    -

    -Bayesian machine learning allows us to encode our prior beliefs about +

    Bayesian machine learning allows us to encode our prior beliefs about what those models should look like, independent of what the data tells us. This is especially useful when we don’t have a ton of data to confidently learn our model. +

    -

    Video on Bayesian deep learning -

    -See also the slides here. +

    See also the slides here.

    -











    +

    Reinforcement Learning

    -

    Reinforcement Learning

    - -

    -Reinforcement Learning (RL) is one of the most exciting fields of +

    Reinforcement Learning (RL) is one of the most exciting fields of Machine Learning today, and also one of the oldest. It has been around since the 1950s, producing many interesting applications over the years. +

    -

    -It studies +

    It studies how agents take actions based on trial and error, so as to maximize some notion of cumulative reward in a dynamic system or environment. Due to its generality, the problem has also been studied in many other disciplines, such as game theory, control theory, operations research, information theory, multi-agent systems, swarm intelligence, statistics, and genetic algorithms. +

    -

    -In March 2016, AlphaGo, a computer program that plays the board game +

    In March 2016, AlphaGo, a computer program that plays the board game Go, beat Lee Sedol in a five-game match. This was the first time a computer Go program had beaten a 9-dan (highest rank) professional without handicaps. AlphaGo is based on deep convolutional neural @@ -1576,20 +1878,16 @@ networks and reinforcement learning. AlphaGo’s victory was a major milestone in artificial intelligence and it has also made reinforcement learning a hot research area in the field of machine learning. +

    -

    -Lecture on Reinforcement Learning. +

    Lecture on Reinforcement Learning.

    -

    -See also A. Geron's textbook, chapter 16. +

    See also A. Geron's textbook, chapter 16.

    -











    +

    Transfer learning

    -

    Transfer learning

    - -

    -The goal of transfer learning is to transfer the model or knowledge +

    The goal of transfer learning is to transfer the model or knowledge obtained from a source task to the target task, in order to resolve the issues of insufficient training data in the target task. The rationality of doing so lies in that usually the source and target @@ -1597,17 +1895,14 @@ tasks have inter-correlations, and therefore either the features, samples, or models in the source task might provide useful information for us to better solve the target task. Transfer learning is a hot research topic in recent years, with many problems still waiting to be studied. +

    -

    -Lecture on transfer learning. +

    Lecture on transfer learning.

    -











    +

    Adversarial learning

    -

    Adversarial learning

    - -

    -The conventional deep generative model has a potential problem: the +

    The conventional deep generative model has a potential problem: the model tends to generate extreme instances to maximize the probabilistic likelihood, which will hurt its performance. Adversarial learning utilizes the adversarial behaviors (e.g., generating @@ -1616,17 +1911,14 @@ robustness of the model and improve the quality of the generated data. In recent years, one of the most promising unsupervised learning technologies, generative adversarial networks (GAN), has already been successfully applied to image, speech, and text. +

    -

    -Lecture on adversial learning. +

    Lecture on adversial learning.

    -











    +

    Dual learning

    -

    Dual learning

    - -

    -Dual learning is a new learning paradigm, the basic idea of which is +

    Dual learning is a new learning paradigm, the basic idea of which is to use the primal-dual structure between machine learning tasks to obtain effective feedback/regularization, and guide and strengthen the learning process, thus reducing the requirement of large-scale labeled @@ -1635,42 +1927,35 @@ many problems in machine learning, including machine translation, image style conversion, question answering and generation, image classification and generation, text classification and generation, image-to-text, and text-to-image. +

    -











    +

    Distributed machine learning

    -

    Distributed machine learning

    - -

    -Distributed computation will speed up machine learning algorithms, +

    Distributed computation will speed up machine learning algorithms, significantly improve their efficiency, and thus enlarge their application. When distributed meets machine learning, more than just implementing the machine learning algorithms in parallel is required. +

    -











    +

    Meta learning

    -

    Meta learning

    - -

    -Meta learning is an emerging research direction in machine +

    Meta learning is an emerging research direction in machine learning. Roughly speaking, meta learning concerns learning how to learn, and focuses on the understanding and adaptation of the learning itself, instead of just completing a specific learning task. That is, a meta learner needs to be able to evaluate its own learning methods and adjust its own learning methods according to specific learning tasks. +

    -











    +

    The Challenges Facing Machine Learning

    -

    The Challenges Facing Machine Learning

    +

    While there has been much progress in machine learning, there are also challenges.

    -

    -While there has been much progress in machine learning, there are also challenges. - -

    -For example, the mainstream machine learning technologies are +

    For example, the mainstream machine learning technologies are black-box approaches, making us concerned about their potential risks. To tackle this challenge, we may want to make machine learning more explainable and controllable. As another example, the @@ -1685,27 +1970,23 @@ models for data fitting? Although there are many challenges, we are still very optimistic about the future of machine learning. As we look forward to the future, here are what we think the research hotspots in the next ten years will be. +

    -

    -See the article on Discovery of Physics From Data: Universal Laws and Discrepancies +

    See the article on Discovery of Physics From Data: Universal Laws and Discrepancies

    -











    +

    Explainable machine learning

    -

    Explainable machine learning

    - -

    -Machine learning, especially deep learning, evolves rapidly. The +

    Machine learning, especially deep learning, evolves rapidly. The ability gap between machine and human on many complex cognitive tasks becomes narrower and narrower. However, we are still in the very early stage in terms of explaining why those effective models work and how they work. +

    -

    -What is missing: the gap between correlation and causation. Standard Machine Learning is based on what e have called a frequentist approach. +

    What is missing: the gap between correlation and causation. Standard Machine Learning is based on what e have called a frequentist approach.

    -

    -Most +

    Most machine learning techniques, especially the statistical ones, depend highly on correlations in data sets to make predictions and analyses. In contrast, rational humans tend to reply on clear and trustworthy @@ -1713,48 +1994,41 @@ causality relations obtained via logical reasoning on real and clear facts. It is one of the core goals of explainable machine learning to transition from solving problems by data correlation to solving problems by logical reasoning. +

    -

    Bayesian Machine Learning is one of the exciting research directions in this field. -











    +

    Quantum machine learning

    -

    Quantum machine learning

    - -

    -Quantum machine learning is an emerging interdisciplinary research +

    Quantum machine learning is an emerging interdisciplinary research area at the intersection of quantum computing and machine learning. +

    -

    -Quantum computers use effects such as quantum coherence and quantum +

    Quantum computers use effects such as quantum coherence and quantum entanglement to process information, which is fundamentally different from classical computers. Quantum algorithms have surpassed the best classical algorithms in several problems (e.g., searching for an unsorted database, inverting a sparse matrix), which we call quantum acceleration. +

    -

    -When quantum computing meets machine learning, it can be a mutually +

    When quantum computing meets machine learning, it can be a mutually beneficial and reinforcing process, as it allows us to take advantage of quantum computing to improve the performance of classical machine learning algorithms. In addition, we can also use the machine learning algorithms (on classic computers) to analyze and improve quantum computing systems. +

    -

    -Lecture on Quantum ML. +

    Lecture on Quantum ML.

    -

    -Read interview with Maria Schuld on her work on Quantum Machine Learning. See also her recent textbook. +

    Read interview with Maria Schuld on her work on Quantum Machine Learning. See also her recent textbook.

    -











    +

    Quantum machine learning algorithms based on linear algebra

    -

    Quantum machine learning algorithms based on linear algebra

    - -

    -Many quantum machine learning algorithms are based on variants of +

    Many quantum machine learning algorithms are based on variants of quantum algorithms for solving linear equations, which can efficiently solve N-variable linear equations with complexity of O(log2 N) under certain conditions. The quantum matrix inversion algorithm can @@ -1766,28 +2040,24 @@ machine learning algorithms is data input—that is, how to initialize the quantum system with the entire data set. Although efficient data-input algorithms exist for certain situations, how to efficiently input data into a quantum system is as yet unknown for most cases. +

    -











    +

    Quantum reinforcement learning

    -

    Quantum reinforcement learning

    - -

    -In quantum reinforcement learning, a quantum agent interacts with the +

    In quantum reinforcement learning, a quantum agent interacts with the classical environment to obtain rewards from the environment, so as to adjust and improve its behavioral strategies. In some cases, it achieves quantum acceleration by the quantum processing capabilities of the agent or the possibility of exploring the environment through quantum superposition. Such algorithms have been proposed in superconducting circuits and systems of trapped ions. +

    -











    +

    Quantum deep learning

    -

    Quantum deep learning

    - -

    -Dedicated quantum information processors, such as quantum annealers +

    Dedicated quantum information processors, such as quantum annealers and programmable photonic circuits, are well suited for building deep quantum networks. The simplest deep quantum network is the Boltzmann machine. The classical Boltzmann machine consists of bits with tunable @@ -1799,14 +2069,12 @@ correspond to an adjustable Ising model. Then, by initializing the input neurons in the Boltzmann machine to a fixed state and allowing the system to heat up, we can read out the output qubits to get the result. +

    -











    +

    Social machine learning

    -

    Social machine learning

    - -

    -Machine learning aims to imitate how humans +

    Machine learning aims to imitate how humans learn. While we have developed successful machine learning algorithms, until now we have ignored one important fact: humans are social. Each of us is one part of the total society and it is difficult for us to @@ -1814,41 +2082,33 @@ live, learn, and improve ourselves, alone and isolated. Therefore, we should design machines with social properties. Can we let machines evolve by imitating human society so as to achieve more effective, intelligent, interpretable “social machine learning”? +

    -

    -And much more. +

    And much more.

    -











    +

    The last words?

    -

    The last words?

    - -

    -Early computer scientist Alan Kay said, The best way to predict the +

    Early computer scientist Alan Kay said, The best way to predict the future is to create it. Therefore, all machine learning practitioners, whether scholars or engineers, professors or students, need to work together to advance these important research topics. Together, we will not just predict the future, but create it. +

    -











    +

    Best wishes to you all and thanks so much for your heroic efforts this semester

    -

    Best wishes to you all and thanks so much for your heroic efforts this semester

    - -

    -



    - -

    +

    +

    +

    +
    +

    - -
    - © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week48/ipynb/ipynb-week48-src.tar.gz b/doc/pub/week48/ipynb/ipynb-week48-src.tar.gz index 40e3c4820..fde56c917 100644 Binary files a/doc/pub/week48/ipynb/ipynb-week48-src.tar.gz and b/doc/pub/week48/ipynb/ipynb-week48-src.tar.gz differ diff --git a/doc/pub/week48/ipynb/week48.ipynb b/doc/pub/week48/ipynb/week48.ipynb index c3bf31609..2d26b01b4 100644 --- a/doc/pub/week48/ipynb/week48.ipynb +++ b/doc/pub/week48/ipynb/week48.ipynb @@ -2,909 +2,1582 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "c3193a71", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "a0b80e0f", + "metadata": { + "editable": true + }, "source": [ - "\n", "# Week 48: Support Vector Machines and Summary of course\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", + "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway\n", "\n", - "Date: **Nov 29, 2020**\n", + "Date: **Nov 21, 2024**\n", "\n", - "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "Copyright 1999-2024, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "6da3d550", + "metadata": { + "editable": true + }, + "source": [ + "## Overview of week 48" + ] + }, + { + "cell_type": "markdown", + "id": "3de7e991", + "metadata": { + "editable": true + }, + "source": [ + "## Plan for week 47\n", "\n", + "**Lab sessions on Tuesday and Wednesday.**\n", "\n", + " * Work and Discussion of project 3\n", "\n", - "## Overview of week 48\n", + " * Last weekly exercise,\n", "\n", - "* **Thursday**: Support Vector Machines: Kernels, Classification and Regression. [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember26.mp4?vrtx=view-as-webpage).\n", + " \n", "\n", - "* **Friday**: Summary of course with perspectives for future studies. [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember27.mp4?vrtx=view-as-webpage).\n", + "**Plans for the lecture Monday 25 November, with video suggestions etc.**\n", "\n", - "See also Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones) of Hastie et al contains also a good discussion.\n", + "1. Bossting and gradient boosting and ensemble models\n", "\n", + "2. Summary of course\n", "\n", - "## Thursday\n", + "3. Readings and Videos:\n", "\n", - "We finalize our discussion on Support Vector Machines with an emphasis on kernel transformations and applications to regression. The following [video attempts at giving an overview on this part](https://www.youtube.com/watch?v=Toet3EiSFcM&ab_channel=StatQuestwithJoshStarmer). See also the [follow-up video](https://www.youtube.com/watch?v=Qc5IyLW_hns&ab_channel=StatQuestwithJoshStarmer).\n", + "a. These lecture notes at \n", "\n", - "## Friday\n", + "b. See also lecture notes from week 47 at . The lecture on Monday starts with a repetition on AdaBoost before we move over to gradient boosting with examples\n", + "\n", + "\n", "\n", - "Friday's lecture is split in two parts. It starts with a summary of\n", - "what we have done this semester and continues with perspectives for future studies and\n", - "modern research projects in machine learning.\n", + "c. Video on Decision trees \n", "\n", - "## Support Vector Machines, overarching aims\n", + "d. Video on boosting methods \n", "\n", - "As discussed last week, \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", + "e. Video on AdaBoost \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.\n", + "f. Video on Gradient boost, part 1, parts 2-4 follow thereafter \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. I recommend you take a look at the lectures from last week on the binary classification problem.\n", + "g. Decision Trees: Rashcka et al chapter 3 pages 86-98, and chapter 7 on Ensemble methods, Voting and Bagging and Gradient Boosting. See also lecture from STK-IN4300, lecture 7 at ." + ] + }, + { + "cell_type": "markdown", + "id": "bcf392e6", + "metadata": { + "editable": true + }, + "source": [ + "## Boosting, a Bird's Eye View\n", "\n", - "## Kernels and non-linearity\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", - "The cases we studied last week 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", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "3496f6ab", + "metadata": { + "editable": true + }, + "source": [ + "## What is boosting? Additive Modelling/Iterative Fitting\n", "\n", - "If our feature space is not easy to separate, as shown in the figure\n", - "generated by the code below, we can achieve a better separation by introducing a more complex\n", - "basis functions. The ideal would be, as shown by the code example below, to,\n", - "via a specific transformation to obtain a separation between the\n", - "classes that is almost linear. See also Figures 12.2 and 12.3 of [Hastie et al.](https://www.springer.com/gp/book/9780387848570).\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", + "id": "3a5f4cf4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3161dc94", + "metadata": { + "editable": true + }, + "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", - "We can achieve a better separation by introducing more complex\n", - "basis functions. The ideal would be (see Figures 12.2 and 12.3) to, via a specific transformation to \n", - "obtain a separation between the classes which is almost linear. \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", + "id": "88356147", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1d8f6ff1", + "metadata": { + "editable": true + }, + "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", - "The change of basis, from $x\\rightarrow z=\\phi(x)$ leads to the same\n", - "type of equations to be solved, except that we need to introduce, for\n", - "example, a polynomial transformation to a two-dimensional training\n", - "set." + "As another example, consider the cost function we defined for linear regression" + ] + }, + { + "cell_type": "markdown", + "id": "66b214e6", + "metadata": { + "editable": true + }, + "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", + "id": "007ebce9", + "metadata": { + "editable": true + }, + "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", + "id": "818f650f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2a0f1f70", + "metadata": { + "editable": true + }, + "source": [ + "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$." + ] + }, + { + "cell_type": "markdown", + "id": "20fd7a4b", + "metadata": { + "editable": true + }, + "source": [ + "## 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", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "a5253a01", + "metadata": { + "editable": true + }, + "source": [ + "## 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", + "id": "82a331f2", + "metadata": { + "editable": true + }, + "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", + "id": "38f0123c", + "metadata": { + "editable": true + }, + "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", + "id": "8885d64f", + "metadata": { + "editable": true + }, + "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", + "id": "bc3b9f34", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "308960c8", + "metadata": { + "editable": true + }, + "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", + "id": "4e6d45c0", + "metadata": { + "editable": true + }, + "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", + "id": "93f28313", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c95dde03", + "metadata": { + "editable": true + }, + "source": [ + "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have" + ] + }, + { + "cell_type": "markdown", + "id": "01efcbbe", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5049378a", + "metadata": { + "editable": true + }, + "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$." + ] + }, + { + "cell_type": "markdown", + "id": "6994caec", + "metadata": { + "editable": true + }, + "source": [ + "## 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", + "id": "a367fb84", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4b3dccdb", + "metadata": { + "editable": true + }, + "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", + "id": "bdcfb41f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "08ec0a91", + "metadata": { + "editable": true + }, + "source": [ + "will be a function of" + ] + }, + { + "cell_type": "markdown", + "id": "0cf3f4ea", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4b8e7ed6", + "metadata": { + "editable": true + }, + "source": [ + "## Adaptive Boosting, AdaBoost\n", + "\n", + "In our iterative procedure we define thus" + ] + }, + { + "cell_type": "markdown", + "id": "235e8777", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f6f51dc4", + "metadata": { + "editable": true + }, + "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", + "id": "8890839a", + "metadata": { + "editable": true + }, + "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", + "id": "52acdfd0", + "metadata": { + "editable": true + }, + "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", + "id": "9add0067", + "metadata": { + "editable": true + }, + "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", + "id": "a44a0cd1", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$." + ] + }, + { + "cell_type": "markdown", + "id": "3531c7dd", + "metadata": { + "editable": true + }, + "source": [ + "## Building up AdaBoost\n", + "\n", + "First, for any $\\beta > 0$, we optimize $G$ by setting" + ] + }, + { + "cell_type": "markdown", + "id": "633d1c21", + "metadata": { + "editable": true + }, + "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", + "id": "ff836742", + "metadata": { + "editable": true + }, + "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", + "id": "f3f23906", + "metadata": { + "editable": true + }, + "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", + "id": "8b4563bf", + "metadata": { + "editable": true + }, + "source": [ + "which can be rewritten as" + ] + }, + { + "cell_type": "markdown", + "id": "4420620d", + "metadata": { + "editable": true + }, + "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", + "id": "d79ce5d4", + "metadata": { + "editable": true + }, + "source": [ + "which leads to" + ] + }, + { + "cell_type": "markdown", + "id": "6ae1d2b3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "adb45dfe", + "metadata": { + "editable": true + }, + "source": [ + "where we have redefined the error as" + ] + }, + { + "cell_type": "markdown", + "id": "33cf4819", + "metadata": { + "editable": true + }, + "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", + "id": "70d46dfa", + "metadata": { + "editable": true + }, + "source": [ + "which leads to an update of" + ] + }, + { + "cell_type": "markdown", + "id": "0812d0a8", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "783db749", + "metadata": { + "editable": true + }, + "source": [ + "This leads to the new weights" + ] + }, + { + "cell_type": "markdown", + "id": "cc77503c", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a0948190", + "metadata": { + "editable": true + }, + "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", + "id": "842d68bc", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "44c88ed6", + "metadata": { + "editable": true + }, + "source": [ + "where the function $I()$ is one if we misclassify and zero if we classify correctly." + ] + }, + { + "cell_type": "markdown", + "id": "b3a7c4c1", + "metadata": { + "editable": true + }, + "source": [ + "## 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", + "id": "ad288a70", + "metadata": { + "editable": true + }, + "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", + "id": "6f0def3e", + "metadata": { + "editable": true + }, + "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", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "cf8a89b9", + "metadata": { + "editable": true + }, + "source": [ + "## AdaBoost Examples\n", + "\n", + "Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here." ] }, { "cell_type": "code", "execution_count": 1, + "id": "fc01de3a", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ - "%matplotlib inline\n", + "from sklearn.ensemble import AdaBoostClassifier\n", "\n", - "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", + "ada_clf = AdaBoostClassifier(\n", + " DecisionTreeClassifier(max_depth=2), n_estimators=200,\n", + " algorithm=\"SAMME.R\", learning_rate=0.01, random_state=42)\n", + "ada_clf.fit(X_train, y_train)\n", + "y_pred = ada_clf.predict(X_test)\n", + "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", + "plt.show()\n", + "y_probas = ada_clf.predict_proba(X_test)\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": {}, + "id": "269f1edd", + "metadata": { + "editable": true + }, "source": [ - "## The equations\n", - "\n", - "Suppose we define a polynomial transformation of degree two only. We define a vector $\\boldsymbol{x}_i=[x_i,y_i]$ and have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{z}_i^T = \\phi(\\boldsymbol{x}_i)^T =\\left[1, \\sqrt{2}x_i, \\sqrt{2}y_i, 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{z}_i^T\\boldsymbol{w}+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)=[1, \\sqrt{2}x_i, \\sqrt{2}y_i, x_i^2, y_i^2, \\sqrt{2}x_iy_i]\\begin{bmatrix} 1\\\\ \\sqrt{2}x_j \\\\ \\sqrt{2}y_j \\\\ x_j^2\\\\ y_i^2\\\\ \\sqrt{2}x_jy_j \\end{bmatrix}=1+2x_ix_j+2y_iy_j+(x_ix_j)^2+(y_iy_j)^2+2x_ix_jy_iy_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We note that this dot product can be rewritten as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=[1+\\boldsymbol{x}_i^T\\boldsymbol{x}_j]^d,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $d=2$ in our case and $\\boldsymbol{x}_i=[x_i,y_i]$ and $\\boldsymbol{x}_j=[x_j,y_j]$.\n", - "To compute the last equation is however inefficient from a computational stand.\n", - "Instead of computing the last equation for the kernel, we simply compute\n", - "the dot product $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$.\n", - "This leads to the so-called\n", - "kernel trick.\n", - "\n", - "## The problem to solve\n", - "\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{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$ 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", - "## Tailoring the equations to the usage of CVXOPT\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{s.t} \\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 ([Adapted from Geron, chapter 5](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/))" + "## Making an ADAboost code yourself" ] }, { "cell_type": "code", "execution_count": 2, + "id": "bef1d223", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "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", + "class DecisionStump:\n", + " def fit(self, X, y, weights):\n", + " m, n = X.shape\n", + " self.alpha = 0\n", + " self.threshold = None\n", + " self.polarity = 1\n", "\n", + " min_error = float('inf')\n", "\n", - "from sklearn.svm import SVC\n", - "from sklearn import datasets\n", + " for feature in range(n):\n", + " feature_values = np.unique(X[:, feature])\n", "\n", + " for threshold in feature_values:\n", + " for polarity in [1, -1]:\n", + " predictions = np.ones(m)\n", + " predictions[X[:, feature] < threshold] = -1\n", + " predictions *= polarity\n", "\n", + " error = sum(weights[predictions != y])\n", "\n", - "from sklearn.pipeline import Pipeline\n", - "from sklearn.preprocessing import StandardScaler\n", - "from sklearn.svm import LinearSVC\n", + " if error < min_error:\n", + " min_error = error\n", + " self.alpha = 0.5 * np.log((1 - error) / (error + 1e-10))\n", + " self.threshold = threshold\n", + " self.feature_index = feature\n", + " self.polarity = polarity\n", "\n", + " def predict(self, X):\n", + " m = X.shape[0]\n", + " predictions = np.ones(m)\n", + " if self.polarity == 1:\n", + " predictions[X[:, self.feature_index] < self.threshold] = -1\n", + " else:\n", + " predictions[X[:, self.feature_index] >= self.threshold] = -1\n", + " return predictions\n", "\n", - "from sklearn.datasets import make_moons\n", - "X, y = make_moons(n_samples=100, noise=0.15, random_state=42)\n", + "class AdaBoost:\n", + " def fit(self, X, y, n_estimators):\n", + " m = X.shape[0]\n", + " self.alphas = []\n", + " self.models = []\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", + " weights = np.ones(m) / m\n", "\n", - "plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])\n", - "plt.show()\n", + " for _ in range(n_estimators):\n", + " stump = DecisionStump()\n", + " stump.fit(X, y, weights)\n", + " predictions = stump.predict(X)\n", "\n", - "from sklearn.datasets import make_moons\n", - "from sklearn.pipeline import Pipeline\n", - "from sklearn.preprocessing import PolynomialFeatures\n", + " error = sum(weights[predictions != y])\n", + " if error == 0:\n", + " break\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", + " self.models.append(stump)\n", + " self.alphas.append(stump.alpha)\n", "\n", - "polynomial_svm_clf.fit(X, y)\n", + " weights *= np.exp(-stump.alpha * y * predictions)\n", + " weights /= np.sum(weights)\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", + " def predict(self, X):\n", + " final_predictions = np.zeros(X.shape[0])\n", + " for alpha, model in zip(self.alphas, self.models):\n", + " final_predictions += alpha * model.predict(X)\n", + " return np.sign(final_predictions)\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", + "# Example dataset (X, y)\n", + "X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])\n", + "y = np.array([-1, -1, -1, -1, 1, 1, 1, 1, 1, 1]) # Labels must be -1 or 1\n", "\n", - "plt.show()\n", + "# Train AdaBoost\n", + "ada = AdaBoost()\n", + "ada.fit(X, y, n_estimators=10)\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()" + "# Predictions\n", + "predictions = ada.predict(X)\n", + "print(\"Predictions:\", predictions)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9338a775", + "metadata": { + "editable": true + }, "source": [ - "## Mathematical optimization of convex functions\n", + "## Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent\n", "\n", - "A mathematical (quadratic) optimization problem, or just optimization problem, has the form" + "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." ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6fc86b75", + "metadata": { + "editable": true + }, + "source": [ + "## 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", + "id": "f4fb65a8", + "metadata": { + "editable": true + }, "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", + "(\\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": {}, + "id": "46ea5f88", + "metadata": { + "editable": true + }, "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", + "We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as" + ] + }, + { + "cell_type": "markdown", + "id": "0fa310b0", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f_M(x) = \\sum_{m=0}^M h_m(x).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3638bac4", + "metadata": { + "editable": true + }, + "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", + "id": "40c8295f", + "metadata": { + "editable": true + }, + "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", + "id": "116dbbbd", + "metadata": { + "editable": true + }, + "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", - "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", + "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", + "id": "1873e19d", + "metadata": { + "editable": true + }, + "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", + "id": "a488e80c", + "metadata": { + "editable": true + }, + "source": [ + "## Steepest Descent Example\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", + "Optimizing with respect to $\\rho$ we obtain (taking the derivative) that $\\rho_1 = -1/2$. We have then that" + ] + }, + { + "cell_type": "markdown", + "id": "754c7e53", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "040f985c", + "metadata": { + "editable": true + }, + "source": [ + "We can then proceed and compute" + ] + }, + { + "cell_type": "markdown", + "id": "2095bf76", + "metadata": { + "editable": true + }, + "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", + "id": "eb32c8f7", + "metadata": { + "editable": true + }, + "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**." + ] + }, + { + "cell_type": "markdown", + "id": "1dffe706", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient Boosting, algorithm\n", "\n", + "Steepest descent is however not much used, since it only optimizes $f$ at a fixed set of $n$ points,\n", + "so we do not learn a function that can generalize. However, we can modify the algorithm by\n", + "fitting a weak learner to approximate the negative gradient signal. \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", + "id": "a773c034", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c5309d69", + "metadata": { + "editable": true + }, + "source": [ + "The way we proceed in an iterative fashion is to\n", + "1. Initialize our estimate $f_0(x)$.\n", "\n", - "## How do we solve these problems?\n", + "2. For $m=1:M$, we\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 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", + "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", - "The functions we need are contained in the quadratic programming package **CVXOPT** and we need to import it together with **numpy** as" + "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)+h_m(u_m,x)$;\n", + "\n", + "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$." + ] + }, + { + "cell_type": "markdown", + "id": "ce123557", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient Boosting, Examples of Regression" ] }, { "cell_type": "code", "execution_count": 3, + "id": "83f66b3c", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ - "import numpy\n", - "import cvxopt" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This will make our life much easier. You don't need to write your own optimizer.\n", + "%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.ensemble import GradientBoostingRegressor\n", + "import scikitplot as skplt\n", + "from sklearn.metrics import mean_squared_error\n", "\n", - "## A simple example\n", + "n = 100\n", + "maxdegree = 6\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{s.t.} \\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": [ - "**Note**: we use **s.t.** for subject to. \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", - "Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem" + "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", + "\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,y_train)\n", + " y_pred = model.predict(X_test)\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": {}, + "id": "1a395403", + "metadata": { + "editable": true + }, "source": [ - "$$\n", - "\\begin{align*}\n", - " &\\mathrm{min}_{x}\\hspace{0.2cm} \\frac{1}{2}x^2+5x+3y \\\\ \\nonumber\n", - " &\\mathrm{s.t.} \\\\ \\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}5\\\\ 3 \\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" + "## Gradient Boosting, Classification Example" ] }, { "cell_type": "code", "execution_count": 4, + "id": "09b1de9c", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "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']" + "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 Gradient boosting 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": {}, + "id": "ef37fb74", + "metadata": { + "editable": true + }, "source": [ - "## Back to the more realistic cases\n", + "## XGBoost: Extreme Gradient Boosting\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" + "[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!!!" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e35c17fd", + "metadata": { + "editable": true + }, "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", - "$$" + "## Regression Case" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "c2ae030f", + "metadata": { + "collapsed": false, + "editable": true + }, + "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", + "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", + "\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,y_train)\n", + " y_pred = model.predict(X_test)\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": {}, + "id": "9fde7dfa", + "metadata": { + "editable": true + }, "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", + "## 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": 6, + "id": "8492209d", + "metadata": { + "collapsed": false, + "editable": true + }, + "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 Gradient Boosting 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", - "## Setting up the matrices and the problem\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", - "We have the general problem" + "xgb.plot_importance(xg_clf)\n", + "plt.rcParams['figure.figsize'] = [5, 5]\n", + "save_fig(\"xgparams\")\n", + "plt.show()" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6d840ba2", + "metadata": { + "editable": true + }, "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{s.t.} \\hspace{0.2cm} \\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h} \\wedge \\boldsymbol{A}\\boldsymbol{\\lambda}=f.\n", - "\\end{align*}\n", - "$$" + "## Gradient boosting, making our own code for a regression case" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "736c2963", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "class DecisionTreeRegressor:\n", + " def __init__(self, max_depth=3):\n", + " self.max_depth = max_depth\n", + " self.tree = None\n", + " def fit(self, X, y):\n", + " self.tree = self._grow_tree(X, y)\n", + " def _grow_tree(self, X, y, depth=0):\n", + " n_samples, n_features = X.shape\n", + " if depth < self.max_depth:\n", + " best_feature, best_threshold = self._best_split(X, y)\n", + " if best_feature is not None:\n", + " left_indices = X[:, best_feature] < best_threshold\n", + " right_indices = X[:, best_feature] >= best_threshold\n", + " left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1)\n", + " right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1)\n", + " return (best_feature, best_threshold, left_child, right_child)\n", + " return np.mean(y)\n", + " def _best_split(self, X, y):\n", + " best_mse = float('inf')\n", + " best_feature, best_threshold = None, None\n", + " n_samples, n_features = X.shape\n", + " \n", + " for feature in range(n_features):\n", + " thresholds = np.unique(X[:, feature])\n", + " for threshold in thresholds:\n", + " left_indices = X[:, feature] < threshold\n", + " right_indices = X[:, feature] >= threshold\n", + " if len(y[left_indices]) > 0 and len(y[right_indices]) > 0:\n", + " left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2)\n", + " right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2)\n", + " mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples\n", + " \n", + " if mse < best_mse:\n", + " best_mse = mse\n", + " best_feature = feature\n", + " best_threshold = threshold\n", + " return best_feature, best_threshold\n", + " def predict(self, X):\n", + " return np.array([self._predict_sample(sample, self.tree) for sample in X])\n", + " def _predict_sample(self, sample, node):\n", + " if isinstance(node, tuple):\n", + " feature, threshold, left_child, right_child = node\n", + " if sample[feature] < threshold:\n", + " return self._predict_sample(sample, left_child)\n", + " else:\n", + " return self._predict_sample(sample, right_child)\n", + " return node\n", + "class GradientBoostingRegressor:\n", + " def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3):\n", + " self.n_estimators = n_estimators\n", + " self.learning_rate = learning_rate\n", + " self.max_depth = max_depth\n", + " self.models = []\n", + " def fit(self, X, y):\n", + " y_pred = np.zeros(y.shape)\n", + " for _ in range(self.n_estimators):\n", + " residuals = y - y_pred\n", + " model = DecisionTreeRegressor(max_depth=self.max_depth)\n", + " model.fit(X, residuals)\n", + " y_pred += self.learning_rate * model.predict(X)\n", + " self.models.append(model)\n", + " def predict(self, X):\n", + " y_pred = np.zeros(X.shape[0])\n", + " for model in self.models:\n", + " y_pred += self.learning_rate * model.predict(X)\n", + " return y_pred\n", + "# Example usage\n", + "if __name__ == \"__main__\":\n", + " # Sample data\n", + " X = np.array([[1], [2], [3], [4], [5]])\n", + " y = np.array([1.5, 1.7, 3.5, 3.7, 5.0])\n", + " model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2)\n", + " model.fit(X, y)\n", + " predictions = model.predict(X)\n", + " print(\"Predictions:\", predictions)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "a016e0f1", + "metadata": { + "editable": true + }, "source": [ - "1. With a given kernel we can thus define the matrix $\\boldsymbol{P}$.\n", - "\n", - "2. 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.\n", - "\n", - "3. The vector $\\boldsymbol{q}$ has all elements equal to $-1$.\n", - "\n", - "4. The constraint $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$ leads to $f=0$ and $\\boldsymbol{A}=\\boldsymbol{y}$.\n", - "\n", - "5. To set up the matrix $\\boldsymbol{G}$ we 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}$.\n", - "\n", - "## Setting up $\\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h}$\n", - "\n", - "We have two constraints, $0\\le \\lambda_i$ and $\\lambda_i \\le C$. To do this we multiply the ones with the constraint\n", - "$\\ge$ with $-1$ in order to get $\\le$. It means that the problem $\\boldsymbol{G}\\boldsymbol{\\lambda} \\preceq \\boldsymbol{h}$\n", - "can be written as" + "## Summary of course" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "db7fd202", + "metadata": { + "editable": true + }, "source": [ - "$$\n", - "\\begin{bmatrix} -1& 0 & 0 & \\dots & 0 \\\\\n", - "0& -1 & 0 & \\dots & 0 \\\\\n", - "0& 0 & -1 & \\dots & 0 \\\\\n", - "\\dots& \\dots & \\dots & \\dots & \\dots \\\\\n", - "0& 0 & 0 & \\dots & -1 \\\\\n", - "1 & 0 & 0 & \\dots & 0 \\\\\n", - "0& 1 & 0 & \\dots & 0 \\\\\n", - "0& 0 & 1 & \\dots & 0 \\\\\n", - "\\dots& \\dots & \\dots & \\dots & \\dots \\\\\n", - "0& 0 & 0 & \\dots & 1 \\\\\n", - "\\end{bmatrix}\n", - "\\begin{bmatrix} \\lambda_1 \\\\\n", - "\\lambda_2 \\\\\n", - "\\lambda_3 \\\\\n", - "\\dots \\\\\n", - "\\lambda_n \\\\\n", - "\\end{bmatrix} \\preceq \n", - "\\begin{bmatrix} 0 \\\\\n", - "0 \\\\\n", - "0 \\\\\n", - "\\dots \\\\\n", - "0 \\\\\n", - "C \\\\\n", - "C \\\\\n", - "C \\\\\n", - "\\dots \\\\\n", - "C \\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And then we are ready to go.\n", - "\n", - "## SVMs and Regression and multiclass classification\n", - "\n", - "More text will be added here. See also [Hastie et al.](https://www.springer.com/gp/book/9780387848570) section 12.3.\n", - "\n", - "## Summary of course\n", - "\n", "## What? Me worry? No final exam in this course!\n", "\n", "\n", "\n", - "

    \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "

    Figure 1:

    \n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "ff2eea1f", + "metadata": { + "editable": true + }, + "source": [ "## Topics we have covered this year\n", "\n", "The course has two central parts\n", "\n", "1. Statistical analysis and optimization of data\n", "\n", - "2. Machine learning\n", - "\n", + "2. Machine learning" + ] + }, + { + "cell_type": "markdown", + "id": "afa4b12f", + "metadata": { + "editable": true + }, + "source": [ "## Statistical analysis and optimization of data\n", "\n", "The following topics have been discussed:\n", @@ -920,8 +1593,16 @@ "\n", "6. Practical optimization using Singular-value decomposition and least squares for parameterizing data.\n", "\n", - "7. Principal Component Analysis to reduce the number of features.\n", - "\n", + "7. Principal Component Analysis to reduce the number of features." + ] + }, + { + "cell_type": "markdown", + "id": "29f93398", + "metadata": { + "editable": true + }, + "source": [ "## Machine learning\n", "\n", "The following topics will be covered\n", @@ -935,7 +1616,6 @@ "\n", "d. Logistic regression\n", "\n", - "\n", "5. Neural networks and deep learning:\n", "\n", "a. Feed Forward Neural Networks\n", @@ -944,7 +1624,6 @@ "\n", "c. Recurrent Neural Networks\n", "\n", - "\n", "4. Decisions trees and ensemble methods:\n", "\n", "a. Decision trees\n", @@ -955,16 +1634,22 @@ "\n", "d. Boosting and gradient boosting\n", "\n", - "\n", "5. Support vector machines\n", "\n", "a. Binary classification and multiclass classification\n", "\n", "b. Kernel methods\n", "\n", - "c. Regression\n", - "\n", - "\n", + "c. Regression" + ] + }, + { + "cell_type": "markdown", + "id": "3eb0cf47", + "metadata": { + "editable": true + }, + "source": [ "## Learning outcomes and overarching aims of this course\n", "\n", "The course introduces a variety of central algorithms and methods\n", @@ -991,8 +1676,16 @@ "\n", "* Have an understanding of central algorithms used in data analysis and machine learning;\n", "\n", - "* Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++.\n", - "\n", + "* Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++." + ] + }, + { + "cell_type": "markdown", + "id": "0e7a583d", + "metadata": { + "editable": true + }, + "source": [ "## Perspective on Machine Learning\n", "\n", "1. Rapidly emerging application area\n", @@ -1006,9 +1699,16 @@ "Huge amounts of data sets require automation, classical analysis tools often inadequate. \n", "High energy physics hit this wall in the 90’s.\n", "In 2009 single top quark production was determined via [Boosted decision trees, Bayesian\n", - "Neural Networks, etc.](https://arxiv.org/pdf/0903.0850.pdf)\n", - "\n", - "\n", + "Neural Networks, etc.](https://arxiv.org/pdf/0903.0850.pdf)" + ] + }, + { + "cell_type": "markdown", + "id": "ef032896", + "metadata": { + "editable": true + }, + "source": [ "## Machine Learning Research\n", "\n", "Where to find recent results:\n", @@ -1022,8 +1722,16 @@ "\n", "5. [Journal of Machine Learning Research](http://www.jmlr.org/papers/v19/) \n", "\n", - "6. [Follow ML on ArXiv](https://arxiv.org/list/cs.LG/recent)\n", - "\n", + "6. [Follow ML on ArXiv](https://arxiv.org/list/cs.LG/recent)" + ] + }, + { + "cell_type": "markdown", + "id": "d8a99fa4", + "metadata": { + "editable": true + }, + "source": [ "## Starting your Machine Learning Project\n", "\n", "1. Identify problem type: classification, regression\n", @@ -1034,16 +1742,32 @@ "\n", "4. Consider your data carefully again! Think of data representation more carefully.\n", "\n", - "5. Based on your results, feedback loop to earliest possible point\n", - "\n", + "5. Based on your results, feedback loop to earliest possible point" + ] + }, + { + "cell_type": "markdown", + "id": "44bf42ac", + "metadata": { + "editable": true + }, + "source": [ "## Choose a Model and Algorithm\n", "\n", "1. Supervised?\n", "\n", "2. Start with the simplest model that fits your problem\n", "\n", - "3. Start with minimal processing of data\n", - "\n", + "3. Start with minimal processing of data" + ] + }, + { + "cell_type": "markdown", + "id": "3bd98dfb", + "metadata": { + "editable": true + }, + "source": [ "## Preparing Your Data\n", "\n", "1. Shuffle your data\n", @@ -1052,21 +1776,26 @@ "\n", " * Why?\n", "\n", - "\n", "3. Normalize the variance\n", "\n", " * Why?\n", "\n", - "\n", "4. **Whitening**\n", "\n", " * Decorrelates data\n", "\n", " * Can be hit or miss\n", "\n", - "\n", - "5. When to do train/test split?\n", - "\n", + "5. When to do train/test split?" + ] + }, + { + "cell_type": "markdown", + "id": "6ecf1ff7", + "metadata": { + "editable": true + }, + "source": [ "## Which Activation and Weights to Choose in Neural Networks\n", "\n", "1. RELU? ELU?\n", @@ -1077,18 +1806,23 @@ "\n", " * Terrible idea\n", "\n", - "\n", "4. Set all weights to random values?\n", "\n", - " * Small random values\n", - "\n", - "\n", + " * Small random values" + ] + }, + { + "cell_type": "markdown", + "id": "d872afb1", + "metadata": { + "editable": true + }, + "source": [ "## Optimization Methods and Hyperparameters\n", "1. Stochastic gradient descent\n", "\n", "a. Stochastic gradient descent + momentum\n", "\n", - "\n", "2. State-of-the-art approaches:\n", "\n", " * RMSProp\n", @@ -1097,12 +1831,18 @@ "\n", " * and more\n", "\n", - "\n", "Which regularization and hyperparameters? $L_1$ or $L_2$, soft\n", "classifiers, depths of trees and many other. Need to explore a large\n", - "set of hyperparameters and regularization methods.\n", - "\n", - "\n", + "set of hyperparameters and regularization methods." + ] + }, + { + "cell_type": "markdown", + "id": "f1c129da", + "metadata": { + "editable": true + }, + "source": [ "## Resampling\n", "\n", "When do we resample?\n", @@ -1111,8 +1851,16 @@ "\n", "2. [Cross-validation](https://www.youtube.com/watch?v=fSytzGwwBVw&ab_channel=StatQuestwithJoshStarmer)\n", "\n", - "3. Jackknife and many other\n", - "\n", + "3. Jackknife and many other" + ] + }, + { + "cell_type": "markdown", + "id": "d0f27c93", + "metadata": { + "editable": true + }, + "source": [ "## Other courses on Data science and Machine Learning at UiO\n", "\n", "The link here gives an excellent overview of courses on Machine learning at UiO.\n", @@ -1131,14 +1879,30 @@ "\n", "7. [IN5400/INF5860 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/). An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too.\n", "\n", - "8. [TEK5040 – Dyp læring for autonome systemer](https://www.uio.no/studier/emner/matnat/its/TEK5040/). The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments.\n", - "\n", + "8. [TEK5040 – Dyp læring for autonome systemer](https://www.uio.no/studier/emner/matnat/its/TEK5040/). The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments." + ] + }, + { + "cell_type": "markdown", + "id": "e28e0a40", + "metadata": { + "editable": true + }, + "source": [ "## Additional courses of interest\n", "\n", "1. [STK4051 Computational Statistics](https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html)\n", "\n", - "2. [STK4021 Applied Bayesian Analysis and Numerical Methods](https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html)\n", - "\n", + "2. [STK4021 Applied Bayesian Analysis and Numerical Methods](https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html)" + ] + }, + { + "cell_type": "markdown", + "id": "3fd96a2c", + "metadata": { + "editable": true + }, + "source": [ "## What's the future like?\n", "\n", "Based on multi-layer nonlinear neural networks, deep learning can\n", @@ -1155,8 +1919,16 @@ "\n", "2. Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing;\n", "\n", - "3. Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning.\n", - "\n", + "3. Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning." + ] + }, + { + "cell_type": "markdown", + "id": "bb05416d", + "metadata": { + "editable": true + }, + "source": [ "## Types of Machine Learning, a repetition\n", "\n", "The approaches to machine learning are many, but are often split into two main categories. \n", @@ -1176,11 +1948,16 @@ "\n", " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n", "\n", - " * Other unsupervised learning algortihms like **Boltzmann machines**\n", - "\n", - "\n", - "\n", - "\n", + " * Other unsupervised learning algortihms like **Boltzmann machines**" + ] + }, + { + "cell_type": "markdown", + "id": "21d8fbea", + "metadata": { + "editable": true + }, + "source": [ "## Why Boltzmann machines?\n", "\n", "What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately. \n", @@ -1188,9 +1965,16 @@ "\n", "The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images. \n", "\n", - "Furthermore, they have been used to solve complicated [quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002). \n", - "\n", - "\n", + "Furthermore, they have been used to solve complicated [quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002)." + ] + }, + { + "cell_type": "markdown", + "id": "7107efa8", + "metadata": { + "editable": true + }, + "source": [ "## Boltzmann Machines\n", "\n", "Why use a generative model rather than the more well known discriminative deep neural networks (DNN)? \n", @@ -1203,9 +1987,16 @@ "\n", "b. Generate a sample of an ordered or disordered phase, having been given samples of such phases.\n", "\n", - "c. Model the trial function for [Monte Carlo calculations](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002).\n", - "\n", - "\n", + "c. Model the trial function for [Monte Carlo calculations](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002)." + ] + }, + { + "cell_type": "markdown", + "id": "74dcfbe6", + "metadata": { + "editable": true + }, + "source": [ "## Some similarities and differences from DNNs\n", "\n", "1. Both use gradient-descent based learning procedures for minimizing cost functions\n", @@ -1214,67 +2005,89 @@ "\n", "3. DNNs often have several hidden layers. A restricted Boltzmann machine has only one hidden layer, however several RBMs can be stacked to make up Deep Belief Networks, of which they constitute the building blocks.\n", "\n", - "History: The RBM was developed by amongst others [Geoffrey Hinton](https://en.wikipedia.org/wiki/Geoffrey_Hinton), called by some the \"Godfather of Deep Learning\", working with the University of Toronto and Google.\n", - "\n", - "\n", + "History: The RBM was developed by amongst others [Geoffrey Hinton](https://en.wikipedia.org/wiki/Geoffrey_Hinton), called by some the \"Godfather of Deep Learning\", working with the University of Toronto and Google." + ] + }, + { + "cell_type": "markdown", + "id": "75c514e3", + "metadata": { + "editable": true + }, + "source": [ "## Boltzmann machines (BM)\n", "\n", "A BM is what we would call an undirected probabilistic graphical model\n", "with stochastic continuous or discrete units.\n", "\n", - "\n", "It is interpreted as a stochastic recurrent neural network where the\n", "state of each unit(neurons/nodes) depends on the units it is connected\n", "to. The weights in the network represent thus the strength of the\n", "interaction between various units/nodes.\n", "\n", - "\n", "It turns into a Hopfield network if we choose deterministic rather\n", "than stochastic units. In contrast to a Hopfield network, a BM is a\n", "so-called generative model. It allows us to generate new samples from\n", - "the learned distribution.\n", - "\n", - "\n", - "\n", + "the learned distribution." + ] + }, + { + "cell_type": "markdown", + "id": "1e734682", + "metadata": { + "editable": true + }, + "source": [ "## A standard BM setup\n", "\n", "A standard BM network is divided into a set of observable and visible units $\\hat{x}$ and a set of unknown hidden units/nodes $\\hat{h}$.\n", "\n", - "\n", - "\n", "Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to $1$.\n", "\n", - "\n", - "\n", "BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning\n", "\n", - "\n", - "\n", "However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS.\n", - "Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below.\n", - "\n", - "\n", - "\n", + "Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below." + ] + }, + { + "cell_type": "markdown", + "id": "c89378ce", + "metadata": { + "editable": true + }, + "source": [ "## The structure of the RBM network\n", "\n", "\n", "\n", "\n", - "

    \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "

    Figure 1:

    \n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "e96b75e9", + "metadata": { + "editable": true + }, + "source": [ "## The network\n", "\n", "**The network layers**:\n", "1. A function $\\mathbf{x}$ that represents the visible layer, a vector of $M$ elements (nodes). This layer represents both what the RBM might be given as training input, and what we want it to be able to reconstruct. This might for example be given by the pixels of an image or coefficients representing speech, or the coordinates of a quantum mechanical state function.\n", "\n", - "2. The function $\\mathbf{h}$ represents the hidden, or latent, layer. A vector of $N$ elements (nodes). Also called \"feature detectors\".\n", - "\n", + "2. The function $\\mathbf{h}$ represents the hidden, or latent, layer. A vector of $N$ elements (nodes). Also called \"feature detectors\"." + ] + }, + { + "cell_type": "markdown", + "id": "29c228a3", + "metadata": { + "editable": true + }, + "source": [ "## Goals\n", "\n", "The goal of the hidden layer is to increase the model's expressive\n", @@ -1289,8 +2102,16 @@ "\n", "2. $\\mathbf{b}$ represents the hidden bias, a vector of same lenght as $\\mathbf{h}$.\n", "\n", - "3. $W$ represents the interaction weights, a matrix of size $M\\times N$.\n", - "\n", + "3. $W$ represents the interaction weights, a matrix of size $M\\times N$." + ] + }, + { + "cell_type": "markdown", + "id": "a9297455", + "metadata": { + "editable": true + }, + "source": [ "## Joint distribution\n", "\n", "The restricted Boltzmann machine is described by a Boltzmann distribution" @@ -1298,7 +2119,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b6d45ca8", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1313,14 +2137,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a794db10", + "metadata": { + "editable": true + }, "source": [ "where $Z$ is the normalization constant or partition function, defined as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "5508a27c", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1335,13 +2165,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "074eda44", + "metadata": { + "editable": true + }, + "source": [ + "It is common to ignore $T_0$ by setting it to one." + ] + }, + { + "cell_type": "markdown", + "id": "ee390a08", + "metadata": { + "editable": true + }, "source": [ - "It is common to ignore $T_0$ by setting it to one. \n", - "\n", - "\n", - "\n", - "\n", "## Network Elements, the energy function\n", "\n", "The function $E(\\mathbf{x},\\mathbf{h})$ gives the **energy** of a\n", @@ -1356,7 +2194,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4f3aa1f0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "E(\\hat{x},\\hat{h}) = -\\sum_{ia}^{NA}b_i^a \\alpha_i^a(x_i)-\\sum_{jd}^{MD}c_j^d \\beta_j^d(h_j)-\\sum_{ijad}^{NAMD}b_i^a \\alpha_i^a(x_i)c_j^d \\beta_j^d(h_j)w_{ij}^{ad}.\n", @@ -1365,26 +2206,39 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "62947b2d", + "metadata": { + "editable": true + }, "source": [ "Here $\\beta_j^d(h_j)$ and $\\alpha_i^a(x_j)$ are so-called transfer functions that map a given input value to a desired feature value. The labels $a$ and $d$ denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. **Note** that there is no connection between nodes in a layer.\n", "\n", "The quantities $b$ and $c$ can be interpreted as the visible and hidden biases, respectively.\n", "\n", - "The connection between the nodes in the two layers is given by the weights $w_{ij}$. \n", - "\n", + "The connection between the nodes in the two layers is given by the weights $w_{ij}$." + ] + }, + { + "cell_type": "markdown", + "id": "501d4d2c", + "metadata": { + "editable": true + }, + "source": [ "## Defining different types of RBMs\n", "There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function $E(\\mathbf{x},\\mathbf{h})$. \n", "\n", "**Binary-Binary RBM:**\n", "\n", - "\n", "RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows:" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "a15140cf", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1399,20 +2253,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "26cdb304", + "metadata": { + "editable": true + }, "source": [ "where the binary values taken on by the nodes are most commonly 0 and 1.\n", "\n", - "\n", "**Gaussian-Binary RBM:**\n", "\n", - "\n", "Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary:" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "3bd28b90", + "metadata": { + "editable": true + }, "source": [ "\n", "
    \n", @@ -1427,7 +2285,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9ddc6c22", + "metadata": { + "editable": true + }, "source": [ "## More about RBMs\n", "1. Useful when we model continuous data (i.e., we wish $\\mathbf{x}$ to be continuous)\n", @@ -1443,9 +2304,16 @@ "\n", "4. Rectified linear units\n", "\n", - "To read more, see [Lectures on Boltzmann machines in Physics](https://github.com/CompPhysics/ComputationalPhysics2/blob/gh-pages/doc/pub/notebook2/ipynb/notebook2.ipynb).\n", - "\n", - "\n", + "To read more, see [Lectures on Boltzmann machines in Physics](https://github.com/CompPhysics/ComputationalPhysics2/blob/gh-pages/doc/pub/notebook2/ipynb/notebook2.ipynb)." + ] + }, + { + "cell_type": "markdown", + "id": "bf03ef62", + "metadata": { + "editable": true + }, + "source": [ "## Autoencoders: Overarching view\n", "\n", "Autoencoders are artificial neural networks capable of learning\n", @@ -1474,8 +2342,16 @@ "\n", "[Video on autoencoders](https://www.coursera.org/lecture/building-deep-learning-models-with-tensorflow/autoencoders-1U4L3)\n", "\n", - "See also A. Geron's textbook, chapter 15.\n", - "\n", + "See also A. Geron's textbook, chapter 15." + ] + }, + { + "cell_type": "markdown", + "id": "f1ac866c", + "metadata": { + "editable": true + }, + "source": [ "## Bayesian Machine Learning\n", "\n", "This is an important topic if we aim at extracting a probability\n", @@ -1489,8 +2365,16 @@ "\n", "[Video on Bayesian deep learning](https://www.youtube.com/watch?v=E1qhGw8QxqY&ab_channel=AndrewGordonWilson)\n", "\n", - "See also the [slides here](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Articles/lec03.pdf).\n", - "\n", + "See also the [slides here](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Articles/lec03.pdf)." + ] + }, + { + "cell_type": "markdown", + "id": "72efdf13", + "metadata": { + "editable": true + }, + "source": [ "## Reinforcement Learning\n", "\n", "Reinforcement Learning (RL) is one of the most exciting fields of\n", @@ -1517,8 +2401,16 @@ "\n", "[Lecture on Reinforcement Learning](https://www.youtube.com/watch?v=FgzM3zpZ55o&ab_channel=stanfordonline).\n", "\n", - "See also A. Geron's textbook, chapter 16.\n", - "\n", + "See also A. Geron's textbook, chapter 16." + ] + }, + { + "cell_type": "markdown", + "id": "b6c3dab1", + "metadata": { + "editable": true + }, + "source": [ "## Transfer learning\n", "\n", "The goal of transfer learning is to transfer the model or knowledge\n", @@ -1530,8 +2422,16 @@ "for us to better solve the target task. Transfer learning is a hot\n", "research topic in recent years, with many problems still waiting to be studied.\n", "\n", - "[Lecture on transfer learning](https://www.ias.edu/video/machinelearning/2020/0331-SamoryKpotufe).\n", - "\n", + "[Lecture on transfer learning](https://www.ias.edu/video/machinelearning/2020/0331-SamoryKpotufe)." + ] + }, + { + "cell_type": "markdown", + "id": "14b0cd78", + "metadata": { + "editable": true + }, + "source": [ "## Adversarial learning\n", "\n", "The conventional deep generative model has a potential problem: the\n", @@ -1544,8 +2444,16 @@ "technologies, generative adversarial networks (GAN), has already been\n", "successfully applied to image, speech, and text.\n", "\n", - "[Lecture on adversial learning](https://www.youtube.com/watch?v=CIfsB_EYsVI&ab_channel=StanfordUniversitySchoolofEngineering).\n", - "\n", + "[Lecture on adversial learning](https://www.youtube.com/watch?v=CIfsB_EYsVI&ab_channel=StanfordUniversitySchoolofEngineering)." + ] + }, + { + "cell_type": "markdown", + "id": "2082df21", + "metadata": { + "editable": true + }, + "source": [ "## Dual learning\n", "\n", "Dual learning is a new learning paradigm, the basic idea of which is\n", @@ -1556,16 +2464,31 @@ "many problems in machine learning, including machine translation,\n", "image style conversion, question answering and generation, image\n", "classification and generation, text classification and generation,\n", - "image-to-text, and text-to-image.\n", - "\n", + "image-to-text, and text-to-image." + ] + }, + { + "cell_type": "markdown", + "id": "0191be7d", + "metadata": { + "editable": true + }, + "source": [ "## Distributed machine learning\n", "\n", "Distributed computation will speed up machine learning algorithms,\n", "significantly improve their efficiency, and thus enlarge their\n", "application. When distributed meets machine learning, more than just\n", - "implementing the machine learning algorithms in parallel is required.\n", - "\n", - "\n", + "implementing the machine learning algorithms in parallel is required." + ] + }, + { + "cell_type": "markdown", + "id": "57579d7b", + "metadata": { + "editable": true + }, + "source": [ "## Meta learning\n", "\n", "Meta learning is an emerging research direction in machine\n", @@ -1574,8 +2497,16 @@ "itself, instead of just completing a specific learning task. That is,\n", "a meta learner needs to be able to evaluate its own learning methods\n", "and adjust its own learning methods according to specific learning\n", - "tasks.\n", - "\n", + "tasks." + ] + }, + { + "cell_type": "markdown", + "id": "5ee1418b", + "metadata": { + "editable": true + }, + "source": [ "## The Challenges Facing Machine Learning\n", "\n", "While there has been much progress in machine learning, there are also challenges.\n", @@ -1596,8 +2527,16 @@ "forward to the future, here are what we think the research hotspots in\n", "the next ten years will be.\n", "\n", - "See the article on [Discovery of Physics From Data: Universal Laws and Discrepancies](https://www.frontiersin.org/articles/10.3389/frai.2020.00025/full)\n", - "\n", + "See the article on [Discovery of Physics From Data: Universal Laws and Discrepancies](https://www.frontiersin.org/articles/10.3389/frai.2020.00025/full)" + ] + }, + { + "cell_type": "markdown", + "id": "147876af", + "metadata": { + "editable": true + }, + "source": [ "## Explainable machine learning\n", "\n", "Machine learning, especially deep learning, evolves rapidly. The\n", @@ -1617,8 +2556,16 @@ "transition from solving problems by data correlation to solving\n", "problems by logical reasoning.\n", "\n", - "**Bayesian Machine Learning is one of the exciting research directions in this field**.\n", - "\n", + "**Bayesian Machine Learning is one of the exciting research directions in this field**." + ] + }, + { + "cell_type": "markdown", + "id": "8c4fca27", + "metadata": { + "editable": true + }, + "source": [ "## Quantum machine learning\n", "\n", "Quantum machine learning is an emerging interdisciplinary research\n", @@ -1640,10 +2587,16 @@ "\n", "[Lecture on Quantum ML](https://www.youtube.com/watch?v=Xh9pUu3-WxM&ab_channel=InstituteforPure%26AppliedMathematics%28IPAM%29).\n", "\n", - "\n", - "[Read interview with Maria Schuld on her work on Quantum Machine Learning](https://physics.aps.org/articles/v13/179?utm_campaign=weekly&utm_medium=email&utm_source=emailalert). See also [her recent textbook](https://www.springer.com/gp/book/9783319964232). \n", - "\n", - "\n", + "[Read interview with Maria Schuld on her work on Quantum Machine Learning](https://physics.aps.org/articles/v13/179?utm_campaign=weekly&utm_medium=email&utm_source=emailalert). See also [her recent textbook](https://www.springer.com/gp/book/9783319964232)." + ] + }, + { + "cell_type": "markdown", + "id": "ab24b71c", + "metadata": { + "editable": true + }, + "source": [ "## Quantum machine learning algorithms based on linear algebra\n", "\n", "Many quantum machine learning algorithms are based on variants of\n", @@ -1657,8 +2610,16 @@ "machine learning algorithms is data input—that is, how to initialize\n", "the quantum system with the entire data set. Although efficient\n", "data-input algorithms exist for certain situations, how to efficiently\n", - "input data into a quantum system is as yet unknown for most cases.\n", - "\n", + "input data into a quantum system is as yet unknown for most cases." + ] + }, + { + "cell_type": "markdown", + "id": "38ce95dc", + "metadata": { + "editable": true + }, + "source": [ "## Quantum reinforcement learning\n", "\n", "In quantum reinforcement learning, a quantum agent interacts with the\n", @@ -1667,8 +2628,16 @@ "achieves quantum acceleration by the quantum processing capabilities\n", "of the agent or the possibility of exploring the environment through\n", "quantum superposition. Such algorithms have been proposed in\n", - "superconducting circuits and systems of trapped ions.\n", - "\n", + "superconducting circuits and systems of trapped ions." + ] + }, + { + "cell_type": "markdown", + "id": "03b3e934", + "metadata": { + "editable": true + }, + "source": [ "## Quantum deep learning\n", "\n", "Dedicated quantum information processors, such as quantum annealers\n", @@ -1682,9 +2651,16 @@ "correspond to an adjustable Ising model. Then, by initializing the\n", "input neurons in the Boltzmann machine to a fixed state and allowing\n", "the system to heat up, we can read out the output qubits to get the\n", - "result.\n", - "\n", - "\n", + "result." + ] + }, + { + "cell_type": "markdown", + "id": "9677955a", + "metadata": { + "editable": true + }, + "source": [ "## Social machine learning\n", "\n", "Machine learning aims to imitate how humans\n", @@ -1696,34 +2672,43 @@ "evolve by imitating human society so as to achieve more effective,\n", "intelligent, interpretable “social machine learning”?\n", "\n", - "And much more.\n", - "\n", - "\n", - "\n", + "And much more." + ] + }, + { + "cell_type": "markdown", + "id": "cc3ff097", + "metadata": { + "editable": true + }, + "source": [ "## The last words?\n", "\n", "Early computer scientist Alan Kay said, **The best way to predict the\n", "future is to create it**. Therefore, all machine learning\n", "practitioners, whether scholars or engineers, professors or students,\n", "need to work together to advance these important research\n", - "topics. Together, we will not just predict the future, but create it.\n", - "\n", - "\n", - "\n", - "\n", + "topics. Together, we will not just predict the future, but create it." + ] + }, + { + "cell_type": "markdown", + "id": "26c891b9", + "metadata": { + "editable": true + }, + "source": [ "## Best wishes to you all and thanks so much for your heroic efforts this semester\n", "\n", "\n", "\n", "\n", - "

    \n", - "\n", - "\n", + "

    Figure 1:

    \n", "" ] } ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/src/week48/backup2023.do.txt b/doc/src/week48/backup2023.do.txt new file mode 100644 index 000000000..6f178bacc --- /dev/null +++ b/doc/src/week48/backup2023.do.txt @@ -0,0 +1,1346 @@ +TITLE: Week 48: Support Vector Machines and Summary of course +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +DATE: today + +!split +===== Overview of week 48 ===== + +* _Thursday_: Support Vector Machines: Kernels, Classification and Regression. "Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember26.mp4?vrtx=view-as-webpage". +* _Friday_: Summary of course with perspectives for future studies. "Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember27.mp4?vrtx=view-as-webpage". + +See also Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones) of Hastie et al contains also a good discussion. + + +!split +===== Thursday ===== + +We finalize our discussion on Support Vector Machines with an emphasis on kernel transformations and applications to regression. The following "video attempts at giving an overview on this part":"https://www.youtube.com/watch?v=Toet3EiSFcM&ab_channel=StatQuestwithJoshStarmer". See also the "follow-up video":"https://www.youtube.com/watch?v=Qc5IyLW_hns&ab_channel=StatQuestwithJoshStarmer". + +!split +===== Friday ===== + +Friday's lecture is split in two parts. It starts with a summary of +what we have done this semester and continues with perspectives for future studies and +modern research projects in machine learning. + +!split +===== Support Vector Machines, overarching aims ===== + +As discussed last week, +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. + +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. I recommend you take a look at the lectures from last week on the binary classification problem. + +!split +===== Kernels and non-linearity ===== + +The cases we studied last week 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 +generated by the code below, we can achieve a better separation by introducing a more complex +basis functions. The ideal would be, as shown by the code example below, to, +via a specific transformation to obtain a separation between the +classes that is almost linear. See also Figures 12.2 and 12.3 of "Hastie et al.":"https://www.springer.com/gp/book/9780387848570". + +We can achieve a better separation by introducing more complex +basis functions. The ideal would be (see Figures 12.2 and 12.3) 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. + +!bc pycod +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() + +!ec + + + +!split +===== The equations ===== + +Suppose we define a polynomial transformation of degree two only. We define a vector $\bm{x}_i=[x_i,y_i]$ and have +!bt +\[ +\bm{z}_i^T = \phi(\bm{x}_i)^T =\left[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i\right]. +\] +!et + +With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +!bt +\[ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{z}_i^T\bm{z}_j, +\] +!et +subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$, and for the support vectors +!bt +\[ +y_i(\bm{z}_i^T\bm{w}+b)= 1 \hspace{0.1cm}\forall i, +\] +!et +from which we also find $b$. +To compute $\bm{z}_i^T\bm{z}_j$ we define the kernel $K(\bm{x}_i,\bm{x}_j)$ as +!bt +\[ +K(\bm{x}_i,\bm{x}_j)=\bm{z}_i^T\bm{z}_j= \phi(\bm{x}_i)^T\phi(\bm{x}_j). +\] +!et +For the above example, the kernel reads +!bt +\[ +K(\bm{x}_i,\bm{x}_j)=[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i]\begin{bmatrix} 1\\ \sqrt{2}x_j \\ \sqrt{2}y_j \\ x_j^2\\ y_i^2\\ \sqrt{2}x_jy_j \end{bmatrix}=1+2x_ix_j+2y_iy_j+(x_ix_j)^2+(y_iy_j)^2+2x_ix_jy_iy_j. +\] +!et + +We note that this dot product can be rewritten as +!bt +\[ +K(\bm{x}_i,\bm{x}_j)=[1+\bm{x}_i^T\bm{x}_j]^d, +\] +!et +where $d=2$ in our case and $\bm{x}_i=[x_i,y_i]$ and $\bm{x}_j=[x_j,y_j]$. +To compute the last equation is however inefficient from a computational stand. +Instead of computing the last equation for the kernel, we simply compute +the dot product $(\bm{x}_i^T\bm{x}_j)^2$. +This leads to the so-called +kernel trick. + +!split +===== The problem to solve ===== + +Using our definition of the kernel, we can rewrite again the Lagrangian +!bt +\[ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{z}_i^T\bm{z}_j, +\] +!et +subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ in terms of a convex optimization problem +!bt +\[ +\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\ +y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\ +\end{bmatrix}\bm{\lambda}-\mathbb{1}\bm{\lambda}, +\] +!et +subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and +$\bm{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$. + +!split +===== Tailoring the equations to the usage of CVXOPT ===== + +We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type +!bt +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber + &\mathrm{s.t} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \hspace{0.2cm} \wedge \bm{A}\bm{\lambda}=f. +\end{align*} +!et +Below we discuss how to solve these equations. Here we note that the matrix $\bm{P}$ has matrix elements $p_{ij}=y_iy_jK(\bm{x}_i,\bm{x}_j)$. +Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\bm{y}^T\bm{\lambda}=0$ leads to $f=0$ and $\bm{A}=\bm{y}$. How to set up the matrix $\bm{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 $\bm{G}$ and the vector $\bm{h}$. + + +!split +===== Different kernels and Mercer's theorem ===== + +There are several popular kernels being used. These are +o Linear: $K(\bm{x},\bm{y})=\bm{x}^T\bm{y}$, +o Polynomial: $K(\bm{x},\bm{y})=(\bm{x}^T\bm{y}+\gamma)^d$, +o Gaussian Radial Basis Function: $K(\bm{x},\bm{y})=\exp{\left(-\gamma\vert\vert\bm{x}-\bm{y}\vert\vert^2\right)}$, +o Tanh: $K(\bm{x},\bm{y})=\tanh{(\bm{x}^T\bm{y}+\gamma)}$, +and many other ones. + +An important theorem for us is "Mercer's +theorem":"https://en.wikipedia.org/wiki/Mercer%27s_theorem". The +theorem states that if a kernel function $K$ is symmetric, continuous +and leads to a positive semi-definite matrix $\bm{P}$ then there +exists a function $\phi$ that maps $\bm{x}_i$ and $\bm{x}_j$ into +another space (possibly with much higher dimensions) such that + +!bt +\[ +K(\bm{x}_i,\bm{x}_j)=\phi(\bm{x}_i)^T\phi(\bm{x}_j). +\] +!et + +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. + + +!split +===== The moons example ("Adapted from Geron, chapter 5":"https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/") ===== +!bc pycod +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() + +!ec + + + +!split +===== Mathematical optimization of convex functions ===== + +A mathematical (quadratic) optimization problem, or just optimization problem, has the form +!bt +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \wedge \bm{A}\bm{\lambda}=f. +\end{align*} +!et +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 $\bm{\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":"http://web.stanford.edu/~boyd/cvxbook/". + + + +!split +===== 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 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 + +!bc pycod +import numpy +import cvxopt +!ec + +This will make our life much easier. You don't need to write your own optimizer. + + +!split +===== A simple example ===== + +We remind ourselves about the general problem we want to solve +!bt +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\bm{x}^T\bm{P}\bm{x}+\bm{q}^T\bm{x},\\ \nonumber + &\mathrm{s.t.} \hspace{0.2cm} \bm{G}\bm{x} \preceq \bm{h} \wedge \bm{A}\bm{x}=f. +\end{align*} +!et +_Note_: we use _s.t._ for subject to. + +Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +!bt +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber + &\mathrm{s.t.} \\ \nonumber + &x, y \geq 0 \\ \nonumber + &x+3y \geq 15 \\ \nonumber + &2x+5y \leq 100 \\ \nonumber + &3x+4y \leq 80. \\ \nonumber +\end{align*} +!et +The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns) +!bt +\[ +\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}5\\ 3 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. +\] +!et +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 +!bt +\[ +\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}. +\] +!et +We have collapsed all the inequalities into a single matrix $\bm{G}$. We see also that our matrix +!bt +\[ +\bm{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +\] +!et +is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector $\bm{h}$ is defined as +!bt +\[ +\bm{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +\] +!et + + +Since we don't have any equalities the matrix $\bm{A}$ is set to zero +The following code solves the equations for us +!bc pycod +# 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'] +!ec + +!split +===== 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 +!bt +\[ +\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\ +y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2K(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\ +\end{bmatrix}\bm{\lambda}-\mathbb{I}\bm{\lambda}, +\] +!et +subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and +$\bm{y}=[y_1,y_2,\dots,y_n]$. +With the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$. + + +!split +===== Setting up the matrices and the problem ===== + +We have the general problem +!bt +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber + &\mathrm{s.t.} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \wedge \bm{A}\bm{\lambda}=f. +\end{align*} +!et + + + + +o With a given kernel we can thus define the matrix $\bm{P}$. +o The matrix $\bm{P}$ has matrix elements $p_{ij}=y_iy_jK(\bm{x}_i,\bm{x}_j)$. Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. +o The vector $\bm{q}$ has all elements equal to $-1$. +o The constraint $\bm{y}^T\bm{\lambda}=0$ leads to $f=0$ and $\bm{A}=\bm{y}$. +o To set up the matrix $\bm{G}$ we 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 $\bm{G}$ and the vector $\bm{h}$. + +!split +===== Setting up $\bm{G}\bm{\lambda} \preceq \bm{h}$ ===== + +We have two constraints, $0\le \lambda_i$ and $\lambda_i \le C$. To do this we multiply the ones with the constraint +$\ge$ with $-1$ in order to get $\le$. It means that the problem $\bm{G}\bm{\lambda} \preceq \bm{h}$ +can be written as +!bt +\[ +\begin{bmatrix} -1& 0 & 0 & \dots & 0 \\ +0& -1 & 0 & \dots & 0 \\ +0& 0 & -1 & \dots & 0 \\ +\dots& \dots & \dots & \dots & \dots \\ +0& 0 & 0 & \dots & -1 \\ +1 & 0 & 0 & \dots & 0 \\ +0& 1 & 0 & \dots & 0 \\ +0& 0 & 1 & \dots & 0 \\ +\dots& \dots & \dots & \dots & \dots \\ +0& 0 & 0 & \dots & 1 \\ +\end{bmatrix} +\begin{bmatrix} \lambda_1 \\ +\lambda_2 \\ +\lambda_3 \\ +\dots \\ +\lambda_n \\ +\end{bmatrix} \preceq +\begin{bmatrix} 0 \\ +0 \\ +0 \\ +\dots \\ +0 \\ +C \\ +C \\ +C \\ +\dots \\ +C \\ +\end{bmatrix}. +\] +!et + +And then we are ready to go. + +!split +===== SVMs and Regression and multiclass classification ===== + +More text will be added here. See also "Hastie et al.":"https://www.springer.com/gp/book/9780387848570" section 12.3. + +!split +===== Summary of course ===== + +!split +===== What? Me worry? No final exam in this course! ===== +FIGURE: [figures/exam1.jpeg, width=500 frac=0.6] + + + +!split +===== Topics we have covered this year ===== + +The course has two central parts + +o Statistical analysis and optimization of data +o Machine learning + +!split +===== Statistical analysis and optimization of data ===== + +The following topics have been discussed: +o Basic concepts, expectation values, variance, covariance, correlation functions and errors; +o Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions; +o Central elements from linear algebra, matrix inversion and SVD +o Gradient methods for data optimization +o Estimation of errors using cross-validation, bootstrapping and jackknife methods; +o Practical optimization using Singular-value decomposition and least squares for parameterizing data. +o Principal Component Analysis to reduce the number of features. + +!split +===== Machine learning ===== + +The following topics will be covered +o Linear methods for regression and classification: + o Ordinary Least Squares + o Ridge regression + o Lasso regression + o Logistic regression +o Neural networks and deep learning: + o Feed Forward Neural Networks + o Convolutional Neural Networks + o Recurrent Neural Networks +o Decisions trees and ensemble methods: + o Decision trees + o Bagging and voting + o Random forests + o Boosting and gradient boosting +o Support vector machines + o Binary classification and multiclass classification + o Kernel methods + o Regression + + +!split +===== Learning outcomes and overarching aims of this course ===== + +The course introduces a variety of central algorithms and methods +essential for studies of data analysis and machine learning. The +course is project based and through the various projects, normally +three, you will be exposed to fundamental research problems +in these fields, with the aim to reproduce state of the art scientific +results. The students will learn to develop and structure large codes +for studying these systems, get acquainted with computing facilities +and learn to handle large scientific projects. A good scientific and +ethical conduct is emphasized throughout the course. + +* Understand linear methods for regression and classification; +* Learn about neural network; +* Learn about bagging, boosting and trees +* Support vector machines +* Learn about basic data analysis; +* Be capable of extending the acquired knowledge to other systems and cases; +* Have an understanding of central algorithms used in data analysis and machine learning; +* Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++. + + + +!split +===== Perspective on Machine Learning ===== + +o Rapidly emerging application area +o Experiment AND theory are evolving in many many fields. Still many low-hanging fruits. +o Requires education/retraining for more widespread adoption +o A lot of “word-of-mouth” development methods + +Huge amounts of data sets require automation, classical analysis tools often inadequate. +High energy physics hit this wall in the 90’s. +In 2009 single top quark production was determined via "Boosted decision trees, Bayesian +Neural Networks, etc.":"https://arxiv.org/pdf/0903.0850.pdf" + + +!split +===== Machine Learning Research ===== + +Where to find recent results: +o Conference proceedings, arXiv and blog posts! +o _NIPS_: "Neural Information Processing Systems":"https://papers.nips.cc" +o _ICLR_: "International Conference on Learning Representations":"https://openreview.net/group?id=ICLR.cc/2018/Conference#accepted-oral-papers" +o _ICML_: International Conference on Machine Learning +o "Journal of Machine Learning Research":"http://www.jmlr.org/papers/v19/" +o "Follow ML on ArXiv":"https://arxiv.org/list/cs.LG/recent" + + +!split +===== Starting your Machine Learning Project ===== + +o Identify problem type: classification, regression +o Consider your data carefully +o Choose a simple model that fits 1. and 2. +o Consider your data carefully again! Think of data representation more carefully. +o Based on your results, feedback loop to earliest possible point + + + + +!split +===== Choose a Model and Algorithm ===== + +o Supervised? +o Start with the simplest model that fits your problem +o Start with minimal processing of data + +!split +===== Preparing Your Data ===== + +o Shuffle your data +o Mean center your data + * Why? +o Normalize the variance + * Why? +o _Whitening_ + * Decorrelates data + * Can be hit or miss +o When to do train/test split? + + +!split +===== Which Activation and Weights to Choose in Neural Networks ===== + +o RELU? ELU? +o Sigmoid or Tanh? +o Set all weights to 0? + * Terrible idea +o Set all weights to random values? + * Small random values + + +!split +===== Optimization Methods and Hyperparameters ===== +o Stochastic gradient descent +o Stochastic gradient descent + momentum +o State-of-the-art approaches: + * RMSProp + * Adam + * and more + +Which regularization and hyperparameters? $L_1$ or $L_2$, soft +classifiers, depths of trees and many other. Need to explore a large +set of hyperparameters and regularization methods. + + +!split +===== Resampling ===== + +When do we resample? + +o "Bootstrap":"https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A" +o "Cross-validation":"https://www.youtube.com/watch?v=fSytzGwwBVw&ab_channel=StatQuestwithJoshStarmer" +o Jackknife and many other + + +!split +===== Other courses on Data science and Machine Learning at UiO ===== + +The link here URL:"https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/" gives an excellent overview of courses on Machine learning at UiO. + +o "STK2100 Machine learning and statistical methods for prediction and classification":"http://www.uio.no/studier/emner/matnat/math/STK2100/index-eng.html". +o "IN3050/IN4050 Introduction to Artificial Intelligence and Machine Learning":"https://www.uio.no/studier/emner/matnat/ifi/IN3050/index-eng.html". Introductory course in machine learning and AI with an algorithmic approach. +o "STK-INF3000/4000 Selected Topics in Data Science":"http://www.uio.no/studier/emner/matnat/math/STK-INF3000/index-eng.html". The course provides insight into selected contemporary relevant topics within Data Science. +o "IN4080 Natural Language Processing":"https://www.uio.no/studier/emner/matnat/ifi/IN4080/index.html". Probabilistic and machine learning techniques applied to natural language processing. +o "STK-IN4300 – Statistical learning methods in Data Science":"https://www.uio.no/studier/emner/matnat/math/STK-IN4300/index-eng.html". An advanced introduction to statistical and machine learning. For students with a good mathematics and statistics background. +o "IN-STK5000 Adaptive Methods for Data-Based Decision Making":"https://www.uio.no/studier/emner/matnat/ifi/IN-STK5000/index-eng.html". Methods for adaptive collection and processing of data based on machine learning techniques. +o "IN5400/INF5860 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/". An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too. +o "TEK5040 – Dyp læring for autonome systemer":"https://www.uio.no/studier/emner/matnat/its/TEK5040/". The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments. + +!split +===== Additional courses of interest ===== + +o "STK4051 Computational Statistics":"https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html" +o "STK4021 Applied Bayesian Analysis and Numerical Methods":"https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html" + +!split +===== What's the future like? ===== + +Based on multi-layer nonlinear neural networks, deep learning can +learn directly from raw data, automatically extract and abstract +features from layer to layer, and then achieve the goal of regression, +classification, or ranking. Deep learning has made breakthroughs in +computer vision, speech processing and natural language, and reached +or even surpassed human level. The success of deep learning is mainly +due to the three factors: big data, big model, and big computing. + +In the past few decades, many different architectures of deep neural +networks have been proposed, such as +o Convolutional neural networks, which are mostly used in image and video data processing, and have also been applied to sequential data such as text processing; +o Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing; +o Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning. + +!split +===== Types of Machine Learning, a repetition ===== + +!bblock +The approaches to machine learning are many, but are often split into two main categories. +In *supervised learning* we know the answer to a problem, +and let the computer deduce the logic behind it. On the other hand, *unsupervised learning* +is a method for finding patterns and relationship in data sets without any prior knowledge of the system. +Some authours also operate with a third category, namely *reinforcement learning*. This is a paradigm +of learning inspired by behavioural psychology, where learning is achieved by trial-and-error, +solely from rewards and punishment. + +Another way to categorize machine learning tasks is to consider the desired output of a system. +Some of the most common tasks are: + + * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning. + + * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values. + + * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning. + + * Other unsupervised learning algortihms like _Boltzmann machines_ +!eblock + + +!split +===== Why Boltzmann machines? ===== + +What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately. +One of the major reasons is that they can be stacked layer-wise to build deep neural networks that capture complicated statistics. + +The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images. + +Furthermore, they have been used to solve complicated "quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models":"https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002". + + +!split +===== Boltzmann Machines ===== + +Why use a generative model rather than the more well known discriminative deep neural networks (DNN)? + +* Discriminitave methods have several limitations: They are mainly supervised learning methods, thus requiring labeled data. And there are tasks they cannot accomplish, like drawing new examples from an unknown probability distribution. + +* A generative model can learn to represent and sample from a probability distribution. The core idea is to learn a parametric model of the probability distribution from which the training data was drawn. As an example + + o A model for images could learn to draw new examples of cats and dogs, given a training dataset of images of cats and dogs. + o Generate a sample of an ordered or disordered phase, having been given samples of such phases. + o Model the trial function for "Monte Carlo calculations":"https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002". + + +!split +===== Some similarities and differences from DNNs ===== + + o Both use gradient-descent based learning procedures for minimizing cost functions + o Energy based models don't use backpropagation and automatic differentiation for computing gradients, instead turning to Markov Chain Monte Carlo methods. + o DNNs often have several hidden layers. A restricted Boltzmann machine has only one hidden layer, however several RBMs can be stacked to make up Deep Belief Networks, of which they constitute the building blocks. + +History: The RBM was developed by amongst others "Geoffrey Hinton":"https://en.wikipedia.org/wiki/Geoffrey_Hinton", called by some the "Godfather of Deep Learning", working with the University of Toronto and Google. + + +!split +===== Boltzmann machines (BM) ===== + +!bblock +A BM is what we would call an undirected probabilistic graphical model +with stochastic continuous or discrete units. +!eblock +!bblock +It is interpreted as a stochastic recurrent neural network where the +state of each unit(neurons/nodes) depends on the units it is connected +to. The weights in the network represent thus the strength of the +interaction between various units/nodes. +!eblock +!bblock +It turns into a Hopfield network if we choose deterministic rather +than stochastic units. In contrast to a Hopfield network, a BM is a +so-called generative model. It allows us to generate new samples from +the learned distribution. +!eblock + +!split +===== A standard BM setup ===== + +!bblock +A standard BM network is divided into a set of observable and visible units $\hat{x}$ and a set of unknown hidden units/nodes $\hat{h}$. +!eblock + +!bblock +Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to $1$. +!eblock + +!bblock +BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning +!eblock + +However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS. +Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below. + + + +!split +===== The structure of the RBM network ===== + +FIGURE: [figures/RBM.pdf, width=800 frac=1.0] + + + +!split +===== The network ===== + +_The network layers_: + o A function $\mathbf{x}$ that represents the visible layer, a vector of $M$ elements (nodes). This layer represents both what the RBM might be given as training input, and what we want it to be able to reconstruct. This might for example be given by the pixels of an image or coefficients representing speech, or the coordinates of a quantum mechanical state function. + o The function $\mathbf{h}$ represents the hidden, or latent, layer. A vector of $N$ elements (nodes). Also called "feature detectors". + +!split +===== Goals ===== + +The goal of the hidden layer is to increase the model's expressive +power. We encode complex interactions between visible variables by +introducing additional, hidden variables that interact with visible +degrees of freedom in a simple manner, yet still reproduce the complex +correlations between visible degrees in the data once marginalized +over (integrated out). + +_The network parameters, to be optimized/learned_: + o $\mathbf{a}$ represents the visible bias, a vector of same length as $\mathbf{x}$. + o $\mathbf{b}$ represents the hidden bias, a vector of same lenght as $\mathbf{h}$. + o $W$ represents the interaction weights, a matrix of size $M\times N$. + + + + +!split +===== Joint distribution ===== + +The restricted Boltzmann machine is described by a Boltzmann distribution +!bt +\begin{align} + P_{rbm}(\mathbf{x},\mathbf{h}) = \frac{1}{Z} e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})}, +\end{align} +!et +where $Z$ is the normalization constant or partition function, defined as +!bt +\begin{align} + Z = \int \int e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})} d\mathbf{x} d\mathbf{h}. +\end{align} +!et +It is common to ignore $T_0$ by setting it to one. + + + + +!split +===== Network Elements, the energy function ===== + +The function $E(\mathbf{x},\mathbf{h})$ gives the _energy_ of a +configuration (pair of vectors) $(\mathbf{x}, \mathbf{h})$. The lower +the energy of a configuration, the higher the probability of it. This +function also depends on the parameters $\mathbf{a}$, $\mathbf{b}$ and +$W$. Thus, when we adjust them during the learning procedure, we are +adjusting the energy function to best fit our problem. + +An expression for the energy function is +!bt +\[ +E(\hat{x},\hat{h}) = -\sum_{ia}^{NA}b_i^a \alpha_i^a(x_i)-\sum_{jd}^{MD}c_j^d \beta_j^d(h_j)-\sum_{ijad}^{NAMD}b_i^a \alpha_i^a(x_i)c_j^d \beta_j^d(h_j)w_{ij}^{ad}. +\] +!et + +Here $\beta_j^d(h_j)$ and $\alpha_i^a(x_j)$ are so-called transfer functions that map a given input value to a desired feature value. The labels $a$ and $d$ denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. _Note_ that there is no connection between nodes in a layer. + +The quantities $b$ and $c$ can be interpreted as the visible and hidden biases, respectively. + +The connection between the nodes in the two layers is given by the weights $w_{ij}$. + +!split +===== Defining different types of RBMs ===== +There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function $E(\mathbf{x},\mathbf{h})$. + +!bblock Binary-Binary RBM: + +RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows: +!bt +\begin{align} + E(\mathbf{x}, \mathbf{h}) = - \sum_i^M x_i a_i- \sum_j^N b_j h_j - \sum_{i,j}^{M,N} x_i w_{ij} h_j, +\end{align} +!et +where the binary values taken on by the nodes are most commonly 0 and 1. +!eblock +!bblock Gaussian-Binary RBM: + +Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary: +!bt +\begin{align} + E(\mathbf{x}, \mathbf{h}) = \sum_i^M \frac{(x_i - a_i)^2}{2\sigma_i^2} - \sum_j^N b_j h_j - \sum_{i,j}^{M,N} \frac{x_i w_{ij} h_j}{\sigma_i^2}. +\end{align} +!et +!eblock + +!split +===== More about RBMs ===== +o Useful when we model continuous data (i.e., we wish $\mathbf{x}$ to be continuous) +o Requires a smaller learning rate, since there's no upper bound to the value a component might take in the reconstruction + +Other types of units include: + o Softmax and multinomial units + o Gaussian visible and hidden units + o Binomial units + o Rectified linear units + +To read more, see "Lectures on Boltzmann machines in Physics":"https://github.com/CompPhysics/ComputationalPhysics2/blob/gh-pages/doc/pub/notebook2/ipynb/notebook2.ipynb". + + +!split +===== Autoencoders: Overarching view ===== + +Autoencoders are artificial neural networks capable of learning +efficient representations of the input data (these representations are called codings) without +any supervision (i.e., the training set is unlabeled). These codings +typically have a much lower dimensionality than the input data, making +autoencoders useful for dimensionality reduction. + +More importantly, autoencoders act as powerful feature detectors, and +they can be used for unsupervised pretraining of deep neural networks. + +Lastly, they are capable of randomly generating new data that looks +very similar to the training data; this is called a generative +model. For example, you could train an autoencoder on pictures of +faces, and it would then be able to generate new faces. Surprisingly, +autoencoders work by simply learning to copy their inputs to their +outputs. This may sound like a trivial task, but we will see that +constraining the network in various ways can make it rather +difficult. For example, you can limit the size of the internal +representation, or you can add noise to the inputs and train the +network to recover the original inputs. These constraints prevent the +autoencoder from trivially copying the inputs directly to the outputs, +which forces it to learn efficient ways of representing the data. In +short, the codings are byproducts of the autoencoder’s attempt to +learn the identity function under some constraints. + +"Video on autoencoders":"https://www.coursera.org/lecture/building-deep-learning-models-with-tensorflow/autoencoders-1U4L3" + +See also A. Geron's textbook, chapter 15. + +!split +===== Bayesian Machine Learning ===== + +This is an important topic if we aim at extracting a probability +distribution. This gives us also a confidence interval and error +estimates. + +Bayesian machine learning allows us to encode our prior beliefs about +what those models should look like, independent of what the data tells +us. This is especially useful when we don’t have a ton of data to +confidently learn our model. + +"Video on Bayesian deep learning":"https://www.youtube.com/watch?v=E1qhGw8QxqY&ab_channel=AndrewGordonWilson" + +See also the "slides here":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Articles/lec03.pdf". + +!split +===== Reinforcement Learning ===== + +Reinforcement Learning (RL) is one of the most exciting fields of +Machine Learning today, and also one of the oldest. It has been around +since the 1950s, producing many interesting applications over the +years. + +It studies +how agents take actions based on trial and error, so as to maximize +some notion of cumulative reward in a dynamic system or +environment. Due to its generality, the problem has also been studied +in many other disciplines, such as game theory, control theory, +operations research, information theory, multi-agent systems, swarm +intelligence, statistics, and genetic algorithms. + +In March 2016, AlphaGo, a computer program that plays the board game +Go, beat Lee Sedol in a five-game match. This was the first time a +computer Go program had beaten a 9-dan (highest rank) professional +without handicaps. AlphaGo is based on deep convolutional neural +networks and reinforcement learning. AlphaGo’s victory was a major +milestone in artificial intelligence and it has also made +reinforcement learning a hot research area in the field of machine +learning. + +"Lecture on Reinforcement Learning":"https://www.youtube.com/watch?v=FgzM3zpZ55o&ab_channel=stanfordonline". + +See also A. Geron's textbook, chapter 16. + +!split +===== Transfer learning ===== + +The goal of transfer learning is to transfer the model or knowledge +obtained from a source task to the target task, in order to resolve +the issues of insufficient training data in the target task. The +rationality of doing so lies in that usually the source and target +tasks have inter-correlations, and therefore either the features, +samples, or models in the source task might provide useful information +for us to better solve the target task. Transfer learning is a hot +research topic in recent years, with many problems still waiting to be studied. + +"Lecture on transfer learning":"https://www.ias.edu/video/machinelearning/2020/0331-SamoryKpotufe". + +!split +===== Adversarial learning ===== + +The conventional deep generative model has a potential problem: the +model tends to generate extreme instances to maximize the +probabilistic likelihood, which will hurt its performance. Adversarial +learning utilizes the adversarial behaviors (e.g., generating +adversarial instances or training an adversarial model) to enhance the +robustness of the model and improve the quality of the generated +data. In recent years, one of the most promising unsupervised learning +technologies, generative adversarial networks (GAN), has already been +successfully applied to image, speech, and text. + +"Lecture on adversial learning":"https://www.youtube.com/watch?v=CIfsB_EYsVI&ab_channel=StanfordUniversitySchoolofEngineering". + +!split +===== Dual learning ===== + +Dual learning is a new learning paradigm, the basic idea of which is +to use the primal-dual structure between machine learning tasks to +obtain effective feedback/regularization, and guide and strengthen the +learning process, thus reducing the requirement of large-scale labeled +data for deep learning. The idea of dual learning has been applied to +many problems in machine learning, including machine translation, +image style conversion, question answering and generation, image +classification and generation, text classification and generation, +image-to-text, and text-to-image. + +!split +===== Distributed machine learning ===== + +Distributed computation will speed up machine learning algorithms, +significantly improve their efficiency, and thus enlarge their +application. When distributed meets machine learning, more than just +implementing the machine learning algorithms in parallel is required. + + +!split +===== Meta learning ===== + +Meta learning is an emerging research direction in machine +learning. Roughly speaking, meta learning concerns learning how to +learn, and focuses on the understanding and adaptation of the learning +itself, instead of just completing a specific learning task. That is, +a meta learner needs to be able to evaluate its own learning methods +and adjust its own learning methods according to specific learning +tasks. + +!split +===== The Challenges Facing Machine Learning ===== + +While there has been much progress in machine learning, there are also challenges. + +For example, the mainstream machine learning technologies are +black-box approaches, making us concerned about their potential +risks. To tackle this challenge, we may want to make machine learning +more explainable and controllable. As another example, the +computational complexity of machine learning algorithms is usually +very high and we may want to invent lightweight algorithms or +implementations. Furthermore, in many domains such as physics, +chemistry, biology, and social sciences, people usually seek elegantly +simple equations (e.g., the Schrödinger equation) to uncover the +underlying laws behind various phenomena. In the field of machine +learning, can we reveal simple laws instead of designing more complex +models for data fitting? Although there are many challenges, we are +still very optimistic about the future of machine learning. As we look +forward to the future, here are what we think the research hotspots in +the next ten years will be. + +See the article on "Discovery of Physics From Data: Universal Laws and Discrepancies":"https://www.frontiersin.org/articles/10.3389/frai.2020.00025/full" + +!split +===== Explainable machine learning ===== + +Machine learning, especially deep learning, evolves rapidly. The +ability gap between machine and human on many complex cognitive tasks +becomes narrower and narrower. However, we are still in the very early +stage in terms of explaining why those effective models work and how +they work. + +_What is missing: the gap between correlation and causation_. Standard Machine Learning is based on what e have called a frequentist approach. + +Most +machine learning techniques, especially the statistical ones, depend +highly on correlations in data sets to make predictions and analyses. In +contrast, rational humans tend to reply on clear and trustworthy +causality relations obtained via logical reasoning on real and clear +facts. It is one of the core goals of explainable machine learning to +transition from solving problems by data correlation to solving +problems by logical reasoning. + +_Bayesian Machine Learning is one of the exciting research directions in this field_. + +!split +===== Quantum machine learning ===== + +Quantum machine learning is an emerging interdisciplinary research +area at the intersection of quantum computing and machine learning. + +Quantum computers use effects such as quantum coherence and quantum +entanglement to process information, which is fundamentally different +from classical computers. Quantum algorithms have surpassed the best +classical algorithms in several problems (e.g., searching for an +unsorted database, inverting a sparse matrix), which we call quantum +acceleration. + +When quantum computing meets machine learning, it can be a mutually +beneficial and reinforcing process, as it allows us to take advantage +of quantum computing to improve the performance of classical machine +learning algorithms. In addition, we can also use the machine learning +algorithms (on classic computers) to analyze and improve quantum +computing systems. + +"Lecture on Quantum ML":"https://www.youtube.com/watch?v=Xh9pUu3-WxM&ab_channel=InstituteforPure%26AppliedMathematics%28IPAM%29". + + +"Read interview with Maria Schuld on her work on Quantum Machine Learning":"https://physics.aps.org/articles/v13/179?utm_campaign=weekly&utm_medium=email&utm_source=emailalert". See also "her recent textbook":"https://www.springer.com/gp/book/9783319964232". + + +!split +===== Quantum machine learning algorithms based on linear algebra ===== + +Many quantum machine learning algorithms are based on variants of +quantum algorithms for solving linear equations, which can efficiently +solve N-variable linear equations with complexity of O(log2 N) under +certain conditions. The quantum matrix inversion algorithm can +accelerate many machine learning methods, such as least square linear +regression, least square version of support vector machine, Gaussian +process, and more. The training of these algorithms can be simplified +to solve linear equations. The key bottleneck of this type of quantum +machine learning algorithms is data input—that is, how to initialize +the quantum system with the entire data set. Although efficient +data-input algorithms exist for certain situations, how to efficiently +input data into a quantum system is as yet unknown for most cases. + +!split +===== Quantum reinforcement learning ===== + +In quantum reinforcement learning, a quantum agent interacts with the +classical environment to obtain rewards from the environment, so as to +adjust and improve its behavioral strategies. In some cases, it +achieves quantum acceleration by the quantum processing capabilities +of the agent or the possibility of exploring the environment through +quantum superposition. Such algorithms have been proposed in +superconducting circuits and systems of trapped ions. + +!split +===== Quantum deep learning ===== + +Dedicated quantum information processors, such as quantum annealers +and programmable photonic circuits, are well suited for building deep +quantum networks. The simplest deep quantum network is the Boltzmann +machine. The classical Boltzmann machine consists of bits with tunable +interactions and is trained by adjusting the interaction of these bits +so that the distribution of its expression conforms to the statistics +of the data. To quantize the Boltzmann machine, the neural network can +simply be represented as a set of interacting quantum spins that +correspond to an adjustable Ising model. Then, by initializing the +input neurons in the Boltzmann machine to a fixed state and allowing +the system to heat up, we can read out the output qubits to get the +result. + + +!split +===== Social machine learning ===== + +Machine learning aims to imitate how humans +learn. While we have developed successful machine learning algorithms, +until now we have ignored one important fact: humans are social. Each +of us is one part of the total society and it is difficult for us to +live, learn, and improve ourselves, alone and isolated. Therefore, we +should design machines with social properties. Can we let machines +evolve by imitating human society so as to achieve more effective, +intelligent, interpretable “social machine learning”? + +And much more. + + + +!split +===== The last words? ===== + +Early computer scientist Alan Kay said, _The best way to predict the +future is to create it_. Therefore, all machine learning +practitioners, whether scholars or engineers, professors or students, +need to work together to advance these important research +topics. Together, we will not just predict the future, but create it. + + + + +!split +===== Best wishes to you all and thanks so much for your heroic efforts this semester ===== + +FIGURE: [figures/Nebbdyr2.png, width=500 frac=0.6] + + + + + + diff --git a/doc/src/week48/week48.do.txt b/doc/src/week48/week48.do.txt index 6f178bacc..920ee82b1 100644 --- a/doc/src/week48/week48.do.txt +++ b/doc/src/week48/week48.do.txt @@ -1,637 +1,830 @@ TITLE: Week 48: Support Vector Machines and Summary of course -AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo, Norway DATE: today !split ===== Overview of week 48 ===== -* _Thursday_: Support Vector Machines: Kernels, Classification and Regression. "Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember26.mp4?vrtx=view-as-webpage". -* _Friday_: Summary of course with perspectives for future studies. "Video of Lecture":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember27.mp4?vrtx=view-as-webpage". +!split +===== Plan for week 47 ===== + +!bblock Lab sessions on Tuesday and Wednesday + * Work and Discussion of project 3 + * Last weekly exercise, +!eblock + +!bblock Plans for the lecture Monday 25 November, with video suggestions etc +o Bossting and gradient boosting and ensemble models +o Summary of course +o Readings and Videos: + o These lecture notes at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week47/ipynb/week48.ipynb" + o See also lecture notes from week 47 at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/pub/week46/ipynb/week47.ipynb". The lecture on Monday starts with a repetition on AdaBoost before we move over to gradient boosting with examples +# o Video of lecture at URL:"https://youtu.be/RIHzmLv05DA" +# o Whiteboard notes at URL:"https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/NotesNovember25.pdf" + o Video on Decision trees URL:"https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" + o Video on boosting methods URL:"https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai" + o Video on AdaBoost URL:"https://www.youtube.com/watch?v=LsK-xG1cLYA" + o Video on Gradient boost, part 1, parts 2-4 follow thereafter URL:"https://www.youtube.com/watch?v=3CC4N4z3GJc" + o Decision Trees: Rashcka et al chapter 3 pages 86-98, and chapter 7 on Ensemble methods, Voting and Bagging and Gradient Boosting. See also lecture from STK-IN4300, lecture 7 at URL:"https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf". +!eblock + -See also Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones) of Hastie et al contains also a good discussion. !split -===== Thursday ===== +===== 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. -We finalize our discussion on Support Vector Machines with an emphasis on kernel transformations and applications to regression. The following "video attempts at giving an overview on this part":"https://www.youtube.com/watch?v=Toet3EiSFcM&ab_channel=StatQuestwithJoshStarmer". See also the "follow-up video":"https://www.youtube.com/watch?v=Qc5IyLW_hns&ab_channel=StatQuestwithJoshStarmer". !split -===== Friday ===== +===== 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 +!bt +\[ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +\] +!et + +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 + + +!bt +\[ +\sigma(t) = \frac{1}{1+\exp{(-t)}}, +\] +!et + +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 +!bt +\[ +C(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\] +!et + +In this case the function $f(x)$ was replaced by the design matrix +$\bm{X}$ and the unknown linear regression parameters $\bm{\beta}$, +that is $\bm{f}=\bm{X}\bm{\beta}$. In linear regression we can +simply invert a matrix and obtain the parameters $\beta$ by + +!bt +\[ +\bm{\beta}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\beta_m$ and $\gamma_m$. -Friday's lecture is split in two parts. It starts with a summary of -what we have done this semester and continues with perspectives for future studies and -modern research projects in machine learning. !split -===== Support Vector Machines, overarching aims ===== +===== Iterative Fitting, Regression and Squared-error Cost Function ===== -As discussed last week, -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 way we proceed is as follows (here we specialize to the squared-error cost function) -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. +o Establish a cost function, here ${\cal C}(\bm{y},\bm{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)$. +o Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers. +o For $m=1:M$ + o minimize $\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2$ wrt $\gamma$ and $\beta$ + o This gives the optimal values $\beta_m$ and $\gamma_m$ + o Determine then the new values $f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m)$ + +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. -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. I recommend you take a look at the lectures from last week on the binary classification problem. !split -===== Kernels and non-linearity ===== +===== Squared-Error Example and Iterative Fitting ===== -The cases we studied last week 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. +To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function. -If our feature space is not easy to separate, as shown in the figure -generated by the code below, we can achieve a better separation by introducing a more complex -basis functions. The ideal would be, as shown by the code example below, to, -via a specific transformation to obtain a separation between the -classes that is almost linear. See also Figures 12.2 and 12.3 of "Hastie et al.":"https://www.springer.com/gp/book/9780387848570". +For simplicity we assume also that our functions $b(x;\gamma)=1+\gamma x$. -We can achieve a better separation by introducing more complex -basis functions. The ideal would be (see Figures 12.2 and 12.3) to, via a specific transformation to -obtain a separation between the classes which is almost linear. +This means that for every iteration $m$, we need to optimize -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. +!bt +\[ +(\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. +\] +!et + +We start our iteration by simply setting $f_0(x)=0$. +Taking the derivatives with respect to $\beta$ and $\gamma$ we obtain +!bt +\[ +\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0, +\] +!et +and +!bt +\[ +\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. +\] +!et +We can then rewrite these equations as (defining $\bm{w}=\bm{e}+\gamma \bm{x})$ with $\bm{e}$ being the unit vector) +!bt +\[ +\gamma \bm{w}^T(\bm{y}-\beta\gamma \bm{w})=0, +\] +!et +which gives us $\beta = \bm{w}^T\bm{y}/(\bm{w}^T\bm{w})$. Similarly we have +!bt +\[ +\beta\gamma \bm{x}^T(\bm{y}-\beta(1+\gamma \bm{x}))=0, +\] +!et + +which leads to $\gamma =(\bm{x}^T\bm{y}-\beta\bm{x}^T\bm{e})/(\beta\bm{x}^T\bm{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$. + + + +!split +===== 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 + +!bt +\[ +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). +\] +!et + +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 +!bt +\[ +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), +\] +!et +will be a function of +!bt +\[ +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). +\] +!et + + + +!split +===== Adaptive Boosting, AdaBoost ===== + +In our iterative procedure we define thus +!bt +\[ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +\] +!et + +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 +!bt +\[ +C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. +\] +!et + +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 + +!bt +\[ +C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))}, +\] +!et +where we have defined $w_i^m= \exp{(-y_if_{m-1}(x_i))}$. + +!split +===== Building up AdaBoost ===== + +First, for any $\beta > 0$, we optimize $G$ by setting +!bt +\[ +G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)), +\] +!et +which is the classifier that minimizes the weighted error rate in predicting $y$. + +We can do this by rewriting +!bt +\[ +\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +\] +!et +which can be rewritten as +!bt +\[ +(\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, +\] +!et +which leads to +!bt +\[ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +\] +!et +where we have redefined the error as +!bt +\[ +\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}, +\] +!et +which leads to an update of +!bt +\[ +f_m(x) = f_{m-1}(x) +\beta_m G_m(x). +\] +!et +This leads to the new weights +!bt +\[ +w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))} +\] +!et + + +!split +===== 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 +$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{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 $\bm{y}$. + +We have already defined the misclassification error $\mathrm{err}$ as +!bt +\[ +\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), +\] +!et +where the function $I()$ is one if we misclassify and zero if we classify correctly. + +!split +===== 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. +o 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$. +o We rewrite the misclassification error as +!bt +\[ +\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}, +\] +!et +o 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. + o Fit then a given classifier to the training set using the weights $w_i$. + o Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly. + o Define a quantity $\alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m}$ + o Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)}$. +o Compute the new classifier $G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i)$. + +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. + + + +!split +===== AdaBoost Examples ===== + +Using _Scikit-Learn_ it is easy to apply the adaptive boosting algorithm, as done here. + +!bc pycod +from sklearn.ensemble import AdaBoostClassifier + +ada_clf = AdaBoostClassifier( + DecisionTreeClassifier(max_depth=2), n_estimators=200, + algorithm="SAMME.R", learning_rate=0.01, random_state=42) +ada_clf.fit(X_train, y_train) +y_pred = ada_clf.predict(X_test) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +plt.show() +y_probas = ada_clf.predict_proba(X_test) +skplt.metrics.plot_roc(y_test, y_probas) +plt.show() +skplt.metrics.plot_cumulative_gain(y_test, y_probas) +plt.show() +!ec + +!split +===== Making an ADAboost code yourself ===== !bc pycod import numpy as np -import os -np.random.seed(42) +class DecisionStump: + def fit(self, X, y, weights): + m, n = X.shape + self.alpha = 0 + self.threshold = None + self.polarity = 1 -# 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 + min_error = float('inf') + for feature in range(n): + feature_values = np.unique(X[:, feature]) -from sklearn.svm import SVC -from sklearn import datasets + for threshold in feature_values: + for polarity in [1, -1]: + predictions = np.ones(m) + predictions[X[:, feature] < threshold] = -1 + predictions *= polarity + error = sum(weights[predictions != y]) + if error < min_error: + min_error = error + self.alpha = 0.5 * np.log((1 - error) / (error + 1e-10)) + self.threshold = threshold + self.feature_index = feature + self.polarity = polarity -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]) + def predict(self, X): + m = X.shape[0] + predictions = np.ones(m) + if self.polarity == 1: + predictions[X[:, self.feature_index] < self.threshold] = -1 + else: + predictions[X[:, self.feature_index] >= self.threshold] = -1 + return predictions -plt.figure(figsize=(11, 4)) +class AdaBoost: + def fit(self, X, y, n_estimators): + m = X.shape[0] + self.alphas = [] + self.models = [] -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]) + weights = np.ones(m) / m -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() + for _ in range(n_estimators): + stump = DecisionStump() + stump.fit(X, y, weights) + predictions = stump.predict(X) + + error = sum(weights[predictions != y]) + if error == 0: + break + + self.models.append(stump) + self.alphas.append(stump.alpha) + + weights *= np.exp(-stump.alpha * y * predictions) + weights /= np.sum(weights) + + def predict(self, X): + final_predictions = np.zeros(X.shape[0]) + for alpha, model in zip(self.alphas, self.models): + final_predictions += alpha * model.predict(X) + return np.sign(final_predictions) + +# Example dataset (X, y) +X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]) +y = np.array([-1, -1, -1, -1, 1, 1, 1, 1, 1, 1]) # Labels must be -1 or 1 + +# Train AdaBoost +ada = AdaBoost() +ada.fit(X, y, n_estimators=10) + +# Predictions +predictions = ada.predict(X) +print("Predictions:", predictions) !ec +!split +===== Gradient boosting: Basics with Steepest Descent/Functional Gradient 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. + +!split +===== The Squared-Error again! Steepest Descent ===== + +We start again with our cost function ${\cal C}(\bm{y}m\bm{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 + +!bt +\[ +(\hat{\bm{f}}) = \mathrm{argmin}_{\bm{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\] +!et + +We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as +!bt +\[ +f_M(x) = \sum_{m=0}^M h_m(x). +\] +!et + +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 +!bt +\[ +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)}. +\] +!et + +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 +!bt +\[ +(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +\] +!et + +!split +===== Steepest Descent Example ===== + +Optimizing with respect to $\rho$ we obtain (taking the derivative) that $\rho_1 = -1/2$. We have then that +!bt +\[ +f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i. +\] +!et +We can then proceed and compute +!bt +\[ +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, +\] +!et +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_. + +!split +===== Gradient Boosting, algorithm ===== + +Steepest descent is however not much used, since it only optimizes $f$ at a fixed set of $n$ points, +so we do not learn a function that can generalize. However, we can modify the algorithm by +fitting a weak learner to approximate the negative gradient signal. + +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 +!bt +\[ +C(\bm{y},\bm{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +\] +!et + +The way we proceed in an iterative fashion is to +o Initialize our estimate $f_0(x)$. +o For $m=1:M$, we + o compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x)$; + o fit the so-called base-learner to the negative gradient $h_m(u_m,x)$; + o update the estimate $f_m(x) = f_{m-1}(x)+h_m(u_m,x)$; +o The final estimate is then $f_M(x) = \sum_{m=1}^M h_m(u_m,x)$. + !split -===== The equations ===== - -Suppose we define a polynomial transformation of degree two only. We define a vector $\bm{x}_i=[x_i,y_i]$ and have -!bt -\[ -\bm{z}_i^T = \phi(\bm{x}_i)^T =\left[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i\right]. -\] -!et - -With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) -!bt -\[ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{z}_i^T\bm{z}_j, -\] -!et -subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$, and for the support vectors -!bt -\[ -y_i(\bm{z}_i^T\bm{w}+b)= 1 \hspace{0.1cm}\forall i, -\] -!et -from which we also find $b$. -To compute $\bm{z}_i^T\bm{z}_j$ we define the kernel $K(\bm{x}_i,\bm{x}_j)$ as -!bt -\[ -K(\bm{x}_i,\bm{x}_j)=\bm{z}_i^T\bm{z}_j= \phi(\bm{x}_i)^T\phi(\bm{x}_j). -\] -!et -For the above example, the kernel reads -!bt -\[ -K(\bm{x}_i,\bm{x}_j)=[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i]\begin{bmatrix} 1\\ \sqrt{2}x_j \\ \sqrt{2}y_j \\ x_j^2\\ y_i^2\\ \sqrt{2}x_jy_j \end{bmatrix}=1+2x_ix_j+2y_iy_j+(x_ix_j)^2+(y_iy_j)^2+2x_ix_jy_iy_j. -\] -!et - -We note that this dot product can be rewritten as -!bt -\[ -K(\bm{x}_i,\bm{x}_j)=[1+\bm{x}_i^T\bm{x}_j]^d, -\] -!et -where $d=2$ in our case and $\bm{x}_i=[x_i,y_i]$ and $\bm{x}_j=[x_j,y_j]$. -To compute the last equation is however inefficient from a computational stand. -Instead of computing the last equation for the kernel, we simply compute -the dot product $(\bm{x}_i^T\bm{x}_j)^2$. -This leads to the so-called -kernel trick. - -!split -===== The problem to solve ===== - -Using our definition of the kernel, we can rewrite again the Lagrangian -!bt -\[ -{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{z}_i^T\bm{z}_j, -\] -!et -subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ in terms of a convex optimization problem -!bt -\[ -\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\ -y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\ -\dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots \\ -y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\ -\end{bmatrix}\bm{\lambda}-\mathbb{1}\bm{\lambda}, -\] -!et -subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and -$\bm{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$. - -!split -===== Tailoring the equations to the usage of CVXOPT ===== - -We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type -!bt -\begin{align*} - &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber - &\mathrm{s.t} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \hspace{0.2cm} \wedge \bm{A}\bm{\lambda}=f. -\end{align*} -!et -Below we discuss how to solve these equations. Here we note that the matrix $\bm{P}$ has matrix elements $p_{ij}=y_iy_jK(\bm{x}_i,\bm{x}_j)$. -Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\bm{y}^T\bm{\lambda}=0$ leads to $f=0$ and $\bm{A}=\bm{y}$. How to set up the matrix $\bm{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 $\bm{G}$ and the vector $\bm{h}$. - - -!split -===== Different kernels and Mercer's theorem ===== - -There are several popular kernels being used. These are -o Linear: $K(\bm{x},\bm{y})=\bm{x}^T\bm{y}$, -o Polynomial: $K(\bm{x},\bm{y})=(\bm{x}^T\bm{y}+\gamma)^d$, -o Gaussian Radial Basis Function: $K(\bm{x},\bm{y})=\exp{\left(-\gamma\vert\vert\bm{x}-\bm{y}\vert\vert^2\right)}$, -o Tanh: $K(\bm{x},\bm{y})=\tanh{(\bm{x}^T\bm{y}+\gamma)}$, -and many other ones. - -An important theorem for us is "Mercer's -theorem":"https://en.wikipedia.org/wiki/Mercer%27s_theorem". The -theorem states that if a kernel function $K$ is symmetric, continuous -and leads to a positive semi-definite matrix $\bm{P}$ then there -exists a function $\phi$ that maps $\bm{x}_i$ and $\bm{x}_j$ into -another space (possibly with much higher dimensions) such that - -!bt -\[ -K(\bm{x}_i,\bm{x}_j)=\phi(\bm{x}_i)^T\phi(\bm{x}_j). -\] -!et - -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. - - -!split -===== The moons example ("Adapted from Geron, chapter 5":"https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/") ===== +===== Gradient Boosting, Examples of Regression ===== !bc pycod -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 +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.ensemble import GradientBoostingRegressor +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) + +for degree in range(1,maxdegree): + model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) + 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() +!ec -from sklearn.svm import SVC -from sklearn import datasets +!split +===== Gradient Boosting, Classification Example ===== +!bc pycod +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() - -from sklearn.pipeline import Pipeline +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 -from sklearn.svm import LinearSVC +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 Gradient boosting and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test))) -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]) +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() - -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]) - +y_probas = gd_clf.predict_proba(X_test_scaled) +skplt.metrics.plot_roc(y_test, y_probas) +save_fig("gdclassiffierroc") 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) - +skplt.metrics.plot_cumulative_gain(y_test, y_probas) +save_fig("gdclassiffiercgain") 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() - !ec +!split +===== XGBoost: Extreme Gradient Boosting ===== + + +"XGBoost":"https://github.com/dmlc/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":"https://arxiv.org/abs/1603.02754". + +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!!! !split -===== Mathematical optimization of convex functions ===== - -A mathematical (quadratic) optimization problem, or just optimization problem, has the form -!bt -\begin{align*} - &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber - &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \wedge \bm{A}\bm{\lambda}=f. -\end{align*} -!et -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 $\bm{\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":"http://web.stanford.edu/~boyd/cvxbook/". - - - -!split -===== 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 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 +===== Regression Case ===== !bc pycod -import numpy -import cvxopt +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +import xgboost as xgb +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) + +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,y_train) + y_pred = model.predict(X_test) + 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() + !ec -This will make our life much easier. You don't need to write your own optimizer. - - !split -===== A simple example ===== +===== Xgboost on the Cancer Data ===== -We remind ourselves about the general problem we want to solve -!bt -\begin{align*} - &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\bm{x}^T\bm{P}\bm{x}+\bm{q}^T\bm{x},\\ \nonumber - &\mathrm{s.t.} \hspace{0.2cm} \bm{G}\bm{x} \preceq \bm{h} \wedge \bm{A}\bm{x}=f. -\end{align*} -!et -_Note_: we use _s.t._ for subject to. - -Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem -!bt -\begin{align*} - &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber - &\mathrm{s.t.} \\ \nonumber - &x, y \geq 0 \\ \nonumber - &x+3y \geq 15 \\ \nonumber - &2x+5y \leq 100 \\ \nonumber - &3x+4y \leq 80. \\ \nonumber -\end{align*} -!et -The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns) -!bt -\[ -\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}5\\ 3 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}. -\] -!et -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 -!bt -\[ -\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}. -\] -!et -We have collapsed all the inequalities into a single matrix $\bm{G}$. We see also that our matrix -!bt -\[ -\bm{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} -\] -!et -is clearly positive semi-definite (all eigenvalues larger or equal zero). -Finally, the vector $\bm{h}$ is defined as -!bt -\[ -\bm{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. -\] -!et - - -Since we don't have any equalities the matrix $\bm{A}$ is set to zero -The following code solves the equations for us +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. !bc pycod -# 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'] + +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 Gradient Boosting 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() + !ec -!split -===== 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 -!bt -\[ -\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\ -y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2K(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\ -\dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots \\ -y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\ -\end{bmatrix}\bm{\lambda}-\mathbb{I}\bm{\lambda}, -\] -!et -subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and -$\bm{y}=[y_1,y_2,\dots,y_n]$. -With the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$. !split -===== Setting up the matrices and the problem ===== +===== Gradient boosting, making our own code for a regression case ===== -We have the general problem -!bt -\begin{align*} - &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber - &\mathrm{s.t.} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \wedge \bm{A}\bm{\lambda}=f. -\end{align*} -!et +!bc pycod +import numpy as np +class DecisionTreeRegressor: + def __init__(self, max_depth=3): + self.max_depth = max_depth + self.tree = None + def fit(self, X, y): + self.tree = self._grow_tree(X, y) + def _grow_tree(self, X, y, depth=0): + n_samples, n_features = X.shape + if depth < self.max_depth: + best_feature, best_threshold = self._best_split(X, y) + if best_feature is not None: + left_indices = X[:, best_feature] < best_threshold + right_indices = X[:, best_feature] >= best_threshold + left_child = self._grow_tree(X[left_indices], y[left_indices], depth + 1) + right_child = self._grow_tree(X[right_indices], y[right_indices], depth + 1) + return (best_feature, best_threshold, left_child, right_child) + return np.mean(y) + def _best_split(self, X, y): + best_mse = float('inf') + best_feature, best_threshold = None, None + n_samples, n_features = X.shape + + for feature in range(n_features): + thresholds = np.unique(X[:, feature]) + for threshold in thresholds: + left_indices = X[:, feature] < threshold + right_indices = X[:, feature] >= threshold + if len(y[left_indices]) > 0 and len(y[right_indices]) > 0: + left_mse = np.mean((y[left_indices] - np.mean(y[left_indices])) ** 2) + right_mse = np.mean((y[right_indices] - np.mean(y[right_indices])) ** 2) + mse = (len(y[left_indices]) * left_mse + len(y[right_indices]) * right_mse) / n_samples + + if mse < best_mse: + best_mse = mse + best_feature = feature + best_threshold = threshold + return best_feature, best_threshold + def predict(self, X): + return np.array([self._predict_sample(sample, self.tree) for sample in X]) + def _predict_sample(self, sample, node): + if isinstance(node, tuple): + feature, threshold, left_child, right_child = node + if sample[feature] < threshold: + return self._predict_sample(sample, left_child) + else: + return self._predict_sample(sample, right_child) + return node +class GradientBoostingRegressor: + def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3): + self.n_estimators = n_estimators + self.learning_rate = learning_rate + self.max_depth = max_depth + self.models = [] + def fit(self, X, y): + y_pred = np.zeros(y.shape) + for _ in range(self.n_estimators): + residuals = y - y_pred + model = DecisionTreeRegressor(max_depth=self.max_depth) + model.fit(X, residuals) + y_pred += self.learning_rate * model.predict(X) + self.models.append(model) + def predict(self, X): + y_pred = np.zeros(X.shape[0]) + for model in self.models: + y_pred += self.learning_rate * model.predict(X) + return y_pred +# Example usage +if __name__ == "__main__": + # Sample data + X = np.array([[1], [2], [3], [4], [5]]) + y = np.array([1.5, 1.7, 3.5, 3.7, 5.0]) + model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=2) + model.fit(X, y) + predictions = model.predict(X) + print("Predictions:", predictions) + +!ec - -o With a given kernel we can thus define the matrix $\bm{P}$. -o The matrix $\bm{P}$ has matrix elements $p_{ij}=y_iy_jK(\bm{x}_i,\bm{x}_j)$. Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. -o The vector $\bm{q}$ has all elements equal to $-1$. -o The constraint $\bm{y}^T\bm{\lambda}=0$ leads to $f=0$ and $\bm{A}=\bm{y}$. -o To set up the matrix $\bm{G}$ we 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 $\bm{G}$ and the vector $\bm{h}$. - -!split -===== Setting up $\bm{G}\bm{\lambda} \preceq \bm{h}$ ===== - -We have two constraints, $0\le \lambda_i$ and $\lambda_i \le C$. To do this we multiply the ones with the constraint -$\ge$ with $-1$ in order to get $\le$. It means that the problem $\bm{G}\bm{\lambda} \preceq \bm{h}$ -can be written as -!bt -\[ -\begin{bmatrix} -1& 0 & 0 & \dots & 0 \\ -0& -1 & 0 & \dots & 0 \\ -0& 0 & -1 & \dots & 0 \\ -\dots& \dots & \dots & \dots & \dots \\ -0& 0 & 0 & \dots & -1 \\ -1 & 0 & 0 & \dots & 0 \\ -0& 1 & 0 & \dots & 0 \\ -0& 0 & 1 & \dots & 0 \\ -\dots& \dots & \dots & \dots & \dots \\ -0& 0 & 0 & \dots & 1 \\ -\end{bmatrix} -\begin{bmatrix} \lambda_1 \\ -\lambda_2 \\ -\lambda_3 \\ -\dots \\ -\lambda_n \\ -\end{bmatrix} \preceq -\begin{bmatrix} 0 \\ -0 \\ -0 \\ -\dots \\ -0 \\ -C \\ -C \\ -C \\ -\dots \\ -C \\ -\end{bmatrix}. -\] -!et - -And then we are ready to go. - -!split -===== SVMs and Regression and multiclass classification ===== - -More text will be added here. See also "Hastie et al.":"https://www.springer.com/gp/book/9780387848570" section 12.3. - !split ===== Summary of course =====