<jupyter_start><jupyter_text>[mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course   Author: <NAME>, ODS Slack krotix      Tutorial  Yet another ensemble learning helper ![title](https://static1.squarespace.com/static/57dc396a03596e8da9fe6b73/t/57eef283b3db2ba633355a07/1480477568336/UBC_Bands.jpg) Image by Brian Hawkes  What does ensemble learning mean? **Ensemble learning** - this is a method use multiple learning algorithms to obtain(I'd say usually it so, but not in any cases) better predictive performance than could be obtained from any of the constituent learning algorithms alone.The most common techniques are:* boosting* bagging* stackingWe are looking at some meta-algorithms to make an ensemble, which can improve the performance of a metric, get a better speed of experimenting and simplify code.I would like to show several libraries for ensambling in python:* https://github.com/rasbt/mlxtend.git - a library of useful tools for the day-to-day data science tasks.* https://github.com/flennerhag/mlens - a library for high performance ensemble learning.* https://github.com/Menelau/DESlib - an easy-to-use ensemble learning library focused on the implementation of the state-of-the-art techniques for dynamic classifier and ensemble selection.We will understand the use of different libraries on a simple example and plot of decision boundaries to visualize differences.   Installation<jupyter_code>!pip install mlxtend
!pip install mlens
!pip install deslib<jupyter_output><empty_output><jupyter_text>Prepare our notebook to further experiments:* import all libraries* load example data and split it* make classifiers for comparison* create utility functionWe'll use Iris dataset as an example.Features* Sepal length* Sepal width* Petal length* Petal widthNumber of samples: 150.Target variable (discrete): {50x Setosa, 50x Versicolor, 50x Virginica}<jupyter_code>import itertools
import warnings

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
# common libraries
import numpy as np
from deslib.dcs import MCB
from deslib.des.knora_e import KNORAE
from deslib.static import StaticSelection
from mlens.ensemble import (BlendEnsemble, SequentialEnsemble, Subsemble,
                            SuperLearner)
from mlxtend.classifier import (EnsembleVoteClassifier, StackingClassifier,
                                StackingCVClassifier)
from mlxtend.data import iris_data
from mlxtend.plotting import plot_decision_regions
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

warnings.filterwarnings("ignore")
# random seed
seed = 10

# Loading example data
X, y = iris_data()
X = X[:, [0, 2]]

# split the data into training and test data
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=seed
)
# Initializing several classifiers
clf1 = LogisticRegression(random_state=seed)
clf2 = RandomForestClassifier(random_state=seed)
clf3 = SVC(random_state=seed, probability=True)
def compare(classifier, X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test):
    # Plotting Decision Regions
    gs = gridspec.GridSpec(2, 2)
    fig = plt.figure(figsize=(10, 8))

    # Label for our classifiers
    labels = ["Logistic Regression", "Random Forest", "RBF kernel SVM", "Ensemble"]

    classifiers = [clf1, clf2, clf3, classifier]
    for clf, label, grid in zip(
        classifiers, labels, itertools.product([0, 1], repeat=2)
    ):
        clf.fit(X, y)
        ax = plt.subplot(gs[grid[0], grid[1]])
        fig = plot_decision_regions(X=X, y=y, clf=clf, legend=2)
        plt.title(label)

    plt.show()

    for clf, label in zip(classifiers, labels):
        print(label)
        print(classification_report(clf.predict(X_test), y_test))<jupyter_output><empty_output><jupyter_text>Mlxtend Mlxtend classes:* EnsembleVoteClassifier - a majority voting helper for classification* StackingClassifier - an ensemble-learning meta-classifier for stacking* StackingCVClassifier - an ensemble-learning meta-classifier for stacking using cross-validation to prepare the inputs for the level-2 classifier to prevent overfittingLet's discover how we can use it by examples.  EnsembleVoteClassifierTo get more information look https://rasbt.github.io/mlxtend/user_guide/classifier/EnsembleVoteClassifier/<jupyter_code>eclf = EnsembleVoteClassifier(clfs=[clf1, clf2, clf3], weights=[2, 1, 1], voting="soft")
compare(eclf)<jupyter_output><empty_output><jupyter_text>StackingClassifierTo get more information look https://rasbt.github.io/mlxtend/user_guide/classifier/StackingClassifier/<jupyter_code>sclf = StackingClassifier(
    classifiers=[clf1, clf2, clf3], meta_classifier=LogisticRegression()
)
compare(sclf)<jupyter_output><empty_output><jupyter_text>StackingCVClassifierTo get more information look https://rasbt.github.io/mlxtend/user_guide/classifier/StackingCVClassifier/<jupyter_code>scvclf = StackingCVClassifier(
    classifiers=[clf1, clf2, clf3], meta_classifier=LogisticRegression()
)
compare(scvclf)<jupyter_output><empty_output><jupyter_text>mlens Mlens has several useful classes:* SuperLearner - a stacking ensemble * Subsemble - a supervised ensemble algorithm that uses subsets of the full data to fit a layer* BlendEnsemble - a supervised ensemble uses the meta-learner to estimate the prediction matrix * SequentialEnsemble - a multi-layer ensemble learning  SuperLearnerTo get more information follow the link http://ml-ensemble.com/info/start/ensembles.htmlsuper-learner<jupyter_code>sl = SuperLearner(folds=5, random_state=seed, verbose=2)

