From 53d95971294c8ebe977bfa631d526e76eb4d48fe Mon Sep 17 00:00:00 2001 From: mhjensen Date: Sat, 31 Oct 2020 23:22:24 +0100 Subject: [PATCH] update week 45 --- doc/pub/week45/html/._week45-bs000.html | 108 +++++----- doc/pub/week45/html/._week45-bs001.html | 150 ++++++-------- doc/pub/week45/html/._week45-bs002.html | 130 ++++++------ doc/pub/week45/html/._week45-bs003.html | 203 ++++++++----------- doc/pub/week45/html/._week45-bs004.html | 144 ++++++------- doc/pub/week45/html/._week45-bs005.html | 184 +++++++++++------ doc/pub/week45/html/._week45-bs006.html | 166 +++++++-------- doc/pub/week45/html/._week45-bs007.html | 134 ++++++------ doc/pub/week45/html/._week45-bs008.html | 170 ++++++++-------- doc/pub/week45/html/._week45-bs009.html | 146 +++++++------ doc/pub/week45/html/._week45-bs010.html | 152 ++++++++------ doc/pub/week45/html/._week45-bs011.html | 153 +++++++------- doc/pub/week45/html/._week45-bs012.html | 134 ++++++------ doc/pub/week45/html/._week45-bs013.html | 164 ++++++++------- doc/pub/week45/html/._week45-bs014.html | 143 +++++++------ doc/pub/week45/html/._week45-bs015.html | 154 +++++++------- doc/pub/week45/html/._week45-bs016.html | 138 +++++++------ doc/pub/week45/html/._week45-bs017.html | 146 ++++++------- doc/pub/week45/html/._week45-bs018.html | 125 ++++++------ doc/pub/week45/html/._week45-bs019.html | 143 +++++++------ doc/pub/week45/html/._week45-bs020.html | 120 ++++++----- doc/pub/week45/html/._week45-bs021.html | 176 +++++++--------- doc/pub/week45/html/._week45-bs022.html | 152 ++++++-------- doc/pub/week45/html/._week45-bs023.html | 167 +++++++++------ doc/pub/week45/html/._week45-bs024.html | 171 ++++++++-------- doc/pub/week45/html/._week45-bs025.html | 175 +++++++--------- doc/pub/week45/html/week45-bs.html | 108 +++++----- doc/pub/week45/html/week45-reveal.html | 139 +++++++------ doc/pub/week45/html/week45-solarized.html | 190 +++++++++-------- doc/pub/week45/html/week45.html | 190 +++++++++-------- doc/pub/week45/ipynb/ipynb-week45-src.tar.gz | Bin 196 -> 190 bytes doc/pub/week45/ipynb/week45.ipynb | 16 +- doc/src/week45/week45.do.txt | 14 ++ 33 files changed, 2364 insertions(+), 2241 deletions(-) diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index 716937c89..39586fc8c 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -195,7 +199,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Sep 16, 2020

+

Oct 31, 2020


