diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index e6071ed7c..2e1cecb88 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -101,81 +101,74 @@ Automatically generated HTML file from DocOnce source ('An Overview of Ensemble Methods', 2, None, '___sec37'), ('Bagging', 2, None, '___sec38'), ('More bagging', 2, None, '___sec39'), - ('Simple Voting Example, head or tail', 2, None, '___sec40'), - ('Using the Voting Classifier', 2, None, '___sec41'), - ('Please, not the moons again! Voting and Bagging', - 2, - None, - '___sec42'), - ('Bagging Examples', 2, None, '___sec43'), ('Making your own Bootstrap: Changing the Level of the Decision ' 'Tree', 2, None, - '___sec44'), - ('Why Voting?', 2, None, '___sec45'), - ('Tossing coins', 2, None, '___sec46'), - ('Standard imports first', 2, None, '___sec47'), - ('Simple Voting Example, head or tail', 2, None, '___sec48'), - ('Using the Voting Classifier', 2, None, '___sec49'), - ('Voting and Bagging', 2, None, '___sec50'), - ('Random forests', 2, None, '___sec51'), - ('Random Forest Algorithm', 2, None, '___sec52'), + '___sec40'), + ('Why Voting?', 2, None, '___sec41'), + ('Tossing coins', 2, None, '___sec42'), + ('Standard imports first', 2, None, '___sec43'), + ('Simple Voting Example, head or tail', 2, None, '___sec44'), + ('Using the Voting Classifier', 2, None, '___sec45'), + ('Voting and Bagging', 2, None, '___sec46'), + ('Random forests', 2, None, '___sec47'), + ('Random Forest Algorithm', 2, None, '___sec48'), ('Random Forests Compared with other Methods on the Cancer Data', 2, None, - '___sec53'), + '___sec49'), ('Compare Bagging on Trees with Random Forests', 2, None, - '___sec54'), - ("Boosting, a Bird's Eye View", 2, None, '___sec55'), + '___sec50'), + ("Boosting, a Bird's Eye View", 2, None, '___sec51'), ('What is boosting? Additive Modelling/Iterative Fitting', 2, None, - '___sec56'), + '___sec52'), ('Iterative Fitting, Regression and Squared-error Cost Function', 2, None, - '___sec57'), + '___sec53'), ('Squared-Error Example and Iterative Fitting', 2, None, - '___sec58'), + '___sec54'), ('Iterative Fitting, Classification and AdaBoost', 2, None, - '___sec59'), - ('Adaptive Boosting, AdaBoost', 2, None, '___sec60'), - ('Building up AdaBoost', 2, None, '___sec61'), + '___sec55'), + ('Adaptive Boosting, AdaBoost', 2, None, '___sec56'), + ('Building up AdaBoost', 2, None, '___sec57'), ('Adaptive boosting: AdaBoost, Basic Algorithm', 2, None, - '___sec62'), - ('Basic Steps of AdaBoost', 2, None, '___sec63'), - ('AdaBoost Examples', 2, None, '___sec64'), + '___sec58'), + ('Basic Steps of AdaBoost', 2, None, '___sec59'), + ('AdaBoost Examples', 2, None, '___sec60'), ('Gradient boosting: Basics with Steepest Descent/Functional ' 'Gradient Descent', 2, None, - '___sec65'), + '___sec61'), ('The Squared-Error again! Steepest Descent', 2, None, - '___sec66'), - ('Steepest Descent Example', 2, None, '___sec67'), - ('Gradient Boosting, algorithm', 2, None, '___sec68'), + '___sec62'), + ('Steepest Descent Example', 2, None, '___sec63'), + ('Gradient Boosting, algorithm', 2, None, '___sec64'), ('Gradient Boosting, Examples of Regression', 2, None, - '___sec69'), + '___sec65'), ('Gradient Boosting, Classification Example', 2, None, - '___sec70'), - ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec71'), - ('Regression Case', 2, None, '___sec72'), - ('Xgboost on the Cancer Data', 2, None, '___sec73')]} + '___sec66'), + ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec67'), + ('Regression Case', 2, None, '___sec68'), + ('Xgboost on the Cancer Data', 2, None, '___sec69')]} end of tocinfo -->
@@ -253,40 +246,36 @@ MathJax.Hub.Config({+Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)).
-
heads_proba = 0.51
-coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
-cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
-plt.figure(figsize=(8,3.5))
-plt.plot(cumulative_heads_ratio)
-plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
-plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
-plt.xlabel("Number of coin tosses")
-plt.ylabel("Heads ratio")
-plt.legend(loc="lower right")
-plt.axis([0, 10000, 0.42, 0.58])
-save_fig("votingsimple")
+import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.pipeline import make_pipeline
+from sklearn.utils import resample
+from sklearn.tree import DecisionTreeRegressor
+
+n = 1000
+n_boostraps = 100
+maxdepth = 10
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+error = np.zeros(maxdepth)
+bias = np.zeros(maxdepth)
+variance = np.zeros(maxdepth)
+polydegree = np.zeros(maxdepth)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+
+# we produce a simple tree first as benchmark, no scaling
+simpletree = DecisionTreeRegressor(max_depth=3)
+simpletree.fit(X_train, y_train)
+simpleprediction = simpletree.predict(X_test)
+for degree in range(1,maxdepth):
+ model = DecisionTreeRegressor(max_depth=degree)
+ y_pred = np.empty((y_test.shape[0], n_boostraps))
+ for i in range(n_boostraps):
+ x_, y_ = resample(X_train, y_train)
+ model.fit(x_, y_)
+ y_pred[:, i] = model.predict(X_test)#.ravel()
+
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
+ variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
+ print('Polynomial degree:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
+print(mse_simpletree)
+plt.xlim(1,maxdepth)
+plt.plot(polydegree, error, label='MSE')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("baggingboot")
plt.show()
@@ -346,7 +377,7 @@ plt.show()
+The idea behind boosting, and voting as well can be phrased as follows: +Can a group of people somehow arrive at highly +reasoned decisions, despite the weak judgement of the individual +members? - -
from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
+
+The aim is to create a good classifier by combining several weak classifiers.
+A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.
+In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in
+each iteration.
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
+
+Decision trees play an important role as our weak classifier. They serve as the basic method.
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
@@ -376,7 +337,7 @@ voting_clf.fit(X_train, y_train)
+The simplest case is a so-called voting ensemble. To illustrate this, +think of yourself tossing coins with a biased outcome of 51 per cent +for heads and 49% for tails. With only few tosses, +you may not clearly see this distribution for heads and tails. However, after some +thousands of tosses, there will be a clear majority of heads. With 2000 tosses +you should see approximately 1020 heads and 980 tails. - -
from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-voting_clf.fit(X_train, y_train)
-+We can then state that the outcome is a clear majority of heads. If +you do this ten thousand times, it is easy to see that there is a 97% +likelihood of a majority of heads. - -
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-+Another example would be to collect all polls before an +election. Different polls may show different likelihoods for a +candidate winning with say a majority of the popular vote. The majority vote +would then consist in many polls indicating that this candidate will +actually win. - -
log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-+The example here shows how we can implement the coin tossing case, +clealry demostrating that after some tosses we see the law of large +numbers kicking in. - -
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
@@ -384,7 +344,7 @@ voting_clf.fit(X_train, y_train)
-
from sklearn.ensemble import BaggingClassifier
+# Common imports
+from IPython.display import Image
+from pydot import graph_from_dot_data
+import pandas as pd
+import numpy as np
+import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
+from sklearn.model_selection import train_test_split
+from sklearn.tree import export_graphviz
+from sklearn.preprocessing import StandardScaler, OneHotEncoder
+from sklearn.compose import ColumnTransformer
+from IPython.display import Image
+from pydot import graph_from_dot_data
+import os
-bag_clf = BaggingClassifier(
- DecisionTreeClassifier(random_state=42), n_estimators=500,
- max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
-bag_clf.fit(X_train, y_train)
-y_pred = bag_clf.predict(X_test)
-
-
+# Where to save the figures and data files
+PROJECT_ROOT_DIR = "Results"
+FIGURE_ID = "Results/FigureFiles"
+DATA_ID = "DataFiles/"
-
-
from sklearn.metrics import accuracy_score
-print(accuracy_score(y_test, y_pred))
-
-
+if not os.path.exists(PROJECT_ROOT_DIR):
+ os.mkdir(PROJECT_ROOT_DIR)
-
-
tree_clf = DecisionTreeClassifier(random_state=42)
-tree_clf.fit(X_train, y_train)
-y_pred_tree = tree_clf.predict(X_test)
-print(accuracy_score(y_test, y_pred_tree))
-
-
+if not os.path.exists(FIGURE_ID):
+ os.makedirs(FIGURE_ID)
-
-
from matplotlib.colors import ListedColormap
+if not os.path.exists(DATA_ID):
+ os.makedirs(DATA_ID)
-def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
- x1s = np.linspace(axes[0], axes[1], 100)
- x2s = np.linspace(axes[2], axes[3], 100)
- x1, x2 = np.meshgrid(x1s, x2s)
- X_new = np.c_[x1.ravel(), x2.ravel()]
- y_pred = clf.predict(X_new).reshape(x1.shape)
- custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
- plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
- if contour:
- custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
- plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
- plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
- plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
- plt.axis(axes)
- plt.xlabel(r"$x_1$", fontsize=18)
- plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
-plt.figure(figsize=(11,4))
-plt.subplot(121)
-plot_decision_boundary(tree_clf, X, y)
-plt.title("Decision Tree", fontsize=14)
-plt.subplot(122)
-plot_decision_boundary(bag_clf, X, y)
-plt.title("Decision Trees with Bagging", fontsize=14)
-save_fig("baggingtree")
-plt.show()
+def image_path(fig_id):
+ return os.path.join(FIGURE_ID, fig_id)
+
+def data_path(dat_id):
+ return os.path.join(DATA_ID, dat_id)
+
+def save_fig(fig_id):
+ plt.savefig(image_path(fig_id) + ".png", format='png')
@@ -387,7 +360,7 @@ plt.show()
-Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with -a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points \( n \)). +
-
import matplotlib.pyplot as plt
+# Common imports
import numpy as np
-from sklearn.model_selection import train_test_split
-from sklearn.pipeline import make_pipeline
-from sklearn.utils import resample
-from sklearn.tree import DecisionTreeRegressor
+import matplotlib
+import matplotlib.pyplot as plt
+from matplotlib.colors import ListedColormap
+plt.rcParams['axes.labelsize'] = 14
+plt.rcParams['xtick.labelsize'] = 12
+plt.rcParams['ytick.labelsize'] = 12
-n = 100
-n_boostraps = 100
-maxdepth = 8
-
-# Make data set.
-x = np.linspace(-3, 3, n).reshape(-1, 1)
-y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
-error = np.zeros(maxdepth)
-bias = np.zeros(maxdepth)
-variance = np.zeros(maxdepth)
-polydegree = np.zeros(maxdepth)
-X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-# we produce a simple tree first as benchmark
-simpletree = DecisionTreeRegressor(max_depth=3)
-simpletree.fit(X_train_scaled, y_train)
-simpleprediction = simpletree.predict(X_test_scaled)
-for degree in range(1,maxdepth):
- model = DecisionTreeRegressor(max_depth=degree)
- y_pred = np.empty((y_test.shape[0], n_boostraps))
- for i in range(n_boostraps):
- x_, y_ = resample(X_train_scaled, y_train)
- model.fit(x_, y_)
- y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
-
- polydegree[degree] = degree
- error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
- bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
- variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
- print('Polynomial degree:', degree)
- print('Error:', error[degree])
- print('Bias^2:', bias[degree])
- print('Var:', variance[degree])
- print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-
-mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
-print(mse_simpletree)
-plt.xlim(1,maxdepth)
-plt.plot(polydegree, error, label='MSE')
-plt.plot(polydegree, bias, label='bias')
-plt.plot(polydegree, variance, label='Variance')
-plt.legend()
-save_fig("baggingboot")
+heads_proba = 0.51
+coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
+cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
+plt.figure(figsize=(8,3.5))
+plt.plot(cumulative_heads_ratio)
+plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
+plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
+plt.xlabel("Number of coin tosses")
+plt.ylabel("Heads ratio")
+plt.legend(loc="lower right")
+plt.axis([0, 10000, 0.42, 0.58])
+save_fig("votingsimple")
plt.show()
@@ -394,7 +344,7 @@ plt.show()
-The idea behind boosting, and voting as well can be phrased as follows: -Can a group of people somehow arrive at highly -reasoned decisions, despite the weak judgement of the individual -members? - +We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
-The aim is to create a good classifier by combining several weak classifiers. -A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random. -
-The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data. -In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in -each iteration. + +
from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
-
-Decision trees play an important role as our weak classifier. They serve as the basic method.
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
+log_clf = LogisticRegression(solver="liblinear", random_state=42)
+rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
+svm_clf = SVC(gamma="auto", probability=True, random_state=42)
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+
+from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
@@ -348,7 +367,7 @@ Decision trees play an important role as our weak classifier. They serve as the
-The simplest case is a so-called voting ensemble. To illustrate this, -think of yourself tossing coins with a biased outcome of 51 per cent -for heads and 49% for tails. With only few tosses, -you may not clearly see this distribution for heads and tails. However, after some -thousands of tosses, there will be a clear majority of heads. With 2000 tosses -you should see approximately 1020 heads and 980 tails. + +
from sklearn.model_selection import train_test_split
+from sklearn.datasets import make_moons
+
+X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
+X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.ensemble import VotingClassifier
+from sklearn.linear_model import LogisticRegression
+from sklearn.svm import SVC
+
+log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='hard')
+voting_clf.fit(X_train, y_train)
+-We can then state that the outcome is a clear majority of heads. If -you do this ten thousand times, it is easy to see that there is a 97% -likelihood of a majority of heads. + +
from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+-Another example would be to collect all polls before an -election. Different polls may show different likelihoods for a -candidate winning with say a majority of the popular vote. The majority vote -would then consist in many polls indicating that this candidate will -actually win. + +
log_clf = LogisticRegression(random_state=42)
+rnd_clf = RandomForestClassifier(random_state=42)
+svm_clf = SVC(probability=True, random_state=42)
+
+voting_clf = VotingClassifier(
+ estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
+ voting='soft')
+voting_clf.fit(X_train, y_train)
+-The example here shows how we can implement the coin tossing case, -clealry demostrating that after some tosses we see the law of large -numbers kicking in. + +
from sklearn.metrics import accuracy_score
+
+for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
+ clf.fit(X_train, y_train)
+ y_pred = clf.predict(X_test)
+ print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+
@@ -355,7 +373,7 @@ numbers kicking in.
+Random forests provide an improvement over bagged trees by way of a +small tweak that decorrelates the trees. - -
# Common imports
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.model_selection import train_test_split
-from sklearn.tree import export_graphviz
-from sklearn.preprocessing import StandardScaler, OneHotEncoder
-from sklearn.compose import ColumnTransformer
-from IPython.display import Image
-from pydot import graph_from_dot_data
-import os
+
+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.
-# Where to save the figures and data files
-PROJECT_ROOT_DIR = "Results"
-FIGURE_ID = "Results/FigureFiles"
-DATA_ID = "DataFiles/"
+
+A fresh sample of \( m \) predictors is
+taken at each split, and typically we choose
-if not os.path.exists(PROJECT_ROOT_DIR):
- os.mkdir(PROJECT_ROOT_DIR)
+$$
+m\approx \sqrt{p}.
+$$
-if not os.path.exists(FIGURE_ID):
- os.makedirs(FIGURE_ID)
+
+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.
-if not os.path.exists(DATA_ID):
- os.makedirs(DATA_ID)
+
+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.
-def image_path(fig_id):
- return os.path.join(FIGURE_ID, fig_id)
-
-def data_path(dat_id):
- return os.path.join(DATA_ID, dat_id)
-
-def save_fig(fig_id):
- plt.savefig(image_path(fig_id) + ".png", format='png')
-
@@ -371,7 +358,7 @@ DATA_ID = "
+
+We will grow of forest of say \( B \) trees.
+
+
-We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
+
-
+Recall that the cumulative gains curve shows the percentage of the
+overall number of cases in a given category gained by targeting a
+percentage of the total number of cases.
+
+
+Similarly, the receiver operating characteristic curve, or ROC curve,
+displays the diagnostic ability of a binary classifier system as its
+discrimination threshold is varied. It plots the true positive rate against the false positive rate.
+
@@ -378,7 +398,7 @@ voting_clf.fit(X_train, y_train)
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
+
+
-
-
-
-
-
-
-
-
-
@@ -384,7 +336,7 @@ voting_clf.fit(X_train, y_train)
-Random forests provide an improvement over bagged trees by way of a
-small tweak that decorrelates the trees.
+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.
-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.
+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.
@@ -369,7 +331,7 @@ this setting.
-We will grow of forest of say \( B \) trees.
+Boosting is a way of fitting an additive expansion in a set of
+elementary basis functions like for example some simple polynomials.
+Assume for example that we have a function
+$$
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+$$
-
+where \( \beta_m \) are the expansion parameters to be determined in a
+minimization process and \( b(x;\gamma_m) \) are some simple functions of
+the multivariable parameter \( x \) which is characterized by the
+parameters \( \gamma_m \).
-
+As an example, consider the Sigmoid function we used in logistic
+regression. In that case, we can translate the function
+\( b(x;\gamma_m) \) into the Sigmoid function
-
+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 \).
+
+
-
-
-
-Recall that the cumulative gains curve shows the percentage of the
-overall number of cases in a given category gained by targeting a
-percentage of the total number of cases.
+
-Similarly, the receiver operating characteristic curve, or ROC curve,
-displays the diagnostic ability of a binary classifier system as its
-discrimination threshold is varied. It plots the true positive rate against the false positive rate.
+The way we proceed is as follows (here we specialize to the squared-error cost function)
+
+
@@ -409,7 +339,7 @@ discrimination threshold is varied. It plots the true positive rate against the
+
+To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
+
+
+For simplicity we assume also that our functions \( b(x;\gamma)=1+\gamma x \).
+
+
+This means that for every iteration \( m \), we need to optimize
+
+$$
+(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.
+$$
+
+
+We start our iteration by simply setting \( f_0(x)=0 \).
+Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
+$$
+\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
+$$
+
+and
+$$
+\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
+$$
+
+We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
+$$
+\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,
+$$
+
+which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
+$$
+\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,
+$$
+
+
+which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting
+for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically.
+
+
+The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as
+\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \).
-
-
@@ -347,7 +362,7 @@ np.sum(y_pred =
-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.
+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\} \).
-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.
+The error rate of the training sample is then
+
+$$
+\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
+$$
+
+
+The iterative procedure starts with defining a weak classifier whose
+error rate is barely better than random guessing. The iterative
+procedure in boosting is to sequentially apply a weak
+classification algorithm to repeatedly modified versions of the data
+producing a sequence of weak classifiers \( G_m(x) \).
+
+
+Here we will express our function \( f(x) \) in terms of \( G(x) \). That is
+$$
+f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+$$
+
+will be a function of
+$$
+G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
+$$
@@ -342,7 +349,7 @@ them with a factor.
-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
+In our iterative procedure we define thus
$$
-f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
+f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
$$
-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
-
+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
$$
-\sigma(t) = \frac{1}{1+\exp{(-t)}},
+C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
$$
-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
+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
$$
-\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.
+C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
$$
-
-In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters \( \beta_m \) and \( \gamma_m \).
+where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
@@ -377,7 +342,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re
-The way we proceed is as follows (here we specialize to the squared-error cost function)
+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)),
+$$
-
+We can do this by rewriting
+$$
+\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
+$$
-
+which can be rewritten as
+$$
+(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
+$$
-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.
+which leads to
+$$
+\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
+$$
+
+where we have redefined the error as
+$$
+\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
+$$
+
+which leads to an update of
+$$
+f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
+$$
+
+This leads to the new weights
+$$
+w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
+$$
@@ -350,7 +358,7 @@ at the internal nodes, and the predictions at the terminal nodes.
-To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
+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} \).
-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
-
+We have already defined the misclassification error \( \mathrm{err} \) as
$$
-(\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.
+\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
$$
-
-We start our iteration by simply setting \( f_0(x)=0 \).
-Taking the derivatives with respect to \( \beta \) and \( \gamma \) we obtain
-$$
-\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
-$$
-
-and
-$$
-\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
-$$
-
-We can then rewrite these equations as (defining \( \boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x}) \) with \( \boldsymbol{e} \) being the unit vector)
-$$
-\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,
-$$
-
-which gives us \( \beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w}) \). Similarly we have
-$$
-\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,
-$$
-
-
-which leads to \( \gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x}) \). Inserting
-for \( \beta \) gives us an equation for \( \gamma \). This is a non-linear equation in the unknown \( \gamma \) and has to be solved numerically.
-
-
-The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma_1 \) leading to the new expression for \( f_1(x) \) as
-\( f_1(x) = \beta_1(1+\gamma_1x) \). Doing this \( M \) times results in our final estimate for the function \( f \).
+where the function \( I() \) is one if we misclassify and zero if we classify correctly.
@@ -373,7 +336,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma
-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\} \).
+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.
-
-The error rate of the training sample is then
+
-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),
-$$
+
@@ -360,7 +354,7 @@ $$
-In our iterative procedure we define thus
-$$
-f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
-$$
+Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
-The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
-exponential cost/loss function defined as
-$$
-C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
-$$
-
-We optimize \( \beta \) and \( G \) for each value of \( m=1:M \) as we did in the regression case.
-This is normally done in two steps. Let us however first rewrite the cost function as
+
+
@@ -352,8 +346,6 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
-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 \).
+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 do this by rewriting
-$$
-\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
-$$
-
-which can be rewritten as
-$$
-(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
-$$
-
-which leads to
-$$
-\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
-$$
-
-where we have redefined the error as
-$$
-\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
-$$
-
-which leads to an update of
-$$
-f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
-$$
-
-This leads to the new weights
-$$
-w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
-$$
+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.
@@ -367,9 +327,6 @@ $$
-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 start again with our cost function \( {\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i)) \) where we want to minimize
+This means that for every iteration, we need to optimize
+
+$$
+(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+$$
-We have already defined the misclassification error \( \mathrm{err} \) as
+We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
$$
-\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
+f_M(x) = \sum_{m=0}^M h_m(x).
$$
-where the function \( I() \) is one if we misclassify and zero if we classify correctly.
+
+In the steepest decent approach we approximate \( h_m(x) = -\rho_m g_m(x) \), where \( \rho_m \) is a scalar and \( g_m(x) \) the gradient defined as
+$$
+g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}.
+$$
+
+
+With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that
+the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \).
+
+
+Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have
+$$
+(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
+$$
@@ -344,10 +346,6 @@ where the function \( I() \) is one if we misclassify and zero if we classify co
-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.
-
-
@@ -361,11 +328,6 @@ observations that are missed in the previous iterations.
-Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
+Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
+so we do not learn a function that can generalize. However, we can modify the algorithm by
+fitting a weak learner to approximate the negative gradient signal.
+Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function
+$$
+C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
+$$
-
-
+The way we proceed in an iterative fashion is to
+
+
-Gradient boosting is again a similar technique to Adaptive boosting,
-it combines so-called weak classifiers or regressors into a strong
-method via a series of iterations.
-
-In order to understand the method, let us illustrate its basics by
-bringing back the essential steps in linear regression, where our cost
-function was the least squares function.
+
+
@@ -334,10 +362,6 @@ function was the least squares 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
-$$
-(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
-$$
+
+
-We define a real function \( h_m(x) \) that defines our final function \( f_M(x) \) as
-$$
-f_M(x) = \sum_{m=0}^M h_m(x).
-$$
+# Load the data
+cancer = load_breast_cancer()
-
-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)}.
-$$
+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)
-
-With the new gradient we can update \( f_m(x) = f_{m-1}(x) -\rho_m g_m(x) \). Using the above squared-error function we see that
-the gradient is \( g_m(x_i) = -2(y_i-f(x_i)) \).
-
-
-Choosing \( f_0(x)=0 \) we obtain \( g_m(x) = -2y_i \) and inserting this into the minimization problem for the cost function we have
-$$
-(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
-$$
+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()
+
@@ -353,10 +355,6 @@ $$
-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.
-$$
+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.
-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,
-$$
+
+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.
-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.
+
+It is now the algorithm which wins essentially all ML competitions!!!
@@ -335,10 +327,6 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(
-Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
-so we do not learn a function that can generalize. However, we can modify the algorithm by
-fitting a weak learner to approximate the negative gradient signal.
+
+
-Suppose we have a cost function \( C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i)) \) where \( y_i \) is our target and \( f(x_i) \) the function which is meant to model \( y_i \). The above cost function could be our standard squared-error function
-$$
-C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
-$$
-
-
-The way we proceed in an iterative fashion is to
-
-
+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.
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
@@ -1703,9 +1506,9 @@ a decision tree wth different depths and perform a bootstrap aggregate (in this
from sklearn.utils import resample
from sklearn.tree import DecisionTreeRegressor
-n = 100
+n = 1000
n_boostraps = 100
-maxdepth = 8
+maxdepth = 10
# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
@@ -1716,23 +1519,17 @@ variance = np.zeros(maxdepth)
polydegree = np.zeros(maxdepth)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-# we produce a simple tree first as benchmark
+# we produce a simple tree first as benchmark, no scaling
simpletree = DecisionTreeRegressor(max_depth=3)
-simpletree.fit(X_train_scaled, y_train)
-simpleprediction = simpletree.predict(X_test_scaled)
+simpletree.fit(X_train, y_train)
+simpleprediction = simpletree.predict(X_test)
for degree in range(1,maxdepth):
model = DecisionTreeRegressor(max_depth=degree)
y_pred = np.empty((y_test.shape[0], n_boostraps))
for i in range(n_boostraps):
- x_, y_ = resample(X_train_scaled, y_train)
+ x_, y_ = resample(X_train, y_train)
model.fit(x_, y_)
- y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+ y_pred[:, i] = model.predict(X_test)#.ravel()
polydegree[degree] = degree
error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
@@ -1744,7 +1541,7 @@ simpleprediction = simpletree.predict(X_test_scaled)
print('Var:', variance[degree])
print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
print(mse_simpletree)
plt.xlim(1,maxdepth)
plt.plot(polydegree, error, label='MSE')
@@ -1758,7 +1555,7 @@ plt.show()
The idea behind boosting, and voting as well can be phrased as follows:
@@ -1781,7 +1578,7 @@ Decision trees play an important role as our weak classifier. They serve as the
The simplest case is a so-called voting ensemble. To illustrate this,
@@ -1811,7 +1608,7 @@ numbers kicking in.
@@ -1858,7 +1655,7 @@ DATA_ID = "DataFiles/"
@@ -1889,7 +1686,7 @@ plt.show()
We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
@@ -1943,7 +1740,7 @@ voting_clf.fit(X_train, y_train)
@@ -2003,7 +1800,7 @@ voting_clf.fit(X_train, y_train)
Random forests provide an improvement over bagged trees by way of a
@@ -2049,7 +1846,7 @@ this setting.
@@ -2080,7 +1877,7 @@ We will grow of forest of say \( B \) trees.
@@ -2164,7 +1961,7 @@ discrimination threshold is varied. It plots the true positive rate against the
@@ -2187,7 +1984,7 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)
The basic idea is to combine weak classifiers in order to create a good
@@ -2204,7 +2001,7 @@ them with a factor.
Boosting is a way of fitting an additive expansion in a set of
@@ -2264,7 +2061,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re
The way we proceed is as follows (here we specialize to the squared-error cost function)
@@ -2290,7 +2087,7 @@ at the internal nodes, and the predictions at the terminal nodes.
To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
@@ -2348,7 +2145,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma
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
@@ -2389,7 +2186,7 @@ $$
In our iterative procedure we define thus
@@ -2423,7 +2220,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
First, for any \( \beta > 0 \), we optimize \( G \) by setting
@@ -2481,7 +2278,7 @@ $$
The algorithm here is rather straightforward. Assume that our weak
@@ -2505,7 +2302,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co
With the above definitions we are now ready to set up the algorithm for AdaBoost.
@@ -2546,7 +2343,7 @@ observations that are missed in the previous iterations.
Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
@@ -2580,7 +2377,7 @@ plt.show()
Gradient boosting is again a similar technique to Adaptive boosting,
@@ -2595,7 +2392,7 @@ function was the least squares 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
@@ -2638,7 +2435,7 @@ $$
Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
@@ -2660,7 +2457,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(
Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
@@ -2693,7 +2490,7 @@ The way we proceed in an iterative fashion is to
@@ -2748,7 +2545,7 @@ plt.show()
@@ -2797,7 +2594,7 @@ plt.show()
XGBoost or Extreme Gradient
@@ -2818,7 +2615,7 @@ It is now the algorithm which wins essentially all ML competitions!!!
@@ -2874,7 +2671,7 @@ plt.show()
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.
diff --git a/doc/pub/week45/html/week45-solarized.html b/doc/pub/week45/html/week45-solarized.html
index 3ca8dac73..40589d7a9 100644
--- a/doc/pub/week45/html/week45-solarized.html
+++ b/doc/pub/week45/html/week45-solarized.html
@@ -121,81 +121,74 @@ div { text-align: justify; text-justify: inter-word; }
('An Overview of Ensemble Methods', 2, None, '___sec37'),
('Bagging', 2, None, '___sec38'),
('More bagging', 2, None, '___sec39'),
- ('Simple Voting Example, head or tail', 2, None, '___sec40'),
- ('Using the Voting Classifier', 2, None, '___sec41'),
- ('Please, not the moons again! Voting and Bagging',
- 2,
- None,
- '___sec42'),
- ('Bagging Examples', 2, None, '___sec43'),
('Making your own Bootstrap: Changing the Level of the Decision '
'Tree',
2,
None,
- '___sec44'),
- ('Why Voting?', 2, None, '___sec45'),
- ('Tossing coins', 2, None, '___sec46'),
- ('Standard imports first', 2, None, '___sec47'),
- ('Simple Voting Example, head or tail', 2, None, '___sec48'),
- ('Using the Voting Classifier', 2, None, '___sec49'),
- ('Voting and Bagging', 2, None, '___sec50'),
- ('Random forests', 2, None, '___sec51'),
- ('Random Forest Algorithm', 2, None, '___sec52'),
+ '___sec40'),
+ ('Why Voting?', 2, None, '___sec41'),
+ ('Tossing coins', 2, None, '___sec42'),
+ ('Standard imports first', 2, None, '___sec43'),
+ ('Simple Voting Example, head or tail', 2, None, '___sec44'),
+ ('Using the Voting Classifier', 2, None, '___sec45'),
+ ('Voting and Bagging', 2, None, '___sec46'),
+ ('Random forests', 2, None, '___sec47'),
+ ('Random Forest Algorithm', 2, None, '___sec48'),
('Random Forests Compared with other Methods on the Cancer Data',
2,
None,
- '___sec53'),
+ '___sec49'),
('Compare Bagging on Trees with Random Forests',
2,
None,
- '___sec54'),
- ("Boosting, a Bird's Eye View", 2, None, '___sec55'),
+ '___sec50'),
+ ("Boosting, a Bird's Eye View", 2, None, '___sec51'),
('What is boosting? Additive Modelling/Iterative Fitting',
2,
None,
- '___sec56'),
+ '___sec52'),
('Iterative Fitting, Regression and Squared-error Cost Function',
2,
None,
- '___sec57'),
+ '___sec53'),
('Squared-Error Example and Iterative Fitting',
2,
None,
- '___sec58'),
+ '___sec54'),
('Iterative Fitting, Classification and AdaBoost',
2,
None,
- '___sec59'),
- ('Adaptive Boosting, AdaBoost', 2, None, '___sec60'),
- ('Building up AdaBoost', 2, None, '___sec61'),
+ '___sec55'),
+ ('Adaptive Boosting, AdaBoost', 2, None, '___sec56'),
+ ('Building up AdaBoost', 2, None, '___sec57'),
('Adaptive boosting: AdaBoost, Basic Algorithm',
2,
None,
- '___sec62'),
- ('Basic Steps of AdaBoost', 2, None, '___sec63'),
- ('AdaBoost Examples', 2, None, '___sec64'),
+ '___sec58'),
+ ('Basic Steps of AdaBoost', 2, None, '___sec59'),
+ ('AdaBoost Examples', 2, None, '___sec60'),
('Gradient boosting: Basics with Steepest Descent/Functional '
'Gradient Descent',
2,
None,
- '___sec65'),
+ '___sec61'),
('The Squared-Error again! Steepest Descent',
2,
None,
- '___sec66'),
- ('Steepest Descent Example', 2, None, '___sec67'),
- ('Gradient Boosting, algorithm', 2, None, '___sec68'),
+ '___sec62'),
+ ('Steepest Descent Example', 2, None, '___sec63'),
+ ('Gradient Boosting, algorithm', 2, None, '___sec64'),
('Gradient Boosting, Examples of Regression',
2,
None,
- '___sec69'),
+ '___sec65'),
('Gradient Boosting, Classification Example',
2,
None,
- '___sec70'),
- ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec71'),
- ('Regression Case', 2, None, '___sec72'),
- ('Xgboost on the Cancer Data', 2, None, '___sec73')]}
+ '___sec66'),
+ ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec67'),
+ ('Regression Case', 2, None, '___sec68'),
+ ('Xgboost on the Cancer Data', 2, None, '___sec69')]}
end of tocinfo -->
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
@@ -1742,9 +1542,9 @@ a decision tree wth different depths and perform a bootstrap aggregate (in this
from sklearn.utils import resample
from sklearn.tree import DecisionTreeRegressor
-n = 100
+n = 1000
n_boostraps = 100
-maxdepth = 8
+maxdepth = 10
# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
@@ -1755,23 +1555,17 @@ variance = np.zeros(maxdepth)
polydegree = np.zeros(maxdepth)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-# we produce a simple tree first as benchmark
+# we produce a simple tree first as benchmark, no scaling
simpletree = DecisionTreeRegressor(max_depth=3)
-simpletree.fit(X_train_scaled, y_train)
-simpleprediction = simpletree.predict(X_test_scaled)
+simpletree.fit(X_train, y_train)
+simpleprediction = simpletree.predict(X_test)
for degree in range(1,maxdepth):
model = DecisionTreeRegressor(max_depth=degree)
y_pred = np.empty((y_test.shape[0], n_boostraps))
for i in range(n_boostraps):
- x_, y_ = resample(X_train_scaled, y_train)
+ x_, y_ = resample(X_train, y_train)
model.fit(x_, y_)
- y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+ y_pred[:, i] = model.predict(X_test)#.ravel()
polydegree[degree] = degree
error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
@@ -1783,7 +1577,7 @@ simpleprediction = simpletree.predict(X_test_scaled)
print('Var:', variance[degree])
print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
print(mse_simpletree)
plt.xlim(1,maxdepth)
plt.plot(polydegree, error, label='MSE')
@@ -1796,7 +1590,7 @@ plt.show()
The idea behind boosting, and voting as well can be phrased as follows:
@@ -1819,7 +1613,7 @@ Decision trees play an important role as our weak classifier. They serve as the
The simplest case is a so-called voting ensemble. To illustrate this,
@@ -1849,7 +1643,7 @@ numbers kicking in.
@@ -1895,7 +1689,7 @@ DATA_ID = "DataFiles/"
@@ -1925,7 +1719,7 @@ plt.show()
We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
@@ -1978,7 +1772,7 @@ voting_clf.fit(X_train, y_train)
@@ -2037,7 +1831,7 @@ voting_clf.fit(X_train, y_train)
Random forests provide an improvement over bagged trees by way of a
@@ -2081,7 +1875,7 @@ this setting.
@@ -2107,7 +1901,7 @@ We will grow of forest of say \( B \) trees.
@@ -2191,7 +1985,7 @@ discrimination threshold is varied. It plots the true positive rate against the
@@ -2213,7 +2007,7 @@ np.sum(y_pred == y_pred_rf) / len(y_pred)
The basic idea is to combine weak classifiers in order to create a good
@@ -2230,7 +2024,7 @@ them with a factor.
Boosting is a way of fitting an additive expansion in a set of
@@ -2282,7 +2076,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re
The way we proceed is as follows (here we specialize to the squared-error cost function)
@@ -2307,7 +2101,7 @@ at the internal nodes, and the predictions at the terminal nodes.
To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
@@ -2355,7 +2149,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma
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
@@ -2390,7 +2184,7 @@ $$
In our iterative procedure we define thus
@@ -2418,7 +2212,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
First, for any \( \beta > 0 \), we optimize \( G \) by setting
@@ -2462,7 +2256,7 @@ $$
The algorithm here is rather straightforward. Assume that our weak
@@ -2484,7 +2278,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co
With the above definitions we are now ready to set up the algorithm for AdaBoost.
@@ -2524,7 +2318,7 @@ observations that are missed in the previous iterations.
Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
@@ -2557,7 +2351,7 @@ plt.show()
Gradient boosting is again a similar technique to Adaptive boosting,
@@ -2572,7 +2366,7 @@ function was the least squares 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
@@ -2607,7 +2401,7 @@ $$
Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
@@ -2625,7 +2419,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(
Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
@@ -2656,7 +2450,7 @@ The way we proceed in an iterative fashion is to
@@ -2710,7 +2504,7 @@ plt.show()
@@ -2758,7 +2552,7 @@ plt.show()
XGBoost or Extreme Gradient
@@ -2779,7 +2573,7 @@ It is now the algorithm which wins essentially all ML competitions!!!
@@ -2834,7 +2628,7 @@ plt.show()
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.
diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html
index 497127df5..55238ff0a 100644
--- a/doc/pub/week45/html/week45.html
+++ b/doc/pub/week45/html/week45.html
@@ -126,81 +126,74 @@ div { text-align: justify; text-justify: inter-word; }
('An Overview of Ensemble Methods', 2, None, '___sec37'),
('Bagging', 2, None, '___sec38'),
('More bagging', 2, None, '___sec39'),
- ('Simple Voting Example, head or tail', 2, None, '___sec40'),
- ('Using the Voting Classifier', 2, None, '___sec41'),
- ('Please, not the moons again! Voting and Bagging',
- 2,
- None,
- '___sec42'),
- ('Bagging Examples', 2, None, '___sec43'),
('Making your own Bootstrap: Changing the Level of the Decision '
'Tree',
2,
None,
- '___sec44'),
- ('Why Voting?', 2, None, '___sec45'),
- ('Tossing coins', 2, None, '___sec46'),
- ('Standard imports first', 2, None, '___sec47'),
- ('Simple Voting Example, head or tail', 2, None, '___sec48'),
- ('Using the Voting Classifier', 2, None, '___sec49'),
- ('Voting and Bagging', 2, None, '___sec50'),
- ('Random forests', 2, None, '___sec51'),
- ('Random Forest Algorithm', 2, None, '___sec52'),
+ '___sec40'),
+ ('Why Voting?', 2, None, '___sec41'),
+ ('Tossing coins', 2, None, '___sec42'),
+ ('Standard imports first', 2, None, '___sec43'),
+ ('Simple Voting Example, head or tail', 2, None, '___sec44'),
+ ('Using the Voting Classifier', 2, None, '___sec45'),
+ ('Voting and Bagging', 2, None, '___sec46'),
+ ('Random forests', 2, None, '___sec47'),
+ ('Random Forest Algorithm', 2, None, '___sec48'),
('Random Forests Compared with other Methods on the Cancer Data',
2,
None,
- '___sec53'),
+ '___sec49'),
('Compare Bagging on Trees with Random Forests',
2,
None,
- '___sec54'),
- ("Boosting, a Bird's Eye View", 2, None, '___sec55'),
+ '___sec50'),
+ ("Boosting, a Bird's Eye View", 2, None, '___sec51'),
('What is boosting? Additive Modelling/Iterative Fitting',
2,
None,
- '___sec56'),
+ '___sec52'),
('Iterative Fitting, Regression and Squared-error Cost Function',
2,
None,
- '___sec57'),
+ '___sec53'),
('Squared-Error Example and Iterative Fitting',
2,
None,
- '___sec58'),
+ '___sec54'),
('Iterative Fitting, Classification and AdaBoost',
2,
None,
- '___sec59'),
- ('Adaptive Boosting, AdaBoost', 2, None, '___sec60'),
- ('Building up AdaBoost', 2, None, '___sec61'),
+ '___sec55'),
+ ('Adaptive Boosting, AdaBoost', 2, None, '___sec56'),
+ ('Building up AdaBoost', 2, None, '___sec57'),
('Adaptive boosting: AdaBoost, Basic Algorithm',
2,
None,
- '___sec62'),
- ('Basic Steps of AdaBoost', 2, None, '___sec63'),
- ('AdaBoost Examples', 2, None, '___sec64'),
+ '___sec58'),
+ ('Basic Steps of AdaBoost', 2, None, '___sec59'),
+ ('AdaBoost Examples', 2, None, '___sec60'),
('Gradient boosting: Basics with Steepest Descent/Functional '
'Gradient Descent',
2,
None,
- '___sec65'),
+ '___sec61'),
('The Squared-Error again! Steepest Descent',
2,
None,
- '___sec66'),
- ('Steepest Descent Example', 2, None, '___sec67'),
- ('Gradient Boosting, algorithm', 2, None, '___sec68'),
+ '___sec62'),
+ ('Steepest Descent Example', 2, None, '___sec63'),
+ ('Gradient Boosting, algorithm', 2, None, '___sec64'),
('Gradient Boosting, Examples of Regression',
2,
None,
- '___sec69'),
+ '___sec65'),
('Gradient Boosting, Classification Example',
2,
None,
- '___sec70'),
- ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec71'),
- ('Regression Case', 2, None, '___sec72'),
- ('Xgboost on the Cancer Data', 2, None, '___sec73')]}
+ '___sec66'),
+ ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec67'),
+ ('Regression Case', 2, None, '___sec68'),
+ ('Xgboost on the Cancer Data', 2, None, '___sec69')]}
end of tocinfo -->
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with
@@ -1747,9 +1547,9 @@ a decision tree wth different depths and perform a bootstrap aggregate (in this
from sklearn.utils import resample
from sklearn.tree import DecisionTreeRegressor
-n = 100
+n = 1000
n_boostraps = 100
-maxdepth = 8
+maxdepth = 10
# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
@@ -1760,23 +1560,17 @@ variance = np.<
polydegree = np.zeros(maxdepth)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-# we produce a simple tree first as benchmark
+# we produce a simple tree first as benchmark, no scaling
simpletree = DecisionTreeRegressor(max_depth=3)
-simpletree.fit(X_train_scaled, y_train)
-simpleprediction = simpletree.predict(X_test_scaled)
+simpletree.fit(X_train, y_train)
+simpleprediction = simpletree.predict(X_test)
for degree in range(1,maxdepth):
model = DecisionTreeRegressor(max_depth=degree)
y_pred = np.empty((y_test.shape[0], n_boostraps))
for i in range(n_boostraps):
- x_, y_ = resample(X_train_scaled, y_train)
+ x_, y_ = resample(X_train, y_train)
model.fit(x_, y_)
- y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+ y_pred[:, i] = model.predict(X_test)#.ravel()
polydegree[degree] = degree
error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
@@ -1788,7 +1582,7 @@ simpleprediction = simpletreeprint('Var:', variance[degree])
print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
print(mse_simpletree)
plt.xlim(1,maxdepth)
plt.plot(polydegree, error, label='MSE')
@@ -1801,7 +1595,7 @@ plt.show()
The idea behind boosting, and voting as well can be phrased as follows:
@@ -1824,7 +1618,7 @@ Decision trees play an important role as our weak classifier. They serve as the
The simplest case is a so-called voting ensemble. To illustrate this,
@@ -1854,7 +1648,7 @@ numbers kicking in.
@@ -1900,7 +1694,7 @@ DATA_ID = "
@@ -1930,7 +1724,7 @@ plt.show()
We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of Scikit-Learn.
@@ -1983,7 +1777,7 @@ voting_clf.fit(X_train, y_train)
@@ -2042,7 +1836,7 @@ voting_clf.fit(X_train, y_train)
Random forests provide an improvement over bagged trees by way of a
@@ -2086,7 +1880,7 @@ this setting.
@@ -2112,7 +1906,7 @@ We will grow of forest of say \( B \) trees.
@@ -2196,7 +1990,7 @@ discrimination threshold is varied. It plots the true positive rate against the
@@ -2218,7 +2012,7 @@ np.sum(y_pred =
The basic idea is to combine weak classifiers in order to create a good
@@ -2235,7 +2029,7 @@ them with a factor.
Boosting is a way of fitting an additive expansion in a set of
@@ -2287,7 +2081,7 @@ In iterative fitting or additive modeling, we minimize the cost function with re
The way we proceed is as follows (here we specialize to the squared-error cost function)
@@ -2312,7 +2106,7 @@ at the internal nodes, and the predictions at the terminal nodes.
To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
@@ -2360,7 +2154,7 @@ The solution to these two equations gives us in turn \( \beta_1 \) and \( \gamma
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
@@ -2395,7 +2189,7 @@ $$
In our iterative procedure we define thus
@@ -2423,7 +2217,7 @@ where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
First, for any \( \beta > 0 \), we optimize \( G \) by setting
@@ -2467,7 +2261,7 @@ $$
The algorithm here is rather straightforward. Assume that our weak
@@ -2489,7 +2283,7 @@ where the function \( I() \) is one if we misclassify and zero if we classify co
With the above definitions we are now ready to set up the algorithm for AdaBoost.
@@ -2529,7 +2323,7 @@ observations that are missed in the previous iterations.
Using Scikit-Learn it is easy to apply the adaptive boosting algorithm, as done here.
@@ -2562,7 +2356,7 @@ plt.show()
Gradient boosting is again a similar technique to Adaptive boosting,
@@ -2577,7 +2371,7 @@ function was the least squares 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
@@ -2612,7 +2406,7 @@ $$
Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
@@ -2630,7 +2424,7 @@ and find a new value for \( \rho_2=-1/2 \) and continue till we have reached \(
Steepest descent is however not much used, since it only optimizes \( f \) at a fixed set of \( n \) points,
@@ -2661,7 +2455,7 @@ The way we proceed in an iterative fashion is to
@@ -2715,7 +2509,7 @@ plt.show()
@@ -2763,7 +2557,7 @@ plt.show()
XGBoost or Extreme Gradient
@@ -2784,7 +2578,7 @@ It is now the algorithm which wins essentially all ML competitions!!!
@@ -2839,7 +2633,7 @@ plt.show()
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.
diff --git a/doc/pub/week45/ipynb/Results/FigureFiles/votingsimple.png b/doc/pub/week45/ipynb/Results/FigureFiles/votingsimple.png
index 564ba322c..30ec67491 100644
Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/votingsimple.png and b/doc/pub/week45/ipynb/Results/FigureFiles/votingsimple.png differ
diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz
index 1b3d5b1f4..285bd3bd0 100644
Binary files a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz and b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz differ
diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb
index 887022d0d..477dfbab6 100644
--- a/doc/pub/week45/ipynb/week45.ipynb
+++ b/doc/pub/week45/ipynb/week45.ipynb
@@ -1457,269 +1457,8 @@
"amount that the Gini index is decreased by splits over a given\n",
"predictor, averaged over all $B$ trees.\n",
"\n",
- "## Simple Voting Example, head or tail"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "heads_proba = 0.51\n",
- "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n",
- "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n",
- "plt.figure(figsize=(8,3.5))\n",
- "plt.plot(cumulative_heads_ratio)\n",
- "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n",
- "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n",
- "plt.xlabel(\"Number of coin tosses\")\n",
- "plt.ylabel(\"Heads ratio\")\n",
- "plt.legend(loc=\"lower right\")\n",
- "plt.axis([0, 10000, 0.42, 0.58])\n",
- "save_fig(\"votingsimple\")\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Using the Voting Classifier"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.datasets import make_moons\n",
"\n",
- "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
- "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
"\n",
- "from sklearn.ensemble import RandomForestClassifier\n",
- "from sklearn.ensemble import VotingClassifier\n",
- "from sklearn.linear_model import LogisticRegression\n",
- "from sklearn.svm import SVC\n",
- "\n",
- "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n",
- "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n",
- "svm_clf = SVC(gamma=\"auto\", random_state=42)\n",
- "\n",
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='hard')\n",
- "\n",
- "voting_clf.fit(X_train, y_train)\n",
- "\n",
- "from sklearn.metrics import accuracy_score\n",
- "\n",
- "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
- " clf.fit(X_train, y_train)\n",
- " y_pred = clf.predict(X_test)\n",
- " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n",
- "\n",
- "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n",
- "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n",
- "svm_clf = SVC(gamma=\"auto\", probability=True, random_state=42)\n",
- "\n",
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='soft')\n",
- "voting_clf.fit(X_train, y_train)\n",
- "\n",
- "from sklearn.metrics import accuracy_score\n",
- "\n",
- "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
- " clf.fit(X_train, y_train)\n",
- " y_pred = clf.predict(X_test)\n",
- " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Please, not the moons again! Voting and Bagging"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from sklearn.model_selection import train_test_split\n",
- "from sklearn.datasets import make_moons\n",
- "\n",
- "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
- "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
- "from sklearn.ensemble import RandomForestClassifier\n",
- "from sklearn.ensemble import VotingClassifier\n",
- "from sklearn.linear_model import LogisticRegression\n",
- "from sklearn.svm import SVC\n",
- "\n",
- "log_clf = LogisticRegression(random_state=42)\n",
- "rnd_clf = RandomForestClassifier(random_state=42)\n",
- "svm_clf = SVC(random_state=42)\n",
- "\n",
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='hard')\n",
- "voting_clf.fit(X_train, y_train)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from sklearn.metrics import accuracy_score\n",
- "\n",
- "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
- " clf.fit(X_train, y_train)\n",
- " y_pred = clf.predict(X_test)\n",
- " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "log_clf = LogisticRegression(random_state=42)\n",
- "rnd_clf = RandomForestClassifier(random_state=42)\n",
- "svm_clf = SVC(probability=True, random_state=42)\n",
- "\n",
- "voting_clf = VotingClassifier(\n",
- " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
- " voting='soft')\n",
- "voting_clf.fit(X_train, y_train)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from sklearn.metrics import accuracy_score\n",
- "\n",
- "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
- " clf.fit(X_train, y_train)\n",
- " y_pred = clf.predict(X_test)\n",
- " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Bagging Examples"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 21,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from sklearn.ensemble import BaggingClassifier\n",
- "from sklearn.tree import DecisionTreeClassifier\n",
- "\n",
- "bag_clf = BaggingClassifier(\n",
- " DecisionTreeClassifier(random_state=42), n_estimators=500,\n",
- " max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)\n",
- "bag_clf.fit(X_train, y_train)\n",
- "y_pred = bag_clf.predict(X_test)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from sklearn.metrics import accuracy_score\n",
- "print(accuracy_score(y_test, y_pred))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 23,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "tree_clf = DecisionTreeClassifier(random_state=42)\n",
- "tree_clf.fit(X_train, y_train)\n",
- "y_pred_tree = tree_clf.predict(X_test)\n",
- "print(accuracy_score(y_test, y_pred_tree))"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 24,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from matplotlib.colors import ListedColormap\n",
- "\n",
- "def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):\n",
- " x1s = np.linspace(axes[0], axes[1], 100)\n",
- " x2s = np.linspace(axes[2], axes[3], 100)\n",
- " x1, x2 = np.meshgrid(x1s, x2s)\n",
- " X_new = np.c_[x1.ravel(), x2.ravel()]\n",
- " y_pred = clf.predict(X_new).reshape(x1.shape)\n",
- " custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
- " plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
- " if contour:\n",
- " custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
- " plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
- " plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n",
- " plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n",
- " plt.axis(axes)\n",
- " plt.xlabel(r\"$x_1$\", fontsize=18)\n",
- " plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
- "plt.figure(figsize=(11,4))\n",
- "plt.subplot(121)\n",
- "plot_decision_boundary(tree_clf, X, y)\n",
- "plt.title(\"Decision Tree\", fontsize=14)\n",
- "plt.subplot(122)\n",
- "plot_decision_boundary(bag_clf, X, y)\n",
- "plt.title(\"Decision Trees with Bagging\", fontsize=14)\n",
- "save_fig(\"baggingtree\")\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
"## Making your own Bootstrap: Changing the Level of the Decision Tree\n",
"\n",
"Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n",
@@ -1728,7 +1467,7 @@
},
{
"cell_type": "code",
- "execution_count": 25,
+ "execution_count": 15,
"metadata": {
"collapsed": false
},
@@ -1742,9 +1481,9 @@
"from sklearn.utils import resample\n",
"from sklearn.tree import DecisionTreeRegressor\n",
"\n",
- "n = 100\n",
+ "n = 1000\n",
"n_boostraps = 100\n",
- "maxdepth = 8\n",
+ "maxdepth = 10\n",
"\n",
"# Make data set.\n",
"x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
@@ -1755,23 +1494,17 @@
"polydegree = np.zeros(maxdepth)\n",
"X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
"\n",
- "from sklearn.preprocessing import StandardScaler\n",
- "scaler = StandardScaler()\n",
- "scaler.fit(X_train)\n",
- "X_train_scaled = scaler.transform(X_train)\n",
- "X_test_scaled = scaler.transform(X_test)\n",
- "\n",
- "# we produce a simple tree first as benchmark\n",
+ "# we produce a simple tree first as benchmark, no scaling\n",
"simpletree = DecisionTreeRegressor(max_depth=3) \n",
- "simpletree.fit(X_train_scaled, y_train)\n",
- "simpleprediction = simpletree.predict(X_test_scaled)\n",
+ "simpletree.fit(X_train, y_train)\n",
+ "simpleprediction = simpletree.predict(X_test)\n",
"for degree in range(1,maxdepth):\n",
" model = DecisionTreeRegressor(max_depth=degree) \n",
" y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
" for i in range(n_boostraps):\n",
- " x_, y_ = resample(X_train_scaled, y_train)\n",
+ " x_, y_ = resample(X_train, y_train)\n",
" model.fit(x_, y_)\n",
- " y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n",
+ " y_pred[:, i] = model.predict(X_test)#.ravel()\n",
"\n",
" polydegree[degree] = degree\n",
" error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
@@ -1783,7 +1516,7 @@
" print('Var:', variance[degree])\n",
" print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
" \n",
- "mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)\n",
+ "mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))\n",
"print(mse_simpletree)\n",
"plt.xlim(1,maxdepth)\n",
"plt.plot(polydegree, error, label='MSE')\n",
@@ -1842,7 +1575,7 @@
},
{
"cell_type": "code",
- "execution_count": 26,
+ "execution_count": 16,
"metadata": {
"collapsed": false
},
@@ -1896,7 +1629,7 @@
},
{
"cell_type": "code",
- "execution_count": 27,
+ "execution_count": 17,
"metadata": {
"collapsed": false
},
@@ -1938,7 +1671,7 @@
},
{
"cell_type": "code",
- "execution_count": 28,
+ "execution_count": 18,
"metadata": {
"collapsed": false
},
@@ -1997,7 +1730,7 @@
},
{
"cell_type": "code",
- "execution_count": 29,
+ "execution_count": 19,
"metadata": {
"collapsed": false
},
@@ -2025,7 +1758,7 @@
},
{
"cell_type": "code",
- "execution_count": 30,
+ "execution_count": 20,
"metadata": {
"collapsed": false
},
@@ -2041,7 +1774,7 @@
},
{
"cell_type": "code",
- "execution_count": 31,
+ "execution_count": 21,
"metadata": {
"collapsed": false
},
@@ -2059,7 +1792,7 @@
},
{
"cell_type": "code",
- "execution_count": 32,
+ "execution_count": 22,
"metadata": {
"collapsed": false
},
@@ -2149,7 +1882,7 @@
},
{
"cell_type": "code",
- "execution_count": 33,
+ "execution_count": 23,
"metadata": {
"collapsed": false
},
@@ -2241,7 +1974,7 @@
},
{
"cell_type": "code",
- "execution_count": 34,
+ "execution_count": 24,
"metadata": {
"collapsed": false
},
@@ -2254,7 +1987,7 @@
},
{
"cell_type": "code",
- "execution_count": 35,
+ "execution_count": 25,
"metadata": {
"collapsed": false
},
@@ -2798,7 +2531,7 @@
},
{
"cell_type": "code",
- "execution_count": 36,
+ "execution_count": 26,
"metadata": {
"collapsed": false
},
@@ -2988,7 +2721,7 @@
},
{
"cell_type": "code",
- "execution_count": 37,
+ "execution_count": 27,
"metadata": {
"collapsed": false
},
@@ -3051,7 +2784,7 @@
},
{
"cell_type": "code",
- "execution_count": 38,
+ "execution_count": 28,
"metadata": {
"collapsed": false
},
@@ -3124,7 +2857,7 @@
},
{
"cell_type": "code",
- "execution_count": 39,
+ "execution_count": 29,
"metadata": {
"collapsed": false
},
@@ -3189,7 +2922,7 @@
},
{
"cell_type": "code",
- "execution_count": 40,
+ "execution_count": 30,
"metadata": {
"collapsed": false
},
diff --git a/doc/src/week45/week45.do.txt b/doc/src/week45/week45.do.txt
index 3bc775cc3..dbd5f0658 100644
--- a/doc/src/week45/week45.do.txt
+++ b/doc/src/week45/week45.do.txt
@@ -1148,184 +1148,6 @@ the context of bagging classification trees, we can add up the total
amount that the Gini index is decreased by splits over a given
predictor, averaged over all $B$ trees.
-!split
-===== Simple Voting Example, head or tail =====
-!bc pycod
-heads_proba = 0.51
-coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
-cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
-plt.figure(figsize=(8,3.5))
-plt.plot(cumulative_heads_ratio)
-plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
-plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
-plt.xlabel("Number of coin tosses")
-plt.ylabel("Heads ratio")
-plt.legend(loc="lower right")
-plt.axis([0, 10000, 0.42, 0.58])
-save_fig("votingsimple")
-plt.show()
-
-!ec
-
-!split
-===== Using the Voting Classifier =====
-!bc pycod
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-!ec
-
-!split
-===== Please, not the moons again! Voting and Bagging =====
-
-!bc pycod
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-voting_clf.fit(X_train, y_train)
-!ec
-
-!bc pycod
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-!ec
-
-!bc pycod
-log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-!ec
-
-!bc pycod
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-!ec
-
-!split
-===== Bagging Examples =====
-
-!bc pycod
-from sklearn.ensemble import BaggingClassifier
-from sklearn.tree import DecisionTreeClassifier
-
-bag_clf = BaggingClassifier(
- DecisionTreeClassifier(random_state=42), n_estimators=500,
- max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
-bag_clf.fit(X_train, y_train)
-y_pred = bag_clf.predict(X_test)
-!ec
-
-
-!bc pycod
-from sklearn.metrics import accuracy_score
-print(accuracy_score(y_test, y_pred))
-!ec
-
-!bc pycod
-tree_clf = DecisionTreeClassifier(random_state=42)
-tree_clf.fit(X_train, y_train)
-y_pred_tree = tree_clf.predict(X_test)
-print(accuracy_score(y_test, y_pred_tree))
-!ec
-
-!bc pycod
-from matplotlib.colors import ListedColormap
-
-def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
- x1s = np.linspace(axes[0], axes[1], 100)
- x2s = np.linspace(axes[2], axes[3], 100)
- x1, x2 = np.meshgrid(x1s, x2s)
- X_new = np.c_[x1.ravel(), x2.ravel()]
- y_pred = clf.predict(X_new).reshape(x1.shape)
- custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
- plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
- if contour:
- custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
- plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
- plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
- plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
- plt.axis(axes)
- plt.xlabel(r"$x_1$", fontsize=18)
- plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
-plt.figure(figsize=(11,4))
-plt.subplot(121)
-plot_decision_boundary(tree_clf, X, y)
-plt.title("Decision Tree", fontsize=14)
-plt.subplot(122)
-plot_decision_boundary(bag_clf, X, y)
-plt.title("Decision Trees with Bagging", fontsize=14)
-save_fig("baggingtree")
-plt.show()
-!ec
-
!split
@@ -1342,9 +1164,9 @@ from sklearn.pipeline import make_pipeline
from sklearn.utils import resample
from sklearn.tree import DecisionTreeRegressor
-n = 100
+n = 1000
n_boostraps = 100
-maxdepth = 8
+maxdepth = 10
# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
@@ -1355,23 +1177,17 @@ variance = np.zeros(maxdepth)
polydegree = np.zeros(maxdepth)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
-from sklearn.preprocessing import StandardScaler
-scaler = StandardScaler()
-scaler.fit(X_train)
-X_train_scaled = scaler.transform(X_train)
-X_test_scaled = scaler.transform(X_test)
-
-# we produce a simple tree first as benchmark
+# we produce a simple tree first as benchmark, no scaling
simpletree = DecisionTreeRegressor(max_depth=3)
-simpletree.fit(X_train_scaled, y_train)
-simpleprediction = simpletree.predict(X_test_scaled)
+simpletree.fit(X_train, y_train)
+simpleprediction = simpletree.predict(X_test)
for degree in range(1,maxdepth):
model = DecisionTreeRegressor(max_depth=degree)
y_pred = np.empty((y_test.shape[0], n_boostraps))
for i in range(n_boostraps):
- x_, y_ = resample(X_train_scaled, y_train)
+ x_, y_ = resample(X_train, y_train)
model.fit(x_, y_)
- y_pred[:, i] = model.predict(X_test_scaled)#.ravel()
+ y_pred[:, i] = model.predict(X_test)#.ravel()
polydegree[degree] = degree
error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
@@ -1383,7 +1199,7 @@ for degree in range(1,maxdepth):
print('Var:', variance[degree])
print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
-mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)
+mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))
print(mse_simpletree)
plt.xlim(1,maxdepth)
plt.plot(polydegree, error, label='MSE')
Simple Voting Example, head or tail
-Random Forest Algorithm
+The algorithm described here can be applied to both classification and regression problems.
-
-# Common imports
-import numpy as np
-import matplotlib
-import matplotlib.pyplot as plt
-from matplotlib.colors import ListedColormap
-plt.rcParams['axes.labelsize'] = 14
-plt.rcParams['xtick.labelsize'] = 12
-plt.rcParams['ytick.labelsize'] = 12
-
-heads_proba = 0.51
-coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
-cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
-plt.figure(figsize=(8,3.5))
-plt.plot(cumulative_heads_ratio)
-plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
-plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
-plt.xlabel("Number of coin tosses")
-plt.ylabel("Heads ratio")
-plt.legend(loc="lower right")
-plt.axis([0, 10000, 0.42, 0.58])
-save_fig("votingsimple")
-plt.show()
-
+
+
+
+
+
+
+
+Using the Voting Classifier
-
-Random Forests Compared with other Methods on the Cancer Data
from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
+
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
+from sklearn.ensemble import BaggingClassifier
+
+# 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)))
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
+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)))
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", random_state=42)
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", probability=True, random_state=42)
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+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()
Voting and Bagging
-
+Compare Bagging on Trees with Random Forests
from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
+
bag_clf = BaggingClassifier(
+ DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
+ n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
+
bag_clf.fit(X_train, y_train)
+y_pred = bag_clf.predict(X_test)
from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
+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)
Random forests
+Boosting, a Bird's Eye View
Random Forest Algorithm
-The algorithm described here can be applied to both classification and regression problems.
+What is boosting? Additive Modelling/Iterative Fitting
-
+
-
+
-
+$$
+\sigma(t) = \frac{1}{1+\exp{(-t)}},
+$$
-Random Forests Compared with other Methods on the Cancer Data
-import matplotlib.pyplot as plt
-import numpy as np
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import load_breast_cancer
-from sklearn.svm import SVC
-from sklearn.linear_model import LogisticRegression
-from sklearn.tree import DecisionTreeClassifier
-from sklearn.ensemble import BaggingClassifier
-
-# 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()
-
Iterative Fitting, Regression and Squared-error Cost Function
+
+
+
+
+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.
Compare Bagging on Trees with Random Forests
-Squared-Error Example and Iterative Fitting
-
-bag_clf = BaggingClassifier(
- DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
- n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
-
bag_clf.fit(X_train, y_train)
-y_pred = bag_clf.predict(X_test)
-from sklearn.ensemble import RandomForestClassifier
-rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
-rnd_clf.fit(X_train, y_train)
-y_pred_rf = rnd_clf.predict(X_test)
-np.sum(y_pred == y_pred_rf) / len(y_pred)
-
Boosting, a Bird's Eye View
+Iterative Fitting, Classification and AdaBoost
What is boosting? Additive Modelling/Iterative Fitting
+Adaptive Boosting, AdaBoost
Iterative Fitting, Regression and Squared-error Cost Function
+Building up AdaBoost
-
+Squared-Error Example and Iterative Fitting
+Adaptive boosting: AdaBoost, Basic Algorithm
Iterative Fitting, Classification and AdaBoost
+Basic Steps of AdaBoost
+
$$
-\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
+\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},
$$
-
+
+
+Adaptive Boosting, AdaBoost
+AdaBoost Examples
from sklearn.ensemble import AdaBoostClassifier
-$$
-C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
-$$
+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)
-where we have defined \( w_i^m= \exp{(-y_if_{m-1}(x_i))} \).
+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()
+
Building up AdaBoost
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
Adaptive boosting: AdaBoost, Basic Algorithm
+The Squared-Error again! Steepest Descent
Basic Steps of AdaBoost
+Steepest Descent Example
-
-
+Optimizing with respect to \( \rho \) we obtain (taking the derivative) that \( \rho_1 = -1/2 \). We have then that
$$
-\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},
+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,
+$$
-
-
-
-AdaBoost Examples
+Gradient Boosting, algorithm
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()
-
+
+
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-
+Gradient Boosting, Examples of Regression
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.ensemble import GradientBoostingRegressor
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(1,maxdegree):
+ model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+save_fig("gdregression")
+plt.show()
+
The Squared-Error again! Steepest Descent
-
+Gradient Boosting, Classification Example
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+from sklearn.datasets import load_breast_cancer
+import scikitplot as skplt
+from sklearn.ensemble import GradientBoostingClassifier
+from sklearn.model_selection import cross_validate
-
Steepest Descent Example
+XGBoost: Extreme Gradient Boosting
Gradient Boosting, algorithm
+Regression Case
import matplotlib.pyplot as plt
+import numpy as np
+from sklearn.model_selection import train_test_split
+import xgboost as xgb
+from sklearn.preprocessing import StandardScaler
+import scikitplot as skplt
+from sklearn.metrics import mean_squared_error
+
+n = 100
+maxdegree = 6
+
+# Make data set.
+x = np.linspace(-3, 3, n).reshape(-1, 1)
+y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
+
+error = np.zeros(maxdegree)
+bias = np.zeros(maxdegree)
+variance = np.zeros(maxdegree)
+polydegree = np.zeros(maxdegree)
+X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
+scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+for degree in range(maxdegree):
+ model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
+
+ model.fit(X_train_scaled,y_train)
+ y_pred = model.predict(X_test_scaled)
+ polydegree[degree] = degree
+ error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
+ bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
+ variance[degree] = np.mean( np.var(y_pred) )
+ print('Max depth:', degree)
+ print('Error:', error[degree])
+ print('Bias^2:', bias[degree])
+ print('Var:', variance[degree])
+ print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
+
+plt.xlim(1,maxdegree-1)
+plt.plot(polydegree, error, label='Error')
+plt.plot(polydegree, bias, label='bias')
+plt.plot(polydegree, variance, label='Variance')
+plt.legend()
+plt.show()
+
-
-
-
@@ -347,10 +360,6 @@ The way we proceed in an iterative fashion is to
diff --git a/doc/pub/week45/html/._week45-bs070.html b/doc/pub/week45/html/._week45-bs070.html
index 7bbac6dcf..ea93e9f5f 100644
--- a/doc/pub/week45/html/._week45-bs070.html
+++ b/doc/pub/week45/html/._week45-bs070.html
@@ -101,81 +101,74 @@ Automatically generated HTML file from DocOnce source
('An Overview of Ensemble Methods', 2, None, '___sec37'),
('Bagging', 2, None, '___sec38'),
('More bagging', 2, None, '___sec39'),
- ('Simple Voting Example, head or tail', 2, None, '___sec40'),
- ('Using the Voting Classifier', 2, None, '___sec41'),
- ('Please, not the moons again! Voting and Bagging',
- 2,
- None,
- '___sec42'),
- ('Bagging Examples', 2, None, '___sec43'),
('Making your own Bootstrap: Changing the Level of the Decision '
'Tree',
2,
None,
- '___sec44'),
- ('Why Voting?', 2, None, '___sec45'),
- ('Tossing coins', 2, None, '___sec46'),
- ('Standard imports first', 2, None, '___sec47'),
- ('Simple Voting Example, head or tail', 2, None, '___sec48'),
- ('Using the Voting Classifier', 2, None, '___sec49'),
- ('Voting and Bagging', 2, None, '___sec50'),
- ('Random forests', 2, None, '___sec51'),
- ('Random Forest Algorithm', 2, None, '___sec52'),
+ '___sec40'),
+ ('Why Voting?', 2, None, '___sec41'),
+ ('Tossing coins', 2, None, '___sec42'),
+ ('Standard imports first', 2, None, '___sec43'),
+ ('Simple Voting Example, head or tail', 2, None, '___sec44'),
+ ('Using the Voting Classifier', 2, None, '___sec45'),
+ ('Voting and Bagging', 2, None, '___sec46'),
+ ('Random forests', 2, None, '___sec47'),
+ ('Random Forest Algorithm', 2, None, '___sec48'),
('Random Forests Compared with other Methods on the Cancer Data',
2,
None,
- '___sec53'),
+ '___sec49'),
('Compare Bagging on Trees with Random Forests',
2,
None,
- '___sec54'),
- ("Boosting, a Bird's Eye View", 2, None, '___sec55'),
+ '___sec50'),
+ ("Boosting, a Bird's Eye View", 2, None, '___sec51'),
('What is boosting? Additive Modelling/Iterative Fitting',
2,
None,
- '___sec56'),
+ '___sec52'),
('Iterative Fitting, Regression and Squared-error Cost Function',
2,
None,
- '___sec57'),
+ '___sec53'),
('Squared-Error Example and Iterative Fitting',
2,
None,
- '___sec58'),
+ '___sec54'),
('Iterative Fitting, Classification and AdaBoost',
2,
None,
- '___sec59'),
- ('Adaptive Boosting, AdaBoost', 2, None, '___sec60'),
- ('Building up AdaBoost', 2, None, '___sec61'),
+ '___sec55'),
+ ('Adaptive Boosting, AdaBoost', 2, None, '___sec56'),
+ ('Building up AdaBoost', 2, None, '___sec57'),
('Adaptive boosting: AdaBoost, Basic Algorithm',
2,
None,
- '___sec62'),
- ('Basic Steps of AdaBoost', 2, None, '___sec63'),
- ('AdaBoost Examples', 2, None, '___sec64'),
+ '___sec58'),
+ ('Basic Steps of AdaBoost', 2, None, '___sec59'),
+ ('AdaBoost Examples', 2, None, '___sec60'),
('Gradient boosting: Basics with Steepest Descent/Functional '
'Gradient Descent',
2,
None,
- '___sec65'),
+ '___sec61'),
('The Squared-Error again! Steepest Descent',
2,
None,
- '___sec66'),
- ('Steepest Descent Example', 2, None, '___sec67'),
- ('Gradient Boosting, algorithm', 2, None, '___sec68'),
+ '___sec62'),
+ ('Steepest Descent Example', 2, None, '___sec63'),
+ ('Gradient Boosting, algorithm', 2, None, '___sec64'),
('Gradient Boosting, Examples of Regression',
2,
None,
- '___sec69'),
+ '___sec65'),
('Gradient Boosting, Classification Example',
2,
None,
- '___sec70'),
- ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec71'),
- ('Regression Case', 2, None, '___sec72'),
- ('Xgboost on the Cancer Data', 2, None, '___sec73')]}
+ '___sec66'),
+ ('XGBoost: Extreme Gradient Boosting', 2, None, '___sec67'),
+ ('Regression Case', 2, None, '___sec68'),
+ ('Xgboost on the Cancer Data', 2, None, '___sec69')]}
end of tocinfo -->
@@ -253,40 +246,36 @@ MathJax.Hub.Config({
Gradient Boosting, Examples of Regression
+Xgboost on the Cancer Data
+
+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
+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
-from sklearn.metrics import mean_squared_error
+import xgboost as xgb
+# Load the data
+cancer = load_breast_cancer()
-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)
+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(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]))
+xg_clf = xgb.XGBClassifier()
+xg_clf.fit(X_train_scaled,y_train)
-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")
+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()
Simple Voting Example, head or tail
-heads_proba = 0.51
-coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
-cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
-plt.figure(figsize=(8,3.5))
-plt.plot(cumulative_heads_ratio)
-plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
-plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
-plt.xlabel("Number of coin tosses")
-plt.ylabel("Heads ratio")
-plt.legend(loc="lower right")
-plt.axis([0, 10000, 0.42, 0.58])
-save_fig("votingsimple")
-plt.show()
-
Using the Voting Classifier
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
Please, not the moons again! Voting and Bagging
-
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
Bagging Examples
-
-from sklearn.ensemble import BaggingClassifier
-from sklearn.tree import DecisionTreeClassifier
-
-bag_clf = BaggingClassifier(
- DecisionTreeClassifier(random_state=42), n_estimators=500,
- max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
-bag_clf.fit(X_train, y_train)
-y_pred = bag_clf.predict(X_test)
-
from sklearn.metrics import accuracy_score
-print(accuracy_score(y_test, y_pred))
-
tree_clf = DecisionTreeClassifier(random_state=42)
-tree_clf.fit(X_train, y_train)
-y_pred_tree = tree_clf.predict(X_test)
-print(accuracy_score(y_test, y_pred_tree))
-
from matplotlib.colors import ListedColormap
-
-def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
- x1s = np.linspace(axes[0], axes[1], 100)
- x2s = np.linspace(axes[2], axes[3], 100)
- x1, x2 = np.meshgrid(x1s, x2s)
- X_new = np.c_[x1.ravel(), x2.ravel()]
- y_pred = clf.predict(X_new).reshape(x1.shape)
- custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
- plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
- if contour:
- custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
- plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
- plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
- plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
- plt.axis(axes)
- plt.xlabel(r"$x_1$", fontsize=18)
- plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
-plt.figure(figsize=(11,4))
-plt.subplot(121)
-plot_decision_boundary(tree_clf, X, y)
-plt.title("Decision Tree", fontsize=14)
-plt.subplot(122)
-plot_decision_boundary(bag_clf, X, y)
-plt.title("Decision Trees with Bagging", fontsize=14)
-save_fig("baggingtree")
-plt.show()
-
Making your own Bootstrap: Changing the Level of the Decision Tree
+Making your own Bootstrap: Changing the Level of the Decision Tree
Why Voting?
+Why Voting?
Tossing coins
+Tossing coins
Standard imports first
+Standard imports first
Simple Voting Example, head or tail
+Simple Voting Example, head or tail
Using the Voting Classifier
+Using the Voting Classifier
Voting and Bagging
+Voting and Bagging
Random forests
+Random forests
Random Forest Algorithm
+Random Forest Algorithm
The algorithm described here can be applied to both classification and regression problems.
Random Forests Compared with other Methods on the Cancer Data
+Random Forests Compared with other Methods on the Cancer Data
Compare Bagging on Trees with Random Forests
+Compare Bagging on Trees with Random Forests
Boosting, a Bird's Eye View
+Boosting, a Bird's Eye View
What is boosting? Additive Modelling/Iterative Fitting
+What is boosting? Additive Modelling/Iterative Fitting
Iterative Fitting, Regression and Squared-error Cost Function
+Iterative Fitting, Regression and Squared-error Cost Function
Squared-Error Example and Iterative Fitting
+Squared-Error Example and Iterative Fitting
Iterative Fitting, Classification and AdaBoost
+Iterative Fitting, Classification and AdaBoost
Adaptive Boosting, AdaBoost
+Adaptive Boosting, AdaBoost
Building up AdaBoost
+Building up AdaBoost
Adaptive boosting: AdaBoost, Basic Algorithm
+Adaptive boosting: AdaBoost, Basic Algorithm
Basic Steps of AdaBoost
+Basic Steps of AdaBoost
AdaBoost Examples
+AdaBoost Examples
Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
The Squared-Error again! Steepest Descent
+The Squared-Error again! Steepest Descent
Steepest Descent Example
+Steepest Descent Example
Gradient Boosting, algorithm
+Gradient Boosting, algorithm
Gradient Boosting, Examples of Regression
+Gradient Boosting, Examples of Regression
Gradient Boosting, Classification Example
+Gradient Boosting, Classification Example
XGBoost: Extreme Gradient Boosting
+XGBoost: Extreme Gradient Boosting
Regression Case
+Regression Case
Xgboost on the Cancer Data
+Xgboost on the Cancer Data
-Simple Voting Example, head or tail
-heads_proba = 0.51
-coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
-cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
-plt.figure(figsize=(8,3.5))
-plt.plot(cumulative_heads_ratio)
-plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
-plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
-plt.xlabel("Number of coin tosses")
-plt.ylabel("Heads ratio")
-plt.legend(loc="lower right")
-plt.axis([0, 10000, 0.42, 0.58])
-save_fig("votingsimple")
-plt.show()
-
-
-Using the Voting Classifier
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-
-Please, not the moons again! Voting and Bagging
-
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-
-Bagging Examples
-
-from sklearn.ensemble import BaggingClassifier
-from sklearn.tree import DecisionTreeClassifier
-
-bag_clf = BaggingClassifier(
- DecisionTreeClassifier(random_state=42), n_estimators=500,
- max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
-bag_clf.fit(X_train, y_train)
-y_pred = bag_clf.predict(X_test)
-
from sklearn.metrics import accuracy_score
-print(accuracy_score(y_test, y_pred))
-
tree_clf = DecisionTreeClassifier(random_state=42)
-tree_clf.fit(X_train, y_train)
-y_pred_tree = tree_clf.predict(X_test)
-print(accuracy_score(y_test, y_pred_tree))
-
from matplotlib.colors import ListedColormap
-
-def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
- x1s = np.linspace(axes[0], axes[1], 100)
- x2s = np.linspace(axes[2], axes[3], 100)
- x1, x2 = np.meshgrid(x1s, x2s)
- X_new = np.c_[x1.ravel(), x2.ravel()]
- y_pred = clf.predict(X_new).reshape(x1.shape)
- custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
- plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
- if contour:
- custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
- plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
- plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
- plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
- plt.axis(axes)
- plt.xlabel(r"$x_1$", fontsize=18)
- plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
-plt.figure(figsize=(11,4))
-plt.subplot(121)
-plot_decision_boundary(tree_clf, X, y)
-plt.title("Decision Tree", fontsize=14)
-plt.subplot(122)
-plot_decision_boundary(bag_clf, X, y)
-plt.title("Decision Trees with Bagging", fontsize=14)
-save_fig("baggingtree")
-plt.show()
-
-
-Making your own Bootstrap: Changing the Level of the Decision Tree
+Making your own Bootstrap: Changing the Level of the Decision Tree
-Why Voting?
+Why Voting?
-Tossing coins
+Tossing coins
-Standard imports first
+Standard imports first
-Simple Voting Example, head or tail
+Simple Voting Example, head or tail
-Using the Voting Classifier
+Using the Voting Classifier
-Voting and Bagging
+Voting and Bagging
-Random forests
+Random forests
-Random Forest Algorithm
+Random Forest Algorithm
The algorithm described here can be applied to both classification and regression problems.
-Random Forests Compared with other Methods on the Cancer Data
+Random Forests Compared with other Methods on the Cancer Data
-Compare Bagging on Trees with Random Forests
+Compare Bagging on Trees with Random Forests
-Boosting, a Bird's Eye View
+Boosting, a Bird's Eye View
-What is boosting? Additive Modelling/Iterative Fitting
+What is boosting? Additive Modelling/Iterative Fitting
-Iterative Fitting, Regression and Squared-error Cost Function
+Iterative Fitting, Regression and Squared-error Cost Function
-Squared-Error Example and Iterative Fitting
+Squared-Error Example and Iterative Fitting
-Iterative Fitting, Classification and AdaBoost
+Iterative Fitting, Classification and AdaBoost
-Adaptive Boosting, AdaBoost
+Adaptive Boosting, AdaBoost
-Building up AdaBoost
+Building up AdaBoost
-Adaptive boosting: AdaBoost, Basic Algorithm
+Adaptive boosting: AdaBoost, Basic Algorithm
-Basic Steps of AdaBoost
+Basic Steps of AdaBoost
-AdaBoost Examples
+AdaBoost Examples
-Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-The Squared-Error again! Steepest Descent
+The Squared-Error again! Steepest Descent
-Steepest Descent Example
+Steepest Descent Example
-Gradient Boosting, algorithm
+Gradient Boosting, algorithm
-Gradient Boosting, Examples of Regression
+Gradient Boosting, Examples of Regression
-Gradient Boosting, Classification Example
+Gradient Boosting, Classification Example
-XGBoost: Extreme Gradient Boosting
+XGBoost: Extreme Gradient Boosting
-Regression Case
+Regression Case
-Xgboost on the Cancer Data
+Xgboost on the Cancer Data
-Simple Voting Example, head or tail
-heads_proba = 0.51
-coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
-cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
-plt.figure(figsize=(8,3.5))
-plt.plot(cumulative_heads_ratio)
-plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
-plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
-plt.xlabel("Number of coin tosses")
-plt.ylabel("Heads ratio")
-plt.legend(loc="lower right")
-plt.axis([0, 10000, 0.42, 0.58])
-save_fig("votingsimple")
-plt.show()
-
-
-Using the Voting Classifier
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-log_clf = LogisticRegression(solver="liblinear", random_state=42)
-rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
-svm_clf = SVC(gamma="auto", probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
-from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-
-Please, not the moons again! Voting and Bagging
-
-from sklearn.model_selection import train_test_split
-from sklearn.datasets import make_moons
-
-X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
-X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
-from sklearn.ensemble import RandomForestClassifier
-from sklearn.ensemble import VotingClassifier
-from sklearn.linear_model import LogisticRegression
-from sklearn.svm import SVC
-
-log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='hard')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
log_clf = LogisticRegression(random_state=42)
-rnd_clf = RandomForestClassifier(random_state=42)
-svm_clf = SVC(probability=True, random_state=42)
-
-voting_clf = VotingClassifier(
- estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
- voting='soft')
-voting_clf.fit(X_train, y_train)
-
from sklearn.metrics import accuracy_score
-
-for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
- print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
-
-
-Bagging Examples
-
-from sklearn.ensemble import BaggingClassifier
-from sklearn.tree import DecisionTreeClassifier
-
-bag_clf = BaggingClassifier(
- DecisionTreeClassifier(random_state=42), n_estimators=500,
- max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)
-bag_clf.fit(X_train, y_train)
-y_pred = bag_clf.predict(X_test)
-
from sklearn.metrics import accuracy_score
-print(accuracy_score(y_test, y_pred))
-
tree_clf = DecisionTreeClassifier(random_state=42)
-tree_clf.fit(X_train, y_train)
-y_pred_tree = tree_clf.predict(X_test)
-print(accuracy_score(y_test, y_pred_tree))
-
from matplotlib.colors import ListedColormap
-
-def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):
- x1s = np.linspace(axes[0], axes[1], 100)
- x2s = np.linspace(axes[2], axes[3], 100)
- x1, x2 = np.meshgrid(x1s, x2s)
- X_new = np.c_[x1.ravel(), x2.ravel()]
- y_pred = clf.predict(X_new).reshape(x1.shape)
- custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])
- plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
- if contour:
- custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])
- plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
- plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha)
- plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha)
- plt.axis(axes)
- plt.xlabel(r"$x_1$", fontsize=18)
- plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
-plt.figure(figsize=(11,4))
-plt.subplot(121)
-plot_decision_boundary(tree_clf, X, y)
-plt.title("Decision Tree", fontsize=14)
-plt.subplot(122)
-plot_decision_boundary(bag_clf, X, y)
-plt.title("Decision Trees with Bagging", fontsize=14)
-save_fig("baggingtree")
-plt.show()
-
-
-Making your own Bootstrap: Changing the Level of the Decision Tree
+Making your own Bootstrap: Changing the Level of the Decision Tree
-Why Voting?
+Why Voting?
-Tossing coins
+Tossing coins
-Standard imports first
+Standard imports first
-Simple Voting Example, head or tail
+Simple Voting Example, head or tail
-Using the Voting Classifier
+Using the Voting Classifier
-Voting and Bagging
+Voting and Bagging
-Random forests
+Random forests
-Random Forest Algorithm
+Random Forest Algorithm
The algorithm described here can be applied to both classification and regression problems.
-Random Forests Compared with other Methods on the Cancer Data
+Random Forests Compared with other Methods on the Cancer Data
-Compare Bagging on Trees with Random Forests
+Compare Bagging on Trees with Random Forests
-Boosting, a Bird's Eye View
+Boosting, a Bird's Eye View
-What is boosting? Additive Modelling/Iterative Fitting
+What is boosting? Additive Modelling/Iterative Fitting
-Iterative Fitting, Regression and Squared-error Cost Function
+Iterative Fitting, Regression and Squared-error Cost Function
-Squared-Error Example and Iterative Fitting
+Squared-Error Example and Iterative Fitting
-Iterative Fitting, Classification and AdaBoost
+Iterative Fitting, Classification and AdaBoost
-Adaptive Boosting, AdaBoost
+Adaptive Boosting, AdaBoost
-Building up AdaBoost
+Building up AdaBoost
-Adaptive boosting: AdaBoost, Basic Algorithm
+Adaptive boosting: AdaBoost, Basic Algorithm
-Basic Steps of AdaBoost
+Basic Steps of AdaBoost
-AdaBoost Examples
+AdaBoost Examples
-Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
+Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent
-The Squared-Error again! Steepest Descent
+The Squared-Error again! Steepest Descent
-Steepest Descent Example
+Steepest Descent Example
-Gradient Boosting, algorithm
+Gradient Boosting, algorithm
-Gradient Boosting, Examples of Regression
+Gradient Boosting, Examples of Regression
-Gradient Boosting, Classification Example
+Gradient Boosting, Classification Example
-XGBoost: Extreme Gradient Boosting
+XGBoost: Extreme Gradient Boosting
-Regression Case
+Regression Case
-Xgboost on the Cancer Data
+Xgboost on the Cancer Data