# Build the first layer
sl.add([clf1, clf2, clf3])
# Attach the final meta-estimator
sl.add_meta(LogisticRegression())

compare(sl)<jupyter_output><empty_output><jupyter_text>SubsembleTo get more information follow the link http://ml-ensemble.com/info/start/ensembles.htmlsubsemble<jupyter_code>sub = Subsemble(partitions=3, random_state=seed, verbose=2, shuffle=True)

# Build the first layer
sub.add([clf1, clf2, clf3])
sub.add_meta(SVC())

compare(sub)<jupyter_output><empty_output><jupyter_text>BlendEnsembleTo get more information follow the link http://ml-ensemble.com/info/start/ensembles.htmlblend-ensemble<jupyter_code>be = BlendEnsemble(test_size=0.7, random_state=seed, verbose=2, shuffle=True)

# Build the first layer
be.add([clf1, clf2, clf3])
be.add_meta(LogisticRegression())

compare(be)<jupyter_output><empty_output><jupyter_text>SequentialEnsembleTo get more information follow the link http://ml-ensemble.com/info/start/ensembles.htmlsequential-ensemble<jupyter_code>se = SequentialEnsemble(random_state=seed, shuffle=True)

# The initial layer is a blended layer, same as a layer in the BlendEnsemble
se.add("blend", [clf1, clf2])

# The second layer is a stacked layer, same as a layer of the SuperLearner
se.add("stack", [clf1, clf3])

# The meta estimator is added as in any other ensemble
se.add_meta(SVC())

compare(se)<jupyter_output><empty_output><jupyter_text>DESlib DESlib has 23 algorithms different ensemble technics split into 3 group:* Dynamic Ensemble Selection(DES)* Dynamic Classifier Selection(DCS)* Baseline methods(static)let's try some of them from different groups:* KNORAE - Dynamic Ensemble Selection(DES) algorithm based on k-Nearest Oracle-Eliminate(KNORA-E)* MCB - Dynamic Classifier Selection(DCS) algorithm based on Multiple Classifier Behaviour (MCB)* StaticSelection - Baseline method(static) for an ensemble model that selects N classifiers with the best performanceTo get more information follow the link https://deslib.readthedocs.io/en/latest/api.html  KNORAE To get more information follow the link https://deslib.readthedocs.io/en/latest/modules/des/knora_e.html<jupyter_code>kne = KNORAE([clf1, clf2, clf3])
compare(kne)<jupyter_output><empty_output><jupyter_text>MCBTo get more information follow the link  https://deslib.readthedocs.io/en/latest/modules/dcs/mcb.html<jupyter_code>mcb = MCB([clf1, clf2, clf3])
compare(mcb)<jupyter_output><empty_output><jupyter_text>StaticSelectionTo get more information follow the link  https://deslib.readthedocs.io/en/latest/modules/static/static_selection.html<jupyter_code>ss = StaticSelection([clf1, clf2, clf3])
compare(ss)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08841354723707665, 'fraction_numerical': 0.01449792038027332, 'mean_word_length': 5.966887417218543, 'pattern_counts': {'":': 0, '<': 50, '<?xml version=': 0, '>': 50, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '301263', 'license': 'Unlicense', 'n_tokens_mistral': 2750, 'n_tokens_neox': 2609, 'n_words': 740, 'path': 'jupyter_english/tutorials/yet_another_ensemble_learning_helper_aleksandr_korotkov.ipynb', 'repo_name': 'salman394/AI-ml--course', 'size': '8427'}