@@ -219,7 +223,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs001.html b/doc/pub/week45/html/._week45-bs001.html index 8fe4f92a5..956dcdf9f 100644 --- a/doc/pub/week45/html/._week45-bs001.html +++ b/doc/pub/week45/html/._week45-bs001.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,46 +180,14 @@ MathJax.Hub.Config({ -

    Random forests

    +

    Overview of week 45

    -

    -Random forests provide an improvement over bagged trees by way of a -small tweak that decorrelates the trees. +

    -

    -As in bagging, we build a -number of decision trees on bootstrapped training samples. But when -building these decision trees, each time a split in a tree is -considered, a random sample of \( m \) predictors is chosen as split -candidates from the full set of \( p \) predictors. The split is allowed to -use only one of those \( m \) predictors. - -

    -A fresh sample of \( m \) predictors is -taken at each split, and typically we choose - -$$ -m\approx \sqrt{p}. -$$ - -

    -In building a random forest, at -each split in the tree, the algorithm is not even allowed to consider -a majority of the available predictors. - -

    -The reason for this is rather clever. Suppose that there is one very -strong predictor in the data set, along with a number of other -moderately strong predictors. Then in the collection of bagged -variable importance random forest trees, most or all of the trees will -use this strong predictor in the top split. Consequently, all of the -bagged trees will look quite similar to each other. Hence the -predictions from the bagged trees will be highly correlated. -Unfortunately, averaging many highly correlated quantities does not -lead to as large of a reduction in variance as averaging many -uncorrelated quantities. In particular, this means that bagging will -not lead to a substantial reduction in variance over a single tree in -this setting. +Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion.

    @@ -234,7 +206,7 @@ this setting.

  • 10
  • 11
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs002.html b/doc/pub/week45/html/._week45-bs002.html index 44fcf6c6a..4ef20a4f7 100644 --- a/doc/pub/week45/html/._week45-bs002.html +++ b/doc/pub/week45/html/._week45-bs002.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,30 +180,12 @@ MathJax.Hub.Config({ -

    Random Forest Algorithm

    -The algorithm described here can be applied to both classification and regression problems. +

    Thursday

    -We will grow of forest of say \( B \) trees. - -

      -
    1. For \( b=1:B \)
    2. - - - -
    3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
    4. -
    +Bagging, voting and random forests. +

    diff --git a/doc/pub/week45/html/._week45-bs003.html b/doc/pub/week45/html/._week45-bs003.html index 515520c4c..632efc707 100644 --- a/doc/pub/week45/html/._week45-bs003.html +++ b/doc/pub/week45/html/._week45-bs003.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,76 +180,47 @@ MathJax.Hub.Config({ -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Random forests

    +

    +Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import  train_test_split 
    -from sklearn.datasets import load_breast_cancer
    -from sklearn.svm import SVC
    -from sklearn.linear_model import LogisticRegression
    -from sklearn.tree import DecisionTreeClassifier
    +

    +As in bagging, we build a +number of decision trees on bootstrapped training samples. But when +building these decision trees, each time a split in a tree is +considered, a random sample of \( m \) predictors is chosen as split +candidates from the full set of \( p \) predictors. The split is allowed to +use only one of those \( m \) predictors. -# Load the data -cancer = load_breast_cancer() +

    +A fresh sample of \( m \) predictors is +taken at each split, and typically we choose -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) -print(X_train.shape) -print(X_test.shape) -# Logistic Regression -logreg = LogisticRegression(solver='lbfgs') -logreg.fit(X_train, y_train) -print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) -# Support vector machine -svm = SVC(gamma='auto', C=100) -svm.fit(X_train, y_train) -print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) -# Decision Trees -deep_tree_clf = DecisionTreeClassifier(max_depth=None) -deep_tree_clf.fit(X_train, y_train) -print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) -#now scale the data -from sklearn.preprocessing import StandardScaler -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) -# Logistic Regression -logreg.fit(X_train_scaled, y_train) -print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) -# Support Vector Machine -svm.fit(X_train_scaled, y_train) -print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) -# Decision Trees -deep_tree_clf.fit(X_train_scaled, y_train) -print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) +$$ +m\approx \sqrt{p}. +$$ +

    +In building a random forest, at +each split in the tree, the algorithm is not even allowed to consider +a majority of the available predictors. -from sklearn.ensemble import RandomForestClassifier -from sklearn.preprocessing import LabelEncoder -from sklearn.model_selection import cross_validate -# Data set not specificied -#Instantiate the model with 500 trees and entropy as splitting criteria -Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy") -Random_Forest_model.fit(X_train_scaled, y_train) -#Cross validation -accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score'] -print(accuracy) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test))) +

    +The reason for this is rather clever. Suppose that there is one very +strong predictor in the data set, along with a number of other +moderately strong predictors. Then in the collection of bagged +variable importance random forest trees, most or all of the trees will +use this strong predictor in the top split. Consequently, all of the +bagged trees will look quite similar to each other. Hence the +predictions from the bagged trees will be highly correlated. +Unfortunately, averaging many highly correlated quantities does not +lead to as large of a reduction in variance as averaging many +uncorrelated quantities. In particular, this means that bagging will +not lead to a substantial reduction in variance over a single tree in +this setting. - -import scikitplot as skplt -y_pred = Random_Forest_model.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) -plt.show() -y_probas = Random_Forest_model.predict_proba(X_test_scaled) -skplt.metrics.plot_roc(y_test, y_probas) -plt.show() -skplt.metrics.plot_cumulative_gain(y_test, y_probas) -plt.show() -

    @@ -265,7 +240,7 @@ plt.show()

  • 12
  • 13
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs004.html b/doc/pub/week45/html/._week45-bs004.html index e6c05eb01..87f861cbd 100644 --- a/doc/pub/week45/html/._week45-bs004.html +++ b/doc/pub/week45/html/._week45-bs004.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,26 +180,30 @@ MathJax.Hub.Config({ -

    Compare Bagging on Trees with Random Forests

    -

    +

    Random Forest Algorithm

    +The algorithm described here can be applied to both classification and regression problems. - -
    bag_clf = BaggingClassifier(
    -    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    -    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    -

    +We will grow of forest of say \( B \) trees. + +

      +
    1. For \( b=1:B \)
    2. + + + +
    3. Output then the ensemble of trees \( \{T_b\}_1^{B} \) and make predictions for either a regression type of problem or a classification type of problem.
    4. +
    - -
    bag_clf.fit(X_train, y_train)
    -y_pred = bag_clf.predict(X_test)
    -from sklearn.ensemble import RandomForestClassifier
    -rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
    -rnd_clf.fit(X_train, y_train)
    -y_pred_rf = rnd_clf.predict(X_test)
    -np.sum(y_pred == y_pred_rf) / len(y_pred) 
    -
    -

    diff --git a/doc/pub/week45/html/._week45-bs005.html b/doc/pub/week45/html/._week45-bs005.html index 76e049c98..00fe570d3 100644 --- a/doc/pub/week45/html/._week45-bs005.html +++ b/doc/pub/week45/html/._week45-bs005.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,20 +180,76 @@ MathJax.Hub.Config({ -

    Boosting, a Bird's Eye View

    - +

    Random Forests Compared with other Methods on the Cancer Data

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

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
    +from sklearn.svm import SVC
    +from sklearn.linear_model import LogisticRegression
    +from sklearn.tree import DecisionTreeClassifier
     
    +# Load the data
    +cancer = load_breast_cancer()
    +
    +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    +print(X_train.shape)
    +print(X_test.shape)
    +# Logistic Regression
    +logreg = LogisticRegression(solver='lbfgs')
    +logreg.fit(X_train, y_train)
    +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
    +# Support vector machine
    +svm = SVC(gamma='auto', C=100)
    +svm.fit(X_train, y_train)
    +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
    +# Decision Trees
    +deep_tree_clf = DecisionTreeClassifier(max_depth=None)
    +deep_tree_clf.fit(X_train, y_train)
    +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
    +#now scale the data
    +from sklearn.preprocessing import StandardScaler
    +scaler = StandardScaler()
    +scaler.fit(X_train)
    +X_train_scaled = scaler.transform(X_train)
    +X_test_scaled = scaler.transform(X_test)
    +# Logistic Regression
    +logreg.fit(X_train_scaled, y_train)
    +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Support Vector Machine
    +svm.fit(X_train_scaled, y_train)
    +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
    +# Decision Trees
    +deep_tree_clf.fit(X_train_scaled, y_train)
    +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
    +
    +
    +from sklearn.ensemble import RandomForestClassifier
    +from sklearn.preprocessing import LabelEncoder
    +from sklearn.model_selection import cross_validate
    +# Data set not specificied
    +#Instantiate the model with 500 trees and entropy as splitting criteria
    +Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
    +Random_Forest_model.fit(X_train_scaled, y_train)
    +#Cross validation
    +accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
    +
    +
    +import scikitplot as skplt
    +y_pred = Random_Forest_model.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = Random_Forest_model.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
    +

    @@ -211,7 +271,7 @@ them with a factor.

  • 14
  • 15
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs006.html b/doc/pub/week45/html/._week45-bs006.html index ee183170e..c2ecc1c69 100644 --- a/doc/pub/week45/html/._week45-bs006.html +++ b/doc/pub/week45/html/._week45-bs006.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,55 +180,25 @@ MathJax.Hub.Config({ -

    What is boosting? Additive Modelling/Iterative Fitting

    - +

    Compare Bagging on Trees with Random Forests

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

    bag_clf = BaggingClassifier(
    +    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    +    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    +

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

    bag_clf.fit(X_train, y_train)
    +y_pred = bag_clf.predict(X_test)
    +from sklearn.ensemble import RandomForestClassifier
    +rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
    +rnd_clf.fit(X_train, y_train)
    +y_pred_rf = rnd_clf.predict(X_test)
    +np.sum(y_pred == y_pred_rf) / len(y_pred) 
    +

    @@ -247,7 +221,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re

  • 15
  • 16
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs007.html b/doc/pub/week45/html/._week45-bs007.html index c48865fdd..e6718368e 100644 --- a/doc/pub/week45/html/._week45-bs007.html +++ b/doc/pub/week45/html/._week45-bs007.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,27 +180,19 @@ MathJax.Hub.Config({ -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Boosting, a Bird's Eye View

    -The way we proceed is as follows (here we specialize to the squared-error cost function) +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. -

      -
    1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
    2. -
    3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    4. -
    5. For \( m=1:M \) - -
        -
      1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
      2. -
      3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      4. -
      5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      6. -
      - -
    - -We could use any of the algorithms we have discussed till now. If we -use trees, \( \gamma \) parameterizes the split variables and split points -at the internal nodes, and the predictions at the terminal nodes. +

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

    @@ -221,7 +217,7 @@ at the internal nodes, and the predictions at the terminal nodes.

  • 16
  • 17
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs008.html b/doc/pub/week45/html/._week45-bs008.html index 37f771c24..23e5346ec 100644 --- a/doc/pub/week45/html/._week45-bs008.html +++ b/doc/pub/week45/html/._week45-bs008.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,50 +180,54 @@ MathJax.Hub.Config({ -

    Squared-Error Example and Iterative Fitting

    +

    What is boosting? Additive Modelling/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 - +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 $$ -(\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. +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$

    -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, -$$ +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 \). -and -$$ -\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0. -$$ +

    +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 -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, +\sigma(t) = \frac{1}{1+\exp{(-t)}}, $$

    -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. +where \( t=\gamma_0+\gamma_1 x \) and the parameters \( \gamma_0 \) and +\( \gamma_1 \) were determined by the Logistic Regression fitting +algorithm.

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

    @@ -245,7 +253,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma

  • 17
  • 18
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs009.html b/doc/pub/week45/html/._week45-bs009.html index c4a2cbce4..0f97fde2c 100644 --- a/doc/pub/week45/html/._week45-bs009.html +++ b/doc/pub/week45/html/._week45-bs009.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,37 +180,27 @@ MathJax.Hub.Config({ -

    Iterative Fitting, Classification and AdaBoost

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    -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 way we proceed is as follows (here we specialize to the squared-error cost function) -

    -The error rate of the training sample is then +

      +
    1. Establish a cost function, here \( {\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2 \) with \( f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m) \).
    2. +
    3. Initialize with a guess \( f_0(x) \). It could be one or even zero or some random numbers.
    4. +
    5. For \( m=1:M \) -$$ -\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). -$$ +
        +
      1. minimize \( \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2 \) wrt \( \gamma \) and \( \beta \)
      2. +
      3. This gives the optimal values \( \beta_m \) and \( \gamma_m \)
      4. +
      5. Determine then the new values \( f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m) \)
      6. +
      -

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

    @@ -233,7 +227,7 @@ $$

  • 18
  • 19
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs010.html b/doc/pub/week45/html/._week45-bs010.html index a7b170f5d..1718a9eaa 100644 --- a/doc/pub/week45/html/._week45-bs010.html +++ b/doc/pub/week45/html/._week45-bs010.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,30 +180,50 @@ MathJax.Hub.Config({ -

    Adaptive Boosting, AdaBoost

    +

    Squared-Error Example and Iterative Fitting

    -In our iterative procedure we define thus +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 + $$ -f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +(\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. $$

    -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 +We start our iteration by simply setting \( f_0(x)=0 \). +Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain $$ -C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. +\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, $$

    -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 +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. -$$ -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))} \). +

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

    @@ -227,7 +251,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

  • 19
  • 20
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs011.html b/doc/pub/week45/html/._week45-bs011.html index b38b17e47..2cf347720 100644 --- a/doc/pub/week45/html/._week45-bs011.html +++ b/doc/pub/week45/html/._week45-bs011.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,45 +180,36 @@ MathJax.Hub.Config({ -

    Building up AdaBoost

    +

    Iterative Fitting, Classification and 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 \). +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\} \).

    -We can do this by rewriting +The error rate of the training sample is then + $$ -\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m, +\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)). $$ -which can be rewritten as +

    +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 $$ -(\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, +f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m), $$ -which leads to +will be a function of $$ -\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))} +G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x). $$

    @@ -243,7 +238,7 @@ $$

  • 20
  • 21
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs012.html b/doc/pub/week45/html/._week45-bs012.html index f0cae321d..39ae61561 100644 --- a/doc/pub/week45/html/._week45-bs012.html +++ b/doc/pub/week45/html/._week45-bs012.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,24 +180,30 @@ MathJax.Hub.Config({ -

    Adaptive boosting: AdaBoost, Basic Algorithm

    +

    Adaptive Boosting, AdaBoost

    -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} \). +In our iterative procedure we define thus +$$ +f_m(x) = f_{m-1}(x)+\beta_mG_m(x). +$$

    -We have already defined the misclassification error \( \mathrm{err} \) as +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 $$ -\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)), +C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}. $$ -where the function \( I() \) is one if we misclassify and zero if we classify correctly. +

    +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))} \).

    @@ -221,7 +231,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co

  • 21
  • 22
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs013.html b/doc/pub/week45/html/._week45-bs013.html index 52c5bcdef..3d6b09011 100644 --- a/doc/pub/week45/html/._week45-bs013.html +++ b/doc/pub/week45/html/._week45-bs013.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,42 +180,46 @@ MathJax.Hub.Config({ -

    Basic Steps of AdaBoost

    +

    Building up 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. -
    - +First, for any \( \beta > 0 \), we optimize \( G \) by setting $$ -\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}, +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 \). -
      -
    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. +

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

        -
      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. -
      +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, +$$ -
    2. Compute the new classifier \( G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i) \).
    3. -
    +which leads to +$$ +\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}}, +$$ -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. +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))} +$$

    @@ -239,7 +247,7 @@ observations that are missed in the previous iterations.

  • 22
  • 23
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs014.html b/doc/pub/week45/html/._week45-bs014.html index 6120f1db4..6700fb44c 100644 --- a/doc/pub/week45/html/._week45-bs014.html +++ b/doc/pub/week45/html/._week45-bs014.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,36 +180,25 @@ MathJax.Hub.Config({ -

    AdaBoost Examples

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    -Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. +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)), +$$ - -

    from sklearn.ensemble import AdaBoostClassifier
    +where the function \( I() \) is one if we misclassify and zero if we classify correctly.
     
    -ada_clf = AdaBoostClassifier(
    -    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    -    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    -ada_clf.fit(X_train, y_train)
    -
    -from sklearn.ensemble import AdaBoostClassifier
    -
    -ada_clf = AdaBoostClassifier(
    -    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    -    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    -ada_clf.fit(X_train_scaled, y_train)
    -y_pred = ada_clf.predict(X_test_scaled)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -plt.show()
    -y_probas = ada_clf.predict_proba(X_test_scaled)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    -plt.show()
    -

    @@ -232,7 +225,7 @@ plt.show()

  • 23
  • 24
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs015.html b/doc/pub/week45/html/._week45-bs015.html index 28a1bdc2b..567db5dd8 100644 --- a/doc/pub/week45/html/._week45-bs015.html +++ b/doc/pub/week45/html/._week45-bs015.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,30 +180,42 @@ MathJax.Hub.Config({ -

    AdaBoost for Regression

    +

    Basic Steps of AdaBoost

    -Here we present Drucker's AdaBoost tailored for regression. - -

    -In bagging, each training example is equally likely to be -picked. In boosting, the probability of a particular -example being in the training set of a particular machine -depends on the performance of the prior machines on -that example. The following is a modification of -Adaboost by Drucker. - -

    -Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: +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 define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
    2. -
    3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
    4. -
    5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
    6. -
    7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
    8. +
    9. 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 \).
    10. +
    11. We rewrite the misclassification error as
    -\( L_i\in [0,1] \). +$$ +\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.

    @@ -227,7 +243,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei

  • 24
  • 25
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs016.html b/doc/pub/week45/html/._week45-bs016.html index d1797d35e..997772367 100644 --- a/doc/pub/week45/html/._week45-bs016.html +++ b/doc/pub/week45/html/._week45-bs016.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,18 +180,36 @@ MathJax.Hub.Config({ -

    Gradient boosting: Basics with Steepest Descent

    +

    AdaBoost Examples

    -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. +Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.

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

    from sklearn.ensemble import AdaBoostClassifier
    +
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    +ada_clf.fit(X_train, y_train)
    +
    +from sklearn.ensemble import AdaBoostClassifier
    +
    +ada_clf = AdaBoostClassifier(
    +    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    +    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
    +ada_clf.fit(X_train_scaled, y_train)
    +y_pred = ada_clf.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +plt.show()
    +y_probas = ada_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +plt.show()
    +

    @@ -213,6 +235,8 @@ function was the least squares function.

  • 24
  • 25
  • 26
  • +
  • ...
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs017.html b/doc/pub/week45/html/._week45-bs017.html index 203a1995d..d126baf39 100644 --- a/doc/pub/week45/html/._week45-bs017.html +++ b/doc/pub/week45/html/._week45-bs017.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,37 +180,30 @@ MathJax.Hub.Config({ -

    The Squared-Error again! Steepest Descent

    +

    AdaBoost for Regression

    -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. -$$ +Here we present Drucker's AdaBoost tailored for regression.

    -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 bagging, each training example is equally likely to be +picked. In boosting, the probability of a particular +example being in the training set of a particular machine +depends on the performance of the prior machines on +that example. The following is a modification of +Adaboost by Drucker.

    -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)}. -$$ +Start by selecting a set of training data \( n \) and assign to each entry a weight \( w_i=1 \) for \( i=1,2,\dots,n \). As we have done earlier, we could pick say \( 80\% \) of the data set for training. The algorithm runs as follows: -

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

      +
    1. We define the probability that the training sample \( i \) is in the set by \( p_i = w_i/\sum_iw_i \). We pick \( n \) samples (with replacement) to form our training set. We pick a number uniformly in the range \( [0,\sum_iw_i] \).
    2. +
    3. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
    4. +
    5. Using every member of the training set with the chosen regression machine we obtain then a prediction \( \tilde{y}_i \).
    6. +
    7. We calculate then the loss function \( L_i \) for each training sample. We can use various types of loss function as long as we have a value
    8. +
    -

    -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. -$$ +\( L_i\in [0,1] \).

    @@ -232,6 +229,9 @@ $$

  • 24
  • 25
  • 26
  • +
  • 27
  • +
  • ...
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs018.html b/doc/pub/week45/html/._week45-bs018.html index 07af08aba..2bf3230a3 100644 --- a/doc/pub/week45/html/._week45-bs018.html +++ b/doc/pub/week45/html/._week45-bs018.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,20 +180,17 @@ MathJax.Hub.Config({ -

    Steepest Descent Example

    +

    Gradient boosting: Basics with Steepest Descent

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

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

    @@ -214,6 +215,8 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(

  • 24
  • 25
  • 26
  • +
  • 27
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs019.html b/doc/pub/week45/html/._week45-bs019.html index 5afb58198..4c4ba244a 100644 --- a/doc/pub/week45/html/._week45-bs019.html +++ b/doc/pub/week45/html/._week45-bs019.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,30 +180,39 @@ MathJax.Hub.Config({ -

    Gradient Boosting, algorithm

    +

    The Squared-Error again! Steepest Descent

    -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 +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 + $$ -C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2. $$

    -The way we proceed in an iterative fashion is to +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). +$$ -

      -
    1. Initialize our estimate \( f_0(x) \).
    2. -
    3. For \( m=1:M \), we +

      +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)}. +$$ -

        -
      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
      2. -
      3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      4. -
      5. update the estimate \( f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x) \);
      6. -
      +

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

    4. The final estimate is then \( f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x) \).
    5. -
    +

    +Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have +$$ +(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2. +$$ +

    diff --git a/doc/pub/week45/html/._week45-bs020.html b/doc/pub/week45/html/._week45-bs020.html index 56c7c37d7..280b59923 100644 --- a/doc/pub/week45/html/._week45-bs020.html +++ b/doc/pub/week45/html/._week45-bs020.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,10 +180,20 @@ MathJax.Hub.Config({ -

    Gradient Boosting Example, Regression

    +

    Steepest Descent Example

    -We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. +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.

    @@ -202,6 +216,8 @@ We discuss here the difference between the steepest descent approach and gradien

  • 24
  • 25
  • 26
  • +
  • 27
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs021.html b/doc/pub/week45/html/._week45-bs021.html index 132a5d245..4b8e814e5 100644 --- a/doc/pub/week45/html/._week45-bs021.html +++ b/doc/pub/week45/html/._week45-bs021.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,58 +180,30 @@ MathJax.Hub.Config({ -

    Gradient Boosting, Examples of Regression

    +

    Gradient Boosting, algorithm

    +

    +Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function +$$ +C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2. +$$ - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import train_test_split
    -from sklearn.ensemble import GradientBoostingRegressor
    -from sklearn.preprocessing import StandardScaler
    -import scikitplot as skplt
    -from sklearn.metrics import mean_squared_error
    -
    -n = 100
    -maxdegree = 6
    -
    -# Make data set.
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -
    -error = np.zeros(maxdegree)
    -bias = np.zeros(maxdegree)
    -variance = np.zeros(maxdegree)
    -polydegree = np.zeros(maxdegree)
    -X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -
    -for degree in range(1,maxdegree):
    -    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
    -    model.fit(X_train_scaled,y_train)
    -    y_pred = model.predict(X_test_scaled)
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    -    variance[degree] = np.mean( np.var(y_pred) )
    -    print('Max depth:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.xlim(1,maxdegree-1)
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -save_fig("gdregression")
    -plt.show()
    -

    +The way we proceed in an iterative fashion is to + +

      +
    1. Initialize our estimate \( f_0(x) \).
    2. +
    3. For \( m=1:M \), we + +
        +
      1. compute the negative gradient vector \( \boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x) \) at \( f(x) = f_{m-1}(x) \);
      2. +
      3. fit the so-called base-learner to the negative gradient \( h_m(u_m,x) \);
      4. +
      5. update the estimate \( f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x) \);
      6. +
      + +
    4. The final estimate is then \( f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x) \).
    5. +
    +

    diff --git a/doc/pub/week45/html/._week45-bs022.html b/doc/pub/week45/html/._week45-bs022.html index 51c974b7a..1dde295c0 100644 --- a/doc/pub/week45/html/._week45-bs022.html +++ b/doc/pub/week45/html/._week45-bs022.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,51 +180,11 @@ MathJax.Hub.Config({ -

    Gradient Boosting, Classification Example

    +

    Gradient Boosting Example, Regression

    +

    +We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import  train_test_split 
    -from sklearn.datasets import load_breast_cancer
    -import scikitplot as skplt
    -from sklearn.ensemble import GradientBoostingClassifier
    -from sklearn.model_selection import cross_validate
    -
    -# Load the data
    -cancer = load_breast_cancer()
    -
    -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    -print(X_train.shape)
    -print(X_test.shape)
    -#now scale the data
    -from sklearn.preprocessing import StandardScaler
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -
    -gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
    -gd_clf.fit(X_train_scaled, y_train)
    -#Cross validation
    -accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
    -print(accuracy)
    -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
    -
    -import scikitplot as skplt
    -y_pred = gd_clf.predict(X_test_scaled)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -save_fig("gdclassiffierconfusion")
    -plt.show()
    -y_probas = gd_clf.predict_proba(X_test_scaled)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -save_fig("gdclassiffierroc")
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    -save_fig("gdclassiffiercgain")
    -plt.show()
    -

    @@ -240,6 +204,8 @@ plt.show()

  • 24
  • 25
  • 26
  • +
  • 27
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs023.html b/doc/pub/week45/html/._week45-bs023.html index d95a816cf..fe2eac04a 100644 --- a/doc/pub/week45/html/._week45-bs023.html +++ b/doc/pub/week45/html/._week45-bs023.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,24 +180,57 @@ MathJax.Hub.Config({ -

    XGBoost: Extreme Gradient Boosting

    - +

    Gradient Boosting, Examples of Regression

    -XGBoost or Extreme Gradient -Boosting, is an optimized distributed gradient boosting library -designed to be highly efficient, flexible and portable. It implements -machine learning algorithms under the Gradient Boosting -framework. XGBoost provides a parallel tree boosting that solve many -data science problems in a fast and accurate way. See the article by Chen and Guestrin. -

    -The authors design and build a highly scalable end-to-end tree -boosting system. It has a theoretically justified weighted quantile -sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.model_selection import train_test_split
    +from sklearn.ensemble import GradientBoostingRegressor
    +from sklearn.preprocessing import StandardScaler
    +import scikitplot as skplt
    +from sklearn.metrics import mean_squared_error
     
    -

    -It is now the algorithm which wins essentially all ML competitions!!! +n = 100 +maxdegree = 6 +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) + +error = np.zeros(maxdegree) +bias = np.zeros(maxdegree) +variance = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +for degree in range(1,maxdegree): + model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) + model.fit(X_train_scaled,y_train) + y_pred = model.predict(X_test_scaled) + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) + variance[degree] = np.mean( np.var(y_pred) ) + print('Max depth:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.xlim(1,maxdegree-1) +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +save_fig("gdregression") +plt.show() +

    @@ -212,6 +249,8 @@ It is now the algorithm which wins essentially all ML competitions!!!

  • 24
  • 25
  • 26
  • +
  • 27
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs024.html b/doc/pub/week45/html/._week45-bs024.html index 3064e1287..1fd29fa6d 100644 --- a/doc/pub/week45/html/._week45-bs024.html +++ b/doc/pub/week45/html/._week45-bs024.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,56 +180,49 @@ MathJax.Hub.Config({ -

    Regression Case

    - +

    Gradient Boosting, Classification Example

    import matplotlib.pyplot as plt
     import numpy as np
    -from sklearn.model_selection import train_test_split
    -import xgboost as xgb
    -from sklearn.preprocessing import StandardScaler
    +from sklearn.model_selection import  train_test_split 
    +from sklearn.datasets import load_breast_cancer
     import scikitplot as skplt
    -from sklearn.metrics import mean_squared_error
    +from sklearn.ensemble import GradientBoostingClassifier
    +from sklearn.model_selection import cross_validate
     
    -n = 100
    -maxdegree = 6
    +# Load the data
    +cancer = load_breast_cancer()
     
    -# 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)
    +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)
     
    -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)
    +gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
    +gd_clf.fit(X_train_scaled, y_train)
    +#Cross validation
    +accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
    +print(accuracy)
    +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
     
    -    model.fit(X_train_scaled,y_train)
    -    y_pred = model.predict(X_test_scaled)
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    -    variance[degree] = np.mean( np.var(y_pred) )
    -    print('Max depth:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.xlim(1,maxdegree-1)
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    +import scikitplot as skplt
    +y_pred = gd_clf.predict(X_test_scaled)
    +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    +save_fig("gdclassiffierconfusion")
    +plt.show()
    +y_probas = gd_clf.predict_proba(X_test_scaled)
    +skplt.metrics.plot_roc(y_test, y_probas)
    +save_fig("gdclassiffierroc")
    +plt.show()
    +skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    +save_fig("gdclassiffiercgain")
     plt.show()
     

    @@ -245,6 +242,8 @@ plt.show()

  • 24
  • 25
  • 26
  • +
  • 27
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/._week45-bs025.html b/doc/pub/week45/html/._week45-bs025.html index ef1498738..bd18e3ec4 100644 --- a/doc/pub/week45/html/._week45-bs025.html +++ b/doc/pub/week45/html/._week45-bs025.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -176,67 +180,25 @@ MathJax.Hub.Config({ -

    Xgboost on the Cancer Data

    +

    XGBoost: Extreme Gradient Boosting

    -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. +XGBoost or Extreme Gradient +Boosting, is an optimized distributed gradient boosting library +designed to be highly efficient, flexible and portable. It implements +machine learning algorithms under the Gradient Boosting +framework. XGBoost provides a parallel tree boosting that solve many +data science problems in a fast and accurate way. See the article by Chen and Guestrin. +

    +The authors design and build a highly scalable end-to-end tree +boosting system. It has a theoretically justified weighted quantile +sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning. - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.model_selection import  train_test_split 
    -from sklearn.datasets import load_breast_cancer
    -from sklearn.preprocessing import LabelEncoder
    -from sklearn.model_selection import cross_validate
    -import scikitplot as skplt
    -import xgboost as xgb
    -# Load the data
    -cancer = load_breast_cancer()
    -
    -X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
    -print(X_train.shape)
    -print(X_test.shape)
    -#now scale the data
    -from sklearn.preprocessing import StandardScaler
    -scaler = StandardScaler()
    -scaler.fit(X_train)
    -X_train_scaled = scaler.transform(X_train)
    -X_test_scaled = scaler.transform(X_test)
    -
    -xg_clf = xgb.XGBClassifier()
    -xg_clf.fit(X_train_scaled,y_train)
    -
    -y_test = xg_clf.predict(X_test_scaled)
    -
    -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
    -
    -import scikitplot as skplt
    -y_pred = xg_clf.predict(X_test_scaled)
    -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
    -save_fig("xdclassiffierconfusion")
    -plt.show()
    -y_probas = xg_clf.predict_proba(X_test_scaled)
    -skplt.metrics.plot_roc(y_test, y_probas)
    -save_fig("xdclassiffierroc")
    -plt.show()
    -skplt.metrics.plot_cumulative_gain(y_test, y_probas)
    -save_fig("gdclassiffiercgain")
    -plt.show()
    -
    -
    -xgb.plot_tree(xg_clf,num_trees=0)
    -plt.rcParams['figure.figsize'] = [50, 10]
    -save_fig("xgtree")
    -plt.show()
    -
    -xgb.plot_importance(xg_clf)
    -plt.rcParams['figure.figsize'] = [5, 5]
    -save_fig("xgparams")
    -plt.show()
    -

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

    diff --git a/doc/pub/week45/html/week45-bs.html b/doc/pub/week45/html/week45-bs.html index 716937c89..39586fc8c 100644 --- a/doc/pub/week45/html/week45-bs.html +++ b/doc/pub/week45/html/week45-bs.html @@ -41,64 +41,66 @@ Automatically generated HTML file from DocOnce source @@ -136,31 +138,33 @@ MathJax.Hub.Config({ @@ -195,7 +199,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Sep 16, 2020

    +

    Oct 31, 2020


    @@ -219,7 +223,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 26
  • +
  • 28
  • »
  • diff --git a/doc/pub/week45/html/week45-reveal.html b/doc/pub/week45/html/week45-reveal.html index 6a1390336..185bba217 100644 --- a/doc/pub/week45/html/week45-reveal.html +++ b/doc/pub/week45/html/week45-reveal.html @@ -148,7 +148,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

     
    -

    Sep 16, 2020

    +

    Oct 31, 2020


    @@ -159,7 +159,28 @@ MathJax.Hub.Config({

    -

    Random forests

    +

    Overview of week 45

    + + +

    + +Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion. +

    + + +
    +

    Thursday

    + +

    +Bagging, voting and random forests. +

    + + +
    +

    Random forests

    Random forests provide an improvement over bagged trees by way of a @@ -205,7 +226,7 @@ this setting.

    -

    Random Forest Algorithm

    +

    Random Forest Algorithm

    The algorithm described here can be applied to both classification and regression problems.

    @@ -236,7 +257,7 @@ We will grow of forest of say \( B \) trees.

    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -252,20 +273,20 @@ We will grow of forest of say \( B \) trees. 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) +print(X_train.shape) +print(X_test.shape) # Logistic Regression logreg = LogisticRegression(solver='lbfgs') logreg.fit(X_train, y_train) -print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) # Support vector machine svm = SVC(gamma='auto', C=100) svm.fit(X_train, y_train) -print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) # Decision Trees -deep_tree_clf = DecisionTreeClassifier(max_depth=None) +deep_tree_clf = DecisionTreeClassifier(max_depth=None) deep_tree_clf.fit(X_train, y_train) -print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -274,13 +295,13 @@ X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) # Logistic Regression logreg.fit(X_train_scaled, y_train) -print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) # Support Vector Machine svm.fit(X_train_scaled, y_train) -print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) # Decision Trees deep_tree_clf.fit(X_train_scaled, y_train) -print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) from sklearn.ensemble import RandomForestClassifier @@ -292,13 +313,13 @@ Random_Forest_model = RandomForestClassifier(n_estimators=#Cross validation accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score'] -print(accuracy) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test))) +print(accuracy) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = Random_Forest_model.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) plt.show() y_probas = Random_Forest_model.predict_proba(X_test_scaled) skplt.metrics.plot_roc(y_test, y_probas) @@ -310,13 +331,13 @@ plt.show()

    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    bag_clf = BaggingClassifier(
         DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    -    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    +    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
     

    @@ -333,7 +354,7 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)

    -

    Boosting, a Bird's Eye View

    +

    Boosting, a Bird's Eye View

    The basic idea is to combine weak classifiers in order to create a good @@ -350,7 +371,7 @@ them with a factor.

    -

    What is boosting? Additive Modelling/Iterative Fitting

    +

    What is boosting? Additive Modelling/Iterative Fitting

    Boosting is a way of fitting an additive expansion in a set of @@ -410,7 +431,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re

    -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    The way we proceed is as follows (here we specialize to the squared-error cost function) @@ -436,7 +457,7 @@ at the internal nodes, and the predictions at the terminal nodes.

    -

    Squared-Error Example and Iterative Fitting

    +

    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. @@ -494,7 +515,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma

    -

    Iterative Fitting, Classification and AdaBoost

    +

    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 @@ -535,7 +556,7 @@ $$

    -

    Adaptive Boosting, AdaBoost

    +

    Adaptive Boosting, AdaBoost

    In our iterative procedure we define thus @@ -569,7 +590,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).

    -

    Building up AdaBoost

    +

    Building up AdaBoost

    First, for any \( \beta > 0 \), we optimize \( G \) by setting @@ -627,7 +648,7 @@ $$

    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    The algorithm here is rather straightforward. Assume that our weak @@ -651,7 +672,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co

    -

    Basic Steps of AdaBoost

    +

    Basic Steps of AdaBoost

    With the above definitions we are now ready to set up the algorithm for AdaBoost. @@ -692,7 +713,7 @@ observations that are missed in the previous iterations.

    -

    AdaBoost Examples

    +

    AdaBoost Examples

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. @@ -714,7 +735,7 @@ ada_clf = AdaBoostClassifier( algorithm="SAMME.R", learning_rate=0.5, random_state=42) ada_clf.fit(X_train_scaled, y_train) y_pred = ada_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) plt.show() y_probas = ada_clf.predict_proba(X_test_scaled) skplt.metrics.plot_roc(y_test, y_probas) @@ -726,7 +747,7 @@ plt.show()

    -

    AdaBoost for Regression

    +

    AdaBoost for Regression

    Here we present Drucker's AdaBoost tailored for regression. @@ -755,7 +776,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei

    -

    Gradient boosting: Basics with Steepest Descent

    +

    Gradient boosting: Basics with Steepest Descent

    Gradient boosting is again a similar technique to Adaptive boosting, @@ -770,7 +791,7 @@ function was the least squares function.

    -

    The Squared-Error again! Steepest Descent

    +

    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 @@ -813,7 +834,7 @@ $$

    -

    Steepest Descent Example

    +

    Steepest Descent Example

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that @@ -835,7 +856,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(

    -

    Gradient Boosting, algorithm

    +

    Gradient Boosting, algorithm

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function @@ -863,7 +884,7 @@ The way we proceed in an iterative fashion is to

    -

    Gradient Boosting Example, Regression

    +

    Gradient Boosting Example, Regression

    We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. @@ -871,7 +892,7 @@ We discuss here the difference between the steepest descent approach and gradien

    -

    Gradient Boosting, Examples of Regression

    +

    Gradient Boosting, Examples of Regression

    @@ -908,11 +929,11 @@ X_test_scaled = scaler.transform(X_test) 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])) + 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') @@ -926,7 +947,7 @@ plt.show()

    -

    Gradient Boosting, Classification Example

    +

    Gradient Boosting, Classification Example

    @@ -942,8 +963,8 @@ plt.show() 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) +print(X_train.shape) +print(X_test.shape) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -955,12 +976,12 @@ gd_clf = GradientBoostingClassifier(max_depth=3#Cross validation accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score'] -print(accuracy) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test))) +print(accuracy) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = gd_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) save_fig("gdclassiffierconfusion") plt.show() y_probas = gd_clf.predict_proba(X_test_scaled) @@ -975,7 +996,7 @@ plt.show()

    -

    XGBoost: Extreme Gradient Boosting

    +

    XGBoost: Extreme Gradient Boosting

    XGBoost or Extreme Gradient @@ -996,7 +1017,7 @@ It is now the algorithm which wins essentially all ML competitions!!!

    -

    Regression Case

    +

    Regression Case

    @@ -1035,11 +1056,11 @@ X_test_scaled = scaler.transform(X_test) 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])) + 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') @@ -1052,7 +1073,7 @@ plt.show()

    -

    Xgboost on the Cancer Data

    +

    Xgboost on the Cancer Data

    As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. @@ -1071,8 +1092,8 @@ As you will see from the confusion matrix below, XGBoots does an excellent job o 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) +print(X_train.shape) +print(X_test.shape) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -1085,11 +1106,11 @@ xg_clf.fit(X_train_scaled,y_train) y_test = xg_clf.predict(X_test_scaled) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = xg_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +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) diff --git a/doc/pub/week45/html/week45-solarized.html b/doc/pub/week45/html/week45-solarized.html index d1277cffd..43e4bfa95 100644 --- a/doc/pub/week45/html/week45-solarized.html +++ b/doc/pub/week45/html/week45-solarized.html @@ -35,64 +35,66 @@ div { text-align: justify; text-justify: inter-word; } @@ -134,12 +136,32 @@ MathJax.Hub.Config({

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

    -

    Sep 16, 2020

    +

    Oct 31, 2020












    -

    Random forests

    +

    Overview of week 45

    + +
      +
    • "Thursday: Wrapping up from last week. Bagging and Random forests.
    • +
    • "Friday: Boosting and gradient boosting
    • +
    + +Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion. + +

    +









    + +

    Thursday

    + +

    +Bagging, voting and random forests. + +

    +









    + +

    Random forests

    Random forests provide an improvement over bagged trees by way of a @@ -183,7 +205,7 @@ this setting.











    -

    Random Forest Algorithm

    +

    Random Forest Algorithm

    The algorithm described here can be applied to both classification and regression problems.

    @@ -209,7 +231,7 @@ We will grow of forest of say \( B \) trees.









    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -225,20 +247,20 @@ We will grow of forest of say \( B \) trees. 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) +print(X_train.shape) +print(X_test.shape) # Logistic Regression logreg = LogisticRegression(solver='lbfgs') logreg.fit(X_train, y_train) -print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) # Support vector machine svm = SVC(gamma='auto', C=100) svm.fit(X_train, y_train) -print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) # Decision Trees -deep_tree_clf = DecisionTreeClassifier(max_depth=None) +deep_tree_clf = DecisionTreeClassifier(max_depth=None) deep_tree_clf.fit(X_train, y_train) -print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -247,13 +269,13 @@ X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) # Logistic Regression logreg.fit(X_train_scaled, y_train) -print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) # Support Vector Machine svm.fit(X_train_scaled, y_train) -print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) # Decision Trees deep_tree_clf.fit(X_train_scaled, y_train) -print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) from sklearn.ensemble import RandomForestClassifier @@ -265,13 +287,13 @@ Random_Forest_model = RandomForestClassifier(n_estimators=#Cross validation accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score'] -print(accuracy) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test))) +print(accuracy) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = Random_Forest_model.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) plt.show() y_probas = Random_Forest_model.predict_proba(X_test_scaled) skplt.metrics.plot_roc(y_test, y_probas) @@ -282,13 +304,13 @@ plt.show()











    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    bag_clf = BaggingClassifier(
         DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    -    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    +    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
     

    @@ -304,7 +326,7 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)











    -

    Boosting, a Bird's Eye View

    +

    Boosting, a Bird's Eye View

    The basic idea is to combine weak classifiers in order to create a good @@ -321,7 +343,7 @@ them with a factor.











    -

    What is boosting? Additive Modelling/Iterative Fitting

    +

    What is boosting? Additive Modelling/Iterative Fitting

    Boosting is a way of fitting an additive expansion in a set of @@ -373,7 +395,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re











    -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    The way we proceed is as follows (here we specialize to the squared-error cost function) @@ -398,7 +420,7 @@ at the internal nodes, and the predictions at the terminal nodes.











    -

    Squared-Error Example and Iterative Fitting

    +

    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. @@ -446,7 +468,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma











    -

    Iterative Fitting, Classification and AdaBoost

    +

    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 @@ -481,7 +503,7 @@ $$











    -

    Adaptive Boosting, AdaBoost

    +

    Adaptive Boosting, AdaBoost

    In our iterative procedure we define thus @@ -509,7 +531,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).











    -

    Building up AdaBoost

    +

    Building up AdaBoost

    First, for any \( \beta > 0 \), we optimize \( G \) by setting @@ -553,7 +575,7 @@ $$











    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    The algorithm here is rather straightforward. Assume that our weak @@ -575,7 +597,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co











    -

    Basic Steps of AdaBoost

    +

    Basic Steps of AdaBoost

    With the above definitions we are now ready to set up the algorithm for AdaBoost. @@ -615,7 +637,7 @@ observations that are missed in the previous iterations.











    -

    AdaBoost Examples

    +

    AdaBoost Examples

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. @@ -637,7 +659,7 @@ ada_clf = AdaBoostClassifier( algorithm="SAMME.R", learning_rate=0.5, random_state=42) ada_clf.fit(X_train_scaled, y_train) y_pred = ada_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) plt.show() y_probas = ada_clf.predict_proba(X_test_scaled) skplt.metrics.plot_roc(y_test, y_probas) @@ -648,7 +670,7 @@ plt.show()











    -

    AdaBoost for Regression

    +

    AdaBoost for Regression

    Here we present Drucker's AdaBoost tailored for regression. @@ -676,7 +698,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei











    -

    Gradient boosting: Basics with Steepest Descent

    +

    Gradient boosting: Basics with Steepest Descent

    Gradient boosting is again a similar technique to Adaptive boosting, @@ -691,7 +713,7 @@ function was the least squares function.











    -

    The Squared-Error again! Steepest Descent

    +

    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 @@ -726,7 +748,7 @@ $$











    -

    Steepest Descent Example

    +

    Steepest Descent Example

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that @@ -744,7 +766,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(











    -

    Gradient Boosting, algorithm

    +

    Gradient Boosting, algorithm

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function @@ -770,7 +792,7 @@ The way we proceed in an iterative fashion is to









    -

    Gradient Boosting Example, Regression

    +

    Gradient Boosting Example, Regression

    We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. @@ -778,7 +800,7 @@ We discuss here the difference between the steepest descent approach and gradien











    -

    Gradient Boosting, Examples of Regression

    +

    Gradient Boosting, Examples of Regression

    @@ -815,11 +837,11 @@ X_test_scaled = scaler.transform(X_test) 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])) + 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') @@ -832,7 +854,7 @@ plt.show()











    -

    Gradient Boosting, Classification Example

    +

    Gradient Boosting, Classification Example

    @@ -848,8 +870,8 @@ plt.show() 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) +print(X_train.shape) +print(X_test.shape) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -861,12 +883,12 @@ gd_clf = GradientBoostingClassifier(max_depth=3#Cross validation accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score'] -print(accuracy) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test))) +print(accuracy) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = gd_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) save_fig("gdclassiffierconfusion") plt.show() y_probas = gd_clf.predict_proba(X_test_scaled) @@ -880,7 +902,7 @@ plt.show()











    -

    XGBoost: Extreme Gradient Boosting

    +

    XGBoost: Extreme Gradient Boosting

    XGBoost or Extreme Gradient @@ -901,7 +923,7 @@ It is now the algorithm which wins essentially all ML competitions!!!











    -

    Regression Case

    +

    Regression Case

    @@ -940,11 +962,11 @@ X_test_scaled = scaler.transform(X_test) 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])) + 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') @@ -956,7 +978,7 @@ plt.show()











    -

    Xgboost on the Cancer Data

    +

    Xgboost on the Cancer Data

    As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. @@ -975,8 +997,8 @@ As you will see from the confusion matrix below, XGBoots does an excellent job o 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) +print(X_train.shape) +print(X_test.shape) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -989,11 +1011,11 @@ xg_clf.fit(X_train_scaled,y_train) y_test = xg_clf.predict(X_test_scaled) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = xg_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +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) diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html index a3859ad05..7617607e2 100644 --- a/doc/pub/week45/html/week45.html +++ b/doc/pub/week45/html/week45.html @@ -40,64 +40,66 @@ div { text-align: justify; text-justify: inter-word; } @@ -139,12 +141,32 @@ MathJax.Hub.Config({

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

    -

    Sep 16, 2020

    +

    Oct 31, 2020












    -

    Random forests

    +

    Overview of week 45

    + +
      +
    • "Thursday: Wrapping up from last week. Bagging and Random forests.
    • +
    • "Friday: Boosting and gradient boosting
    • +
    + +Geron's chapter 7. See also lecture from STK-IN4300, lecture 7. Chapter 9.2 of Hastie et al contains also a good discussion. + +

    +









    + +

    Thursday

    + +

    +Bagging, voting and random forests. + +

    +









    + +

    Random forests

    Random forests provide an improvement over bagged trees by way of a @@ -188,7 +210,7 @@ this setting.











    -

    Random Forest Algorithm

    +

    Random Forest Algorithm

    The algorithm described here can be applied to both classification and regression problems.

    @@ -214,7 +236,7 @@ We will grow of forest of say \( B \) trees.









    -

    Random Forests Compared with other Methods on the Cancer Data

    +

    Random Forests Compared with other Methods on the Cancer Data

    @@ -230,20 +252,20 @@ We will grow of forest of say \( B \) trees. 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) +print(X_train.shape) +print(X_test.shape) # Logistic Regression logreg = LogisticRegression(solver='lbfgs') logreg.fit(X_train, y_train) -print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) # Support vector machine svm = SVC(gamma='auto', C=100) svm.fit(X_train, y_train) -print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) +print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test))) # Decision Trees -deep_tree_clf = DecisionTreeClassifier(max_depth=None) +deep_tree_clf = DecisionTreeClassifier(max_depth=None) deep_tree_clf.fit(X_train, y_train) -print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) +print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test))) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -252,13 +274,13 @@ X_train_scaled = scaler= scaler.transform(X_test) # Logistic Regression logreg.fit(X_train_scaled, y_train) -print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) # Support Vector Machine svm.fit(X_train_scaled, y_train) -print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) # Decision Trees deep_tree_clf.fit(X_train_scaled, y_train) -print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) +print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test))) from sklearn.ensemble import RandomForestClassifier @@ -270,13 +292,13 @@ Random_Forest_model = RandomForestClassifier Random_Forest_model.fit(X_train_scaled, y_train) #Cross validation accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score'] -print(accuracy) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test))) +print(accuracy) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = Random_Forest_model.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) plt.show() y_probas = Random_Forest_model.predict_proba(X_test_scaled) skplt.metrics.plot_roc(y_test, y_probas) @@ -287,13 +309,13 @@ plt.show()











    -

    Compare Bagging on Trees with Random Forests

    +

    Compare Bagging on Trees with Random Forests

    bag_clf = BaggingClassifier(
         DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    -    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
    +    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
     

    @@ -309,7 +331,7 @@ np.sum(y_pred =











    -

    Boosting, a Bird's Eye View

    +

    Boosting, a Bird's Eye View

    The basic idea is to combine weak classifiers in order to create a good @@ -326,7 +348,7 @@ them with a factor.











    -

    What is boosting? Additive Modelling/Iterative Fitting

    +

    What is boosting? Additive Modelling/Iterative Fitting

    Boosting is a way of fitting an additive expansion in a set of @@ -378,7 +400,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re











    -

    Iterative Fitting, Regression and Squared-error Cost Function

    +

    Iterative Fitting, Regression and Squared-error Cost Function

    The way we proceed is as follows (here we specialize to the squared-error cost function) @@ -403,7 +425,7 @@ at the internal nodes, and the predictions at the terminal nodes.











    -

    Squared-Error Example and Iterative Fitting

    +

    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. @@ -451,7 +473,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma











    -

    Iterative Fitting, Classification and AdaBoost

    +

    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 @@ -486,7 +508,7 @@ $$











    -

    Adaptive Boosting, AdaBoost

    +

    Adaptive Boosting, AdaBoost

    In our iterative procedure we define thus @@ -514,7 +536,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).











    -

    Building up AdaBoost

    +

    Building up AdaBoost

    First, for any \( \beta > 0 \), we optimize \( G \) by setting @@ -558,7 +580,7 @@ $$











    -

    Adaptive boosting: AdaBoost, Basic Algorithm

    +

    Adaptive boosting: AdaBoost, Basic Algorithm

    The algorithm here is rather straightforward. Assume that our weak @@ -580,7 +602,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co











    -

    Basic Steps of AdaBoost

    +

    Basic Steps of AdaBoost

    With the above definitions we are now ready to set up the algorithm for AdaBoost. @@ -620,7 +642,7 @@ observations that are missed in the previous iterations.











    -

    AdaBoost Examples

    +

    AdaBoost Examples

    Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here. @@ -642,7 +664,7 @@ ada_clf = AdaBoostClassifier( algorithm="SAMME.R", learning_rate=0.5, random_state=42) ada_clf.fit(X_train_scaled, y_train) y_pred = ada_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) plt.show() y_probas = ada_clf.predict_proba(X_test_scaled) skplt.metrics.plot_roc(y_test, y_probas) @@ -653,7 +675,7 @@ plt.show()











    -

    AdaBoost for Regression

    +

    AdaBoost for Regression

    Here we present Drucker's AdaBoost tailored for regression. @@ -681,7 +703,7 @@ Start by selecting a set of training data \( n \) and assign to each entry a wei











    -

    Gradient boosting: Basics with Steepest Descent

    +

    Gradient boosting: Basics with Steepest Descent

    Gradient boosting is again a similar technique to Adaptive boosting, @@ -696,7 +718,7 @@ function was the least squares function.











    -

    The Squared-Error again! Steepest Descent

    +

    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 @@ -731,7 +753,7 @@ $$











    -

    Steepest Descent Example

    +

    Steepest Descent Example

    Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that @@ -749,7 +771,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(











    -

    Gradient Boosting, algorithm

    +

    Gradient Boosting, algorithm

    Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function @@ -775,7 +797,7 @@ The way we proceed in an iterative fashion is to









    -

    Gradient Boosting Example, Regression

    +

    Gradient Boosting Example, Regression

    We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. @@ -783,7 +805,7 @@ We discuss here the difference between the steepest descent approach and gradien











    -

    Gradient Boosting, Examples of Regression

    +

    Gradient Boosting, Examples of Regression

    @@ -820,11 +842,11 @@ X_test_scaled = scaler= 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])) + 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') @@ -837,7 +859,7 @@ plt.show()











    -

    Gradient Boosting, Classification Example

    +

    Gradient Boosting, Classification Example

    @@ -853,8 +875,8 @@ plt.show() 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) +print(X_train.shape) +print(X_test.shape) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -866,12 +888,12 @@ gd_clf = GradientBoostingClassifier(max_dept gd_clf.fit(X_train_scaled, y_train) #Cross validation accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score'] -print(accuracy) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test))) +print(accuracy) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = gd_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) save_fig("gdclassiffierconfusion") plt.show() y_probas = gd_clf.predict_proba(X_test_scaled) @@ -885,7 +907,7 @@ plt.show()











    -

    XGBoost: Extreme Gradient Boosting

    +

    XGBoost: Extreme Gradient Boosting

    XGBoost or Extreme Gradient @@ -906,7 +928,7 @@ It is now the algorithm which wins essentially all ML competitions!!!











    -

    Regression Case

    +

    Regression Case

    @@ -945,11 +967,11 @@ X_test_scaled = scaler= 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])) + 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') @@ -961,7 +983,7 @@ plt.show()











    -

    Xgboost on the Cancer Data

    +

    Xgboost on the Cancer Data

    As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now. @@ -980,8 +1002,8 @@ As you will see from the confusion matrix below, XGBoots does an excellent job o 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) +print(X_train.shape) +print(X_test.shape) #now scale the data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() @@ -994,11 +1016,11 @@ xg_clf.fit(X_train_scaled,y_train) y_test = xg_clf.predict(X_test_scaled) -print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) +print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test))) import scikitplot as skplt y_pred = xg_clf.predict(X_test_scaled) -skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +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) diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz index f30ba752fb9322959192176ca436fcfbf379467f..f8420afba1eab6f41ae0e83da4170995a5f77fd0 100644 GIT binary patch literal 190 zcmV;v073sBiwFRe{q sh89@7w#p(%-GM9$<(1L$95>b+t-QD-{`E6K5Cp;39`n6WmH-F<0K#Bi)c^nh literal 196 zcmb2|=3sd1m=w>z{Pz6Dyh8>etq;#scKv3Vc=yQ3o{%;^j}?ztdy+)CH>`ZT;>la? z*aSzP6;6Nd7qu0)Rog$`{Qc;jQ^#X$daN>UKby15_?6ZFj9jkR@~v4?S0#fr{x0)Z zd{w9(+vB{=bIFb4Q(|}Q-F@AD<<(>SpEl0TdZ}pZ3pZWIzH9;-9!@T`&`3&|qKy0Op@tumAu6 diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb index 80433a3e0..d7b453b7b 100644 --- a/doc/pub/week45/ipynb/week45.ipynb +++ b/doc/pub/week45/ipynb/week45.ipynb @@ -10,12 +10,24 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Sep 16, 2020**\n", + "Date: **Oct 31, 2020**\n", "\n", "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", "\n", "\n", + "## Overview of week 45\n", + "\n", + "* \"Thursday: Wrapping up from last week. Bagging and Random forests.\n", + "\n", + "* \"Friday: Boosting and gradient boosting\n", + "\n", + "Geron's chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion.\n", + "\n", + "\n", + "## Thursday\n", + "\n", + "Bagging, voting and random forests.\n", "\n", "\n", "## Random forests\n", @@ -1208,5 +1220,5 @@ ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/doc/src/week45/week45.do.txt b/doc/src/week45/week45.do.txt index 13c6037d4..a7554dc16 100644 --- a/doc/src/week45/week45.do.txt +++ b/doc/src/week45/week45.do.txt @@ -2,6 +2,20 @@ TITLE: Week 45: Random Forests and Boosting 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 45 ===== + +* "Thursday: Wrapping up from last week. Bagging and Random forests. +* "Friday: Boosting and gradient boosting + + +Geron's chapter 7. See also lecture from "STK-IN4300, lecture 7":"https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf". Chapter 9.2 of Hastie et al contains also a good discussion. + + +!split +===== Thursday ===== + +Bagging, voting and random forests. !split