TPOT-for-Automated-Machine-Learning-in-Python.jpg

TPOT for Automated Machine Learning in Python

Automated Machine Learning (AutoML) refers to techniques for automatically discovering well-performing models for predictive modeling tasks with very little user involvement.

TPOT is an open-source library for performing AutoML in Python. It makes use of the popular Scikit-Learn machine learning library for data transforms and machine learning algorithms and uses a Genetic Programming stochastic global search procedure to efficiently discover a top-performing model pipeline for a given dataset.

In this tutorial, you will discover how to use TPOT for AutoML with Scikit-Learn machine learning algorithms in Python.

After completing this tutorial, you will know:

  • TPOT is an open-source library for AutoML with scikit-learn data preparation and machine learning models.
  • How to use TPOT to automatically discover top-performing models for classification tasks.
  • How to use TPOT to automatically discover top-performing models for regression tasks.

Let’s get started.

TPOT for Automated Machine Learning in Python

TPOT for Automated Machine Learning in Python
Photo by Gwen, some rights reserved.

Tutorial Overview

This tutorial is divided into four parts; they are:

  • TPOT for Automated Machine Learning
  • Install and Use TPOT
  • TPOT for Classification
  • TPOT for Regression
  • TPOT for Automated Machine Learning

    Tree-based Pipeline Optimization Tool, or TPOT for short, is a Python library for automated machine learning.

    TPOT uses a tree-based structure to represent a model pipeline for a predictive modeling problem, including data preparation and modeling algorithms and model hyperparameters.

    … an evolutionary algorithm called the Tree-based Pipeline Optimization Tool (TPOT) that automatically designs and optimizes machine learning pipelines.

    — Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science, 2016.

    An optimization procedure is then performed to find a tree structure that performs best for a given dataset. Specifically, a genetic programming algorithm, designed to perform a stochastic global optimization on programs represented as trees.

    TPOT uses a version of genetic programming to automatically design and optimize a series of data transformations and machine learning models that attempt to maximize the classification accuracy for a given supervised learning data set.

    — Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science, 2016.

    The figure below taken from the TPOT paper shows the elements involved in the pipeline search, including data cleaning, feature selection, feature processing, feature construction, model selection, and hyperparameter optimization.

    Overview of the TPOT Pipeline Search

    Overview of the TPOT Pipeline Search
    Taken from: Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science, 2016.

    Now that we are familiar with what TPOT is, let’s look at how we can install and use TPOT to find an effective model pipeline.

    Install and Use TPOT

    The first step is to install the TPOT library, which can be achieved using pip, as follows:


    Once installed, we can import the library and print the version number to confirm it was installed successfully:


    Running the example prints the version number.

    Your version number should be the same or higher.


    Using TPOT is straightforward.

    It involves creating an instance of the TPOTRegressor or TPOTClassifier class, configuring it for the search, and then exporting the model pipeline that was found to achieve the best performance on your dataset.

    Configuring the class involves two main elements.

    The first is how models will be evaluated, e.g. the cross-validation scheme and performance metric. I recommend explicitly specifying a cross-validation class with your chosen configuration and the performance metric to use.

    For example, RepeatedKFold for regression with ‘neg_mean_absolute_error‘ metric for regression:


    Or a RepeatedStratifiedKFold for regression with ‘accuracy‘ metric for classification:


    The other element is the nature of the stochastic global search procedure.

    As an evolutionary algorithm, this involves setting configuration, such as the size of the population, the number of generations to run, and potentially crossover and mutation rates. The former importantly control the extent of the search; the latter can be left on default values if evolutionary search is new to you.

    For example, a modest population size of 100 and 5 or 10 generations is a good starting point.


    At the end of a search, a Pipeline is found that performs the best.

    This Pipeline can be exported as code into a Python file that you can later copy-and-paste into your own project.


    Now that we are familiar with how to use TPOT, let’s look at some worked examples with real data.

    TPOT for Classification

    In this section, we will use TPOT to discover a model for the sonar dataset.

    The sonar dataset is a standard machine learning dataset comprised of 208 rows of data with 60 numerical input variables and a target variable with two class values, e.g. binary classification.

    Using a test harness of repeated stratified 10-fold cross-validation with three repeats, a naive model can achieve an accuracy of about 53 percent. A top-performing model can achieve accuracy on this same test harness of about 88 percent. This provides the bounds of expected performance on this dataset.

    The dataset involves predicting whether sonar returns indicate a rock or simulated mine.

    No need to download the dataset; we will download it automatically as part of our worked examples.

    The example below downloads the dataset and summarizes its shape.


    Running the example downloads the dataset and splits it into input and output elements. As expected, we can see that there are 208 rows of data with 60 input variables.


    Next, let’s use TPOT to find a good model for the sonar dataset.

    First, we can define the method for evaluating models. We will use a good practice of repeated stratified k-fold cross-validation with three repeats and 10 folds.


    We will use a population size of 50 for five generations for the search and use all cores on the system by setting “n_jobs” to -1.


    Finally, we can start the search and ensure that the best-performing model is saved at the end of the run.


    Tying this together, the complete example is listed below.


    Running the example may take a few minutes, and you will see a progress bar on the command line.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    The accuracy of top-performing models will be reported along the way.


    In this case, we can see that the top-performing pipeline achieved the mean accuracy of about 86.6 percent. This is a skillful model, and close to a top-performing model on this dataset.

    The top-performing pipeline is then saved to a file named “tpot_sonar_best_model.py“.

    Opening this file, you can see that there is some generic code for loading a dataset and fitting the pipeline. An example is listed below.


    Note: as-is, this code does not execute, by design. It is a template that you can copy-and-paste into your project.

    In this case, we can see that the best-performing model is a pipeline comprised of a Naive Bayes model and a Gradient Boosting model.

    We can adapt this code to fit a final model on all available data and make a prediction for new data.

    The complete example is listed below.


    Running the example fits the best-performing model on the dataset and makes a prediction for a single row of new data.


    TPOT for Regression

    In this section, we will use TPOT to discover a model for the auto insurance dataset.

    The auto insurance dataset is a standard machine learning dataset comprised of 63 rows of data with one numerical input variable and a numerical target variable.

    Using a test harness of repeated stratified 10-fold cross-validation with three repeats, a naive model can achieve a mean absolute error (MAE) of about 66. A top-performing model can achieve a MAE on this same test harness of about 28. This provides the bounds of expected performance on this dataset.

    The dataset involves predicting the total amount in claims (thousands of Swedish Kronor) given the number of claims for different geographical regions.

    No need to download the dataset; we will download it automatically as part of our worked examples.

    The example below downloads the dataset and summarizes its shape.


    Running the example downloads the dataset and splits it into input and output elements. As expected, we can see that there are 63 rows of data with one input variable.


    Next, we can use TPOT to find a good model for the auto insurance dataset.

    First, we can define the method for evaluating models. We will use a good practice of repeated k-fold cross-validation with three repeats and 10 folds.


    We will use a population size of 50 for 5 generations for the search and use all cores on the system by setting “n_jobs” to -1.


    Finally, we can start the search and ensure that the best-performing model is saved at the end of the run.


    Tying this together, the complete example is listed below.


    Running the example may take a few minutes, and you will see a progress bar on the command line.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    The MAE of top-performing models will be reported along the way.


    In this case, we can see that the top-performing pipeline achieved the mean MAE of about 29.14. This is a skillful model, and close to a top-performing model on this dataset.

    The top-performing pipeline is then saved to a file named “tpot_insurance_best_model.py“.

    Opening this file, you can see that there is some generic code for loading a dataset and fitting the pipeline. An example is listed below.


    Note: as-is, this code does not execute, by design. It is a template that you can copy-paste into your project.

    In this case, we can see that the best-performing model is a pipeline comprised of a linear support vector machine model.

    We can adapt this code to fit a final model on all available data and make a prediction for new data.

    The complete example is listed below.


    Running the example fits the best-performing model on the dataset and makes a prediction for a single row of new data.


    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Summary

    In this tutorial, you discovered how to use TPOT for AutoML with Scikit-Learn machine learning algorithms in Python.

    Specifically, you learned:

    • TPOT is an open-source library for AutoML with scikit-learn data preparation and machine learning models.
    • How to use TPOT to automatically discover top-performing models for classification tasks.
    • How to use TPOT to automatically discover top-performing models for regression tasks.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Discover Fast Machine Learning in Python!

    Master Machine Learning With Python
    Develop Your Own Models in Minutes

    …with just a few lines of scikit-learn code

    Learn how in my new Ebook:
    Machine Learning Mastery With Python

    Covers self-study tutorials and end-to-end projects like:
    Loading data, visualization, modeling, tuning, and much more…

    Finally Bring Machine Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    Hypothesis-Test-for-Comparing-Machine-Learning-Algorithms.png

    Hypothesis Test for Comparing Machine Learning Algorithms

    Machine learning models are chosen based on their mean performance, often calculated using k-fold cross-validation.

    The algorithm with the best mean performance is expected to be better than those algorithms with worse mean performance. But what if the difference in the mean performance is caused by a statistical fluke?

    The solution is to use a statistical hypothesis test to evaluate whether the difference in the mean performance between any two algorithms is real or not.

    In this tutorial, you will discover how to use statistical hypothesis tests for comparing machine learning algorithms.

    After completing this tutorial, you will know:

    • Performing model selection based on the mean model performance can be misleading.
    • The five repeats of two-fold cross-validation with a modified Student’s t-Test is a good practice for comparing machine learning algorithms.
    • How to use the MLxtend machine learning to compare algorithms using a statistical hypothesis test.

    Kick-start your project with my new book Statistics for Machine Learning, including step-by-step tutorials and the Python source code files for all examples.

    Let’s get started.

    Hypothesis Test for Comparing Machine Learning Algorithms

    Hypothesis Test for Comparing Machine Learning Algorithms
    Photo by Frank Shepherd, some rights reserved.

    Tutorial Overview

    This tutorial is divided into three parts; they are:

  • Hypothesis Test for Comparing Algorithms
  • 5×2 Procedure With MLxtend
  • Comparing Classifier Algorithms
  • Hypothesis Test for Comparing Algorithms

    Model selection involves evaluating a suite of different machine learning algorithms or modeling pipelines and comparing them based on their performance.

    The model or modeling pipeline that achieves the best performance according to your performance metric is then selected as your final model that you can then use to start making predictions on new data.

    This applies to regression and classification predictive modeling tasks with classical machine learning algorithms and deep learning. It’s always the same process.

    The problem is, how do you know the difference between two models is real and not just a statistical fluke?

    This problem can be addressed using a statistical hypothesis test.

    One approach is to evaluate each model on the same k-fold cross-validation split of the data (e.g. using the same random number seed to split the data in each case) and calculate a score for each split. This would give a sample of 10 scores for 10-fold cross-validation. The scores can then be compared using a paired statistical hypothesis test because the same treatment (rows of data) was used for each algorithm to come up with each score. The Paired Student’s t-Test could be used.

    A problem with using the Paired Student’s t-Test, in this case, is that each evaluation of the model is not independent. This is because the same rows of data are used to train the data multiple times — actually, each time, except for the time a row of data is used in the hold-out test fold. This lack of independence in the evaluation means that the Paired Student’s t-Test is optimistically biased.

    This statistical test can be adjusted to take the lack of independence into account. Additionally, the number of folds and repeats of the procedure can be configured to achieve a good sampling of model performance that generalizes well to a wide range of problems and algorithms. Specifically two-fold cross-validation with five repeats, so-called 5×2-fold cross-validation.

    This approach was proposed by Thomas Dietterich in his 1998 paper titled “Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms.”

    For more on this topic, see the tutorial:

    Thankfully, we don’t need to implement this procedure ourselves.

    5×2 Procedure With MLxtend

    The MLxtend library by Sebastian Raschka provides an implementation via the paired_ttest_5x2cv() function.

    First, you must install the mlxtend library, for example:


    To use the evaluation, you must first load your dataset, then define the two models that you wish to compare.


    You can then call the paired_ttest_5x2cv() function and pass in your data and models and it will report the t-statistic value and the p-value as to whether the difference in the performance of the two algorithms is significant or not.


    The p-value must be interpreted using an alpha value, which is the significance level that you are willing to accept.

    If the p-value is less or equal to the chosen alpha, we reject the null hypothesis that the models have the same mean performance, which means the difference is probably real. If the p-value is greater than alpha, we fail to reject the null hypothesis that the models have the same mean performance and any observed difference in the mean accuracies is probability a statistical fluke.

    The smaller the alpha value, the better, and a common value is 5 percent (0.05).


    Now that we are familiar with the way to use a hypothesis test to compare algorithms, let’s look at some examples.

    Comparing Classifier Algorithms

    In this section, let’s compare the performance of two machine learning algorithms on a binary classification task, then check if the observed difference is statistically significant or not.

    First, we can use the make_classification() function to create a synthetic dataset with 1,000 samples and 20 input variables.

    The example below creates the dataset and summarizes its shape.


    Running the example creates the dataset and summarizes the number of rows and columns, confirming our expectations.

    We can use this data as the basis for comparing two algorithms.


    We will compare the performance of two linear algorithms on this dataset. Specifically, a logistic regression algorithm and a linear discriminant analysis (LDA) algorithm.

    The procedure I like is to use repeated stratified k-fold cross-validation with 10 folds and three repeats. We will use this procedure to evaluate each algorithm and return and report the mean classification accuracy.

    The complete example is listed below.


    Running the example first reports the mean classification accuracy for each algorithm.

    Your specific results may differ given the stochastic nature of the learning algorithms and evaluation procedure. Try running the example a few times.

    In this case, the results suggest that LDA has better performance if we just look at the mean scores: 89.2 percent for logistic regression and 89.3 percent for LDA.


    A box and whisker plot is also created summarizing the distribution of accuracy scores.

    This plot would support my decision in choosing LDA over LR.

    Box and Whisker Plot of Classification Accuracy Scores for Two Algorithms

    Box and Whisker Plot of Classification Accuracy Scores for Two Algorithms

    Now we can use a hypothesis test to see if the observed results are statistically significant.

    First, we will use the 5×2 procedure to evaluate the algorithms and calculate a p-value and test statistic value.


    We can then interpret the p-value using an alpha of 5 percent.


    Tying this together, the complete example is listed below.


    Running the example, we first evaluate the algorithms before, then report on the result of the statistical hypothesis test.

    Your specific results may differ given the stochastic nature of the learning algorithms and evaluation procedure. Try running the example a few times.

    In this case, we can see that the p-value is about 0.3, which is much larger than 0.05. This leads us to fail to reject the null hypothesis, suggesting that any observed difference between the algorithms is probably not real.

    We could just as easily choose logistic regression or LDA and both would perform about the same on average.

    This highlights that performing model selection based only on the mean performance may not be sufficient.


    Recall that we are reporting performance using a different procedure (3×10 CV) than the procedure used to estimate the performance in the statistical test (5×2 CV). Perhaps results would be different if we looked at scores using five repeats of two-fold cross-validation?

    The example below is updated to report classification accuracy for each algorithm using 5×2 CV.


    Running the example reports the mean accuracy for both algorithms and the results of the statistical test.

    Your specific results may differ given the stochastic nature of the learning algorithms and evaluation procedure. Try running the example a few times.

    In this case, we can see that the difference in the mean performance for the two algorithms is even larger, 89.4 percent vs. 89.0 percent in favor of logistic regression instead of LDA as we saw with 3×10 CV.


    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Tutorials
    Papers
    APIs

    Summary

    In this tutorial, you discovered how to use statistical hypothesis tests for comparing machine learning algorithms.

    Specifically, you learned:

    • Performing model selection based on the mean model performance can be misleading.
    • The five repeats of two-fold cross-validation with a modified Student’s t-Test is a good practice for comparing machine learning algorithms.
    • How to use the MLxtend machine learning to compare algorithms using a statistical hypothesis test.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Get a Handle on Statistics for Machine Learning!

    Statistical Methods for Machine Learning
    Develop a working understanding of statistics

    …by writing lines of code in python

    Discover how in my new Ebook:
    Statistical Methods for Machine Learning

    It provides self-study tutorials on topics like:
    Hypothesis Tests, Correlation, Nonparametric Stats, Resampling, and much more…

    Discover how to Transform Data into Knowledge

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    Auto-Sklearn-for-Automated-Machine-Learning-in-Python.jpg

    Auto-Sklearn for Automated Machine Learning in Python

    Automated Machine Learning (AutoML) refers to techniques for automatically discovering well-performing models for predictive modeling tasks with very little user involvement.

    Auto-Sklearn is an open-source library for performing AutoML in Python. It makes use of the popular Scikit-Learn machine learning library for data transforms and machine learning algorithms and uses a Bayesian Optimization search procedure to efficiently discover a top-performing model pipeline for a given dataset.

    In this tutorial, you will discover how to use Auto-Sklearn for AutoML with Scikit-Learn machine learning algorithms in Python.

    After completing this tutorial, you will know:

    • Auto-Sklearn is an open-source library for AutoML with scikit-learn data preparation and machine learning models.
    • How to use Auto-Sklearn to automatically discover top-performing models for classification tasks.
    • How to use Auto-Sklearn to automatically discover top-performing models for regression tasks.

    Let’s get started.

    Auto-Sklearn for Automated Machine Learning in Python

    Auto-Sklearn for Automated Machine Learning in Python
    Photo by Richard, some rights reserved.

    Tutorial Overview

    This tutorial is divided into four parts; they are:

  • AutoML With Auto-Sklearn
  • Install and Using Auto-Sklearn
  • Auto-Sklearn for Classification
  • Auto-Sklearn for Regression
  • AutoML With Auto-Sklearn

    Automated Machine Learning, or AutoML for short, is a process of discovering the best-performing pipeline of data transforms, model, and model configuration for a dataset.

    AutoML often involves the use of sophisticated optimization algorithms, such as Bayesian Optimization, to efficiently navigate the space of possible models and model configurations and quickly discover what works well for a given predictive modeling task. It allows non-expert machine learning practitioners to quickly and easily discover what works well or even best for a given dataset with very little technical background or direct input.

    Auto-Sklearn is an open-source Python library for AutoML using machine learning models from the scikit-learn machine learning library.

    It was developed by Matthias Feurer, et al. and described in their 2015 paper titled “Efficient and Robust Automated Machine Learning.”

    … we introduce a robust new AutoML system based on scikit-learn (using 15 classifiers, 14 feature preprocessing methods, and 4 data preprocessing methods, giving rise to a structured hypothesis space with 110 hyperparameters).

    — Efficient and Robust Automated Machine Learning, 2015.

    The benefit of Auto-Sklearn is that, in addition to discovering the data preparation and model that performs for a dataset, it also is able to learn from models that performed well on similar datasets and is able to automatically create an ensemble of top-performing models discovered as part of the optimization process.

    This system, which we dub AUTO-SKLEARN, improves on existing AutoML methods by automatically taking into account past performance on similar datasets, and by constructing ensembles from the models evaluated during the optimization.

    — Efficient and Robust Automated Machine Learning, 2015.

    The authors provide a useful depiction of their system in the paper, provided below.

    Overview of the Auto-Sklearn System

    Overview of the Auto-Sklearn System.
    Taken from: Efficient and Robust Automated Machine Learning, 2015.

    Install and Using Auto-Sklearn

    The first step is to install the Auto-Sklearn library, which can be achieved using pip, as follows:


    Once installed, we can import the library and print the version number to confirm it was installed successfully:


    Running the example prints the version number.

    Your version number should be the same or higher.


    Using Auto-Sklearn is straightforward.

    Depending on whether your prediction task is classification or regression, you create and configure an instance of the AutoSklearnClassifier or AutoSklearnRegressor class, fit it on your dataset, and that’s it. The resulting model can then be used to make predictions directly or saved to file (using pickle) for later use.


    There are a ton of configuration options provided as arguments to the AutoSklearn class.

    By default, the search will use a train-test split of your dataset during the search, and this default is recommended both for speed and simplicity.

    Importantly, you should set the “n_jobs” argument to the number of cores in your system, e.g. 8 if you have 8 cores.

    The optimization process will run for as long as you allow, measure in minutes. By default, it will run for one hour.

    I recommend setting the “time_left_for_this_task” argument for the number of seconds you want the process to run. E.g. less than 5-10 minutes is probably plenty for many small predictive modeling tasks (sub 1,000 rows).

    We will use 5 minutes (300 seconds) for the examples in this tutorial. We will also limit the time allocated to each model evaluation to 30 seconds via the “per_run_time_limit” argument. For example:


    You can limit the algorithms considered in the search, as well as the data transforms.

    By default, the search will create an ensemble of top-performing models discovered as part of the search. Sometimes, this can lead to overfitting and can be disabled by setting the “ensemble_size” argument to 1 and “initial_configurations_via_metalearning” to 0.


    At the end of a run, the list of models can be accessed, as well as other details.

    Perhaps the most useful feature is the sprint_statistics() function that summarizes the search and the performance of the final model.


    Now that we are familiar with the Auto-Sklearn library, let’s look at some worked examples.

    Auto-Sklearn for Classification

    In this section, we will use Auto-Sklearn to discover a model for the sonar dataset.

    The sonar dataset is a standard machine learning dataset comprised of 208 rows of data with 60 numerical input variables and a target variable with two class values, e.g. binary classification.

    Using a test harness of repeated stratified 10-fold cross-validation with three repeats, a naive model can achieve an accuracy of about 53 percent. A top-performing model can achieve accuracy on this same test harness of about 88 percent. This provides the bounds of expected performance on this dataset.

    The dataset involves predicting whether sonar returns indicate a rock or simulated mine.

    No need to download the dataset; we will download it automatically as part of our worked examples.

    The example below downloads the dataset and summarizes its shape.


    Running the example downloads the dataset and splits it into input and output elements. As expected, we can see that there are 208 rows of data with 60 input variables.


    We will use Auto-Sklearn to find a good model for the sonar dataset.

    First, we will split the dataset into train and test sets and allow the process to find a good model on the training set, then later evaluate the performance of what was found on the holdout test set.


    The AutoSklearnClassifier is configured to run for 5 minutes with 8 cores and limit each model evaluation to 30 seconds.


    The search is then performed on the training dataset.


    Afterward, a summary of the search and best-performing model is reported.


    Finally, we evaluate the performance of the model that was prepared on the holdout test dataset.


    Tying this together, the complete example is listed below.


    Running the example will take about five minutes, given the hard limit we imposed on the run.

    At the end of the run, a summary is printed showing that 1,054 models were evaluated and the estimated performance of the final model was 91 percent.

    Your specific results may vary given the stochastic nature of the optimization algorithm.


    We then evaluate the model on the holdout dataset and see that classification accuracy of 81.2 percent was achieved, which is reasonably skillful.


    Auto-Sklearn for Regression

    In this section, we will use Auto-Sklearn to discover a model for the auto insurance dataset.

    The auto insurance dataset is a standard machine learning dataset comprised of 63 rows of data with one numerical input variable and a numerical target variable.

    Using a test harness of repeated stratified 10-fold cross-validation with three repeats, a naive model can achieve a mean absolute error (MAE) of about 66. A top-performing model can achieve a MAE on this same test harness of about 28. This provides the bounds of expected performance on this dataset.

    The dataset involves predicting the total amount in claims (thousands of Swedish Kronor) given the number of claims for different geographical regions.

    No need to download the dataset; we will download it automatically as part of our worked examples.

    The example below downloads the dataset and summarizes its shape.


    Running the example downloads the dataset and splits it into input and output elements. As expected, we can see that there are 63 rows of data with one input variable.


    We will use Auto-Sklearn to find a good model for the auto insurance dataset.

    We can use the same process as was used in the previous section, although we will use the AutoSklearnRegressor class instead of the AutoSklearnClassifier.


    By default, the regressor will optimize the R^2 metric.

    In this case, we are interested in the mean absolute error, or MAE, which we can specify via the “metric” argument when calling the fit() function.


    The complete example is listed below.


    Running the example will take about five minutes, given the hard limit we imposed on the run.

    You might see some warning messages during the run and you can safely ignore them, such as:


    At the end of the run, a summary is printed showing that 1,759 models were evaluated and the estimated performance of the final model was a MAE of 29.


    We then evaluate the model on the holdout dataset and see that a MAE of 26 was achieved, which is a great result.


    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Summary

    In this tutorial, you discovered how to use Auto-Sklearn for AutoML with Scikit-Learn machine learning algorithms in Python.

    Specifically, you learned:

    • Auto-Sklearn is an open-source library for AutoML with scikit-learn data preparation and machine learning models.
    • How to use Auto-Sklearn to automatically discover top-performing models for classification tasks.
    • How to use Auto-Sklearn to automatically discover top-performing models for regression tasks.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Discover Fast Machine Learning in Python!

    Master Machine Learning With Python
    Develop Your Own Models in Minutes

    …with just a few lines of scikit-learn code

    Learn how in my new Ebook:
    Machine Learning Mastery With Python

    Covers self-study tutorials and end-to-end projects like:
    Loading data, visualization, modeling, tuning, and much more…

    Finally Bring Machine Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    Scikit-Optimize-for-Hyperparameter-Tuning-in-Machine-Learning.jpg

    Scikit-Optimize for Hyperparameter Tuning in Machine Learning

    Hyperparameter optimization refers to performing a search in order to discover the set of specific model configuration arguments that result in the best performance of the model on a specific dataset.

    There are many ways to perform hyperparameter optimization, although modern methods, such as Bayesian Optimization, are fast and effective. The Scikit-Optimize library is an open-source Python library that provides an implementation of Bayesian Optimization that can be used to tune the hyperparameters of machine learning models from the scikit-Learn Python library.

    You can easily use the Scikit-Optimize library to tune the models on your next machine learning project.

    In this tutorial, you will discover how to use the Scikit-Optimize library to use Bayesian Optimization for hyperparameter tuning.

    After completing this tutorial, you will know:

    • Scikit-Optimize provides a general toolkit for Bayesian Optimization that can be used for hyperparameter tuning.
    • How to manually use the Scikit-Optimize library to tune the hyperparameters of a machine learning model.
    • How to use the built-in BayesSearchCV class to perform model hyperparameter tuning.

    Let’s get started.

    Scikit-Optimize for Hyperparameter Tuning in Machine Learning

    Scikit-Optimize for Hyperparameter Tuning in Machine Learning
    Photo by Dan Nevill, some rights reserved.

    Tutorial Overview

    This tutorial is divided into four parts; they are:

  • Scikit-Optimize
  • Machine Learning Dataset and Model
  • Manually Tune Algorithm Hyperparameters
  • Automatically Tune Algorithm Hyperparameters
  • Scikit-Optimize

    Scikit-Optimize, or skopt for short, is an open-source Python library for performing optimization tasks.

    It offers efficient optimization algorithms, such as Bayesian Optimization, and can be used to find the minimum or maximum of arbitrary cost functions.

    Bayesian Optimization provides a principled technique based on Bayes Theorem to direct a search of a global optimization problem that is efficient and effective. It works by building a probabilistic model of the objective function, called the surrogate function, that is then searched efficiently with an acquisition function before candidate samples are chosen for evaluation on the real objective function.

    For more on the topic of Bayesian Optimization, see the tutorial:

    Importantly, the library provides support for tuning the hyperparameters of machine learning algorithms offered by the scikit-learn library, so-called hyperparameter optimization. As such, it offers an efficient alternative to less efficient hyperparameter optimization procedures such as grid search and random search.

    The scikit-optimize library can be installed using pip, as follows:


    Once installed, we can import the library and print the version number to confirm the library was installed successfully and can be accessed.

    The complete example is listed below.


    Running the example reports the currently installed version number of scikit-optimize.

    Your version number should be the same or higher.


    For more installation instructions, see the documentation:

    Now that we are familiar with what Scikit-Optimize is and how to install it, let’s explore how we can use it to tune the hyperparameters of a machine learning model.

    Machine Learning Dataset and Model

    First, let’s select a standard dataset and a model to address it.

    We will use the ionosphere machine learning dataset. This is a standard machine learning dataset comprising 351 rows of data with three numerical input variables and a target variable with two class values, e.g. binary classification.

    Using a test harness of repeated stratified 10-fold cross-validation with three repeats, a naive model can achieve an accuracy of about 64 percent. A top performing model can achieve accuracy on this same test harness of about 94 percent. This provides the bounds of expected performance on this dataset.

    The dataset involves predicting whether measurements of the ionosphere indicate a specific structure or not.

    You can learn more about the dataset here:

    No need to download the dataset; we will download it automatically as part of our worked examples.

    The example below downloads the dataset and summarizes its shape.


    Running the example downloads the dataset and splits it into input and output elements. As expected, we can see that there are 351 rows of data with 34 input variables.


    We can evaluate a support vector machine (SVM) model on this dataset using repeated stratified cross-validation.

    We can report the mean model performance on the dataset averaged over all folds and repeats, which will provide a reference for model hyperparameter tuning performed in later sections.

    The complete example is listed below.


    Running the example first loads and prepares the dataset, then evaluates the SVM model on the dataset.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    In this case, we can see that the SVM with default hyperparameters achieved a mean classification accuracy of about 83.7 percent, which is skillful and close to the top performance on the problem of 94 percent.


    Next, let’s see if we can improve performance by tuning the model hyperparameters using the scikit-optimize library.

    Manually Tune Algorithm Hyperparameters

    The Scikit-Optimize library can be used to tune the hyperparameters of a machine learning model.

    We can achieve this manually by using the Bayesian Optimization capabilities of the library.

    This requires that we first define a search space. In this case, this will be the hyperparameters of the model that we wish to tune, and the scope or range of each hyperparameter.

    We will tune the following hyperparameters of the SVM model:

    • C, the regularization parameter.
    • kernel, the type of kernel used in the model.
    • degree, used for the polynomial kernel.
    • gamma, used in most other kernels.

    For the numeric hyperparameters C and gamma, we will define a log scale to search between a small value of 1e-6 and 100. Degree is an integer and we will search values between 1 and 5. Finally, the kernel is a categorical variable with specific named values.

    We can define the search space for these four hyperparameters, a list of data types from the skopt library, as follows:


    Note the data type, the range, and the name of the hyperparameter specified for each.

    We can then define a function that will be called by the search procedure. This is a function expected by the optimization procedure later and takes a model and set of specific hyperparameters for the model, evaluates it, and returns a score for the set of hyperparameters.

    In our case, we want to evaluate the model using repeated stratified 10-fold cross-validation on our ionosphere dataset. We want to maximize classification accuracy, e.g. find the set of model hyperparameters that give the best accuracy. By default, the process minimizes the score returned from this function, therefore, we will return one minus the accuracy, e.g. perfect skill will be (1 – accuracy) or 0.0, and the worst skill will be 1.0.

    The evaluate_model() function below implements this and takes a specific set of hyperparameters.


    Next, we can execute the search by calling the gp_minimize() function and passing the name of the function to call to evaluate each model and the search space to optimize.


    The procedure will run until it converges and returns a result.

    The result object contains lots of details, but importantly, we can access the score of the best performing configuration and the hyperparameters used by the best forming model.


    Tying this together, the complete example of manually tuning the hyperparameters of an SVM on the ionosphere dataset is listed below.


    Running the example may take a few moments, depending on the speed of your machine.

    You may see some warning messages that you can safely ignore, such as:


    At the end of the run, the best-performing configuration is reported.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    In this case, we can see that configuration, reported in order of the search space list, was a modest C value, a RBF kernel, a degree of 2 (ignored by the RBF kernel), and a modest gamma value.

    Importantly, we can see that the skill of this model was approximately 94.7 percent, which is a top-performing model


    This is not the only way to use the Scikit-Optimize library for hyperparameter tuning. In the next section, we can see a more automated approach.

    Automatically Tune Algorithm Hyperparameters

    The Scikit-Learn machine learning library provides tools for tuning model hyperparameters.

    Specifically, it provides the GridSearchCV and RandomizedSearchCV classes that take a model, a search space, and a cross-validation configuration.

    The benefit of these classes is that the search procedure is performed automatically, requiring minimal configuration.

    Similarly, the Scikit-Optimize library provides a similar interface for performing a Bayesian Optimization of model hyperparameters via the BayesSearchCV class.

    This class can be used in the same way as the Scikit-Learn equivalents.

    First, the search space must be defined as a dictionary with hyperparameter names used as the key and the scope of the variable as the value.


    We can then define the BayesSearchCV configuration taking the model we wish to evaluate, the hyperparameter search space, and the cross-validation configuration.


    We can then execute the search and report the best result and configuration at the end.


    Tying this together, the complete example of automatically tuning SVM hyperparameters using the BayesSearchCV class on the ionosphere dataset is listed below.


    Running the example may take a few moments, depending on the speed of your machine.

    You may see some warning messages that you can safely ignore, such as:


    At the end of the run, the best-performing configuration is reported.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    In this case, we can see that the model performed above top-performing models achieving a mean classification accuracy of about 95.2 percent.

    The search discovered a large C value, an RBF kernel, and a small gamma value.


    This provides a template that you can use to tune the hyperparameters on your machine learning project.

    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Related Tutorials
    APIs

    Summary

    In this tutorial, you discovered how to use the Scikit-Optimize library to use Bayesian Optimization for hyperparameter tuning.

    Specifically, you learned:

    • Scikit-Optimize provides a general toolkit for Bayesian Optimization that can be used for hyperparameter tuning.
    • How to manually use the Scikit-Optimize library to tune the hyperparameters of a machine learning model.
    • How to use the built-in BayesSearchCV class to perform model hyperparameter tuning.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Discover Fast Machine Learning in Python!

    Master Machine Learning With Python
    Develop Your Own Models in Minutes

    …with just a few lines of scikit-learn code

    Learn how in my new Ebook:
    Machine Learning Mastery With Python

    Covers self-study tutorials and end-to-end projects like:
    Loading data, visualization, modeling, tuning, and much more…

    Finally Bring Machine Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    1598716808_524_Plot-a-Decision-Surface-for-Machine-Learning-Algorithms-in-Python.png

    Plot a Decision Surface for Machine Learning Algorithms in Python

    Last Updated on August 26, 2020

    Classification algorithms learn how to assign class labels to examples, although their decisions can appear opaque.

    A popular diagnostic for understanding the decisions made by a classification algorithm is the decision surface. This is a plot that shows how a fit machine learning algorithm predicts a coarse grid across the input feature space.

    A decision surface plot is a powerful tool for understanding how a given model “sees” the prediction task and how it has decided to divide the input feature space by class label.

    In this tutorial, you will discover how to plot a decision surface for a classification machine learning algorithm.

    After completing this tutorial, you will know:

    • Decision surface is a diagnostic tool for understanding how a classification algorithm divides up the feature space.
    • How to plot a decision surface for using crisp class labels for a machine learning algorithm.
    • How to plot and interpret a decision surface using predicted probabilities.

    Kick-start your project with my new book Machine Learning Mastery With Python, including step-by-step tutorials and the Python source code files for all examples.

    Let’s get started.

    Plot a Decision Surface for Machine Learning Algorithms in Python

    Plot a Decision Surface for Machine Learning Algorithms in Python
    Photo by Tony Webster, some rights reserved.

    Tutorial Overview

    This tutorial is divided into three parts; they are:

  • Decision Surface
  • Dataset and Model
  • Plot a Decision Surface
  • Decision Surface

    Classification machine learning algorithms learn to assign labels to input examples.

    Consider numeric input features for the classification task defining a continuous input feature space.

    We can think of each input feature defining an axis or dimension on a feature space. Two input features would define a feature space that is a plane, with dots representing input coordinates in the input space. If there were three input variables, the feature space would be a three-dimensional volume.

    Each point in the space can be assigned a class label. In terms of a two-dimensional feature space, we can think of each point on the planing having a different color, according to their assigned class.

    The goal of a classification algorithm is to learn how to divide up the feature space such that labels are assigned correctly to points in the feature space, or at least, as correctly as is possible.

    This is a useful geometric understanding of classification predictive modeling. We can take it one step further.

    Once a classification machine learning algorithm divides a feature space, we can then classify each point in the feature space, on some arbitrary grid, to get an idea of how exactly the algorithm chose to divide up the feature space.

    This is called a decision surface or decision boundary, and it provides a diagnostic tool for understanding a model on a classification predictive modeling task.

    Although the notion of a “surface” suggests a two-dimensional feature space, the method can be used with feature spaces with more than two dimensions, where a surface is created for each pair of input features.

    Now that we are familiar with what a decision surface is, next, let’s define a dataset and model for which we later explore the decision surface.

    Dataset and Model

    In this section, we will define a classification task and predictive model to learn the task.

    Synthetic Classification Dataset

    We can use the make_blobs() scikit-learn function to define a classification task with a two-dimensional class numerical feature space and each point assigned one of two class labels, e.g. a binary classification task.


    Once defined, we can then create a scatter plot of the feature space with the first feature defining the x-axis, the second feature defining the y axis, and each sample represented as a point in the feature space.

    We can then color points in the scatter plot according to their class label as either 0 or 1.


    Tying this together, the complete example of defining and plotting a synthetic classification dataset is listed below.


    Running the example creates the dataset, then plots the dataset as a scatter plot with points colored by class label.

    We can see a clear separation between examples from the two classes and we can imagine how a machine learning model might draw a line to separate the two classes, e.g. perhaps a diagonal line right through the middle of the two groups.

    Scatter Plot of Binary Classification Dataset With 2D Feature Space

    Scatter Plot of Binary Classification Dataset With 2D Feature Space

    Fit Classification Predictive Model

    We can now fit a model on our dataset.

    In this case, we will fit a logistic regression algorithm because we can predict both crisp class labels and probabilities, both of which we can use in our decision surface.

    We can define the model, then fit it on the training dataset.


    Once defined, we can use the model to make a prediction for the training dataset to get an idea of how well it learned to divide the feature space of the training dataset and assign labels.


    The predictions can be evaluated using classification accuracy.


    Tying this together, the complete example of fitting and evaluating a model on the synthetic binary classification dataset is listed below.


    Running the example fits the model and makes a prediction for each example.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    In this case, we can see that the model achieved a performance of about 97.2 percent.


    Now that we have a dataset and model, let’s explore how we can develop a decision surface.

    Plot a Decision Surface

    We can create a decision surface by fitting a model on the training dataset, then using the model to make predictions for a grid of values across the input domain.

    Once we have the grid of predictions, we can plot the values and their class label.

    A scatter plot could be used if a fine enough grid was taken. A better approach is to use a contour plot that can interpolate the colors between the points.

    The contourf() Matplotlib function can be used.

    This requires a few steps.

    First, we need to define a grid of points across the feature space.

    To do this, we can find the minimum and maximum values for each feature and expand the grid one step beyond that to ensure the whole feature space is covered.


    We can then create a uniform sample across each dimension using the arange() function at a chosen resolution. We will use a resolution of 0.1 in this case.


    Now we need to turn this into a grid.

    We can use the meshgrid() NumPy function to create a grid from these two vectors.

    If the first feature x1 is our x-axis of the feature space, then we need one row of x1 values of the grid for each point on the y-axis.

    Similarly, if we take x2 as our y-axis of the feature space, then we need one column of x2 values of the grid for each point on the x-axis.

    The meshgrid() function will do this for us, duplicating the rows and columns for us as needed. It returns two grids for the two input vectors. The first grid of x-values and the second of y-values, organized in an appropriately sized grid of rows and columns across the feature space.


    We then need to flatten out the grid to create samples that we can feed into the model and make a prediction.

    To do this, first, we flatten each grid into a vector.


    Then we stack the vectors side by side as columns in an input dataset, e.g. like our original training dataset, but at a much higher resolution.


    We can then feed this into our model and get a prediction for each point in the grid.


    So far, so good.

    We have a grid of values across the feature space and the class labels as predicted by our model.

    Next, we need to plot the grid of values as a contour plot.

    The contourf() function takes separate grids for each axis, just like what was returned from our prior call to meshgrid(). Great!

    So we can use xx and yy that we prepared earlier and simply reshape the predictions (yhat) from the model to have the same shape.


    We then plot the decision surface with a two-color colormap.


    We can then plot the actual points of the dataset over the top to see how well they were separated by the logistic regression decision surface.

    The complete example of plotting a decision surface for a logistic regression model on our synthetic binary classification dataset is listed below.


    Running the example fits the model and uses it to predict outcomes for the grid of values across the feature space and plots the result as a contour plot.

    We can see, as we might have suspected, logistic regression divides the feature space using a straight line. It is a linear model, after all; this is all it can do.

    Creating a decision surface is almost like magic. It gives immediate and meaningful insight into how the model has learned the task.

    Try it with different algorithms, like an SVM or decision tree.
    Post your resulting maps as links in the comments below!

    Decision Surface for Logistic Regression on a Binary Classification Task

    Decision Surface for Logistic Regression on a Binary Classification Task

    We can add more depth to the decision surface by using the model to predict probabilities instead of class labels.


    When plotted, we can see how confident or likely it is that each point in the feature space belongs to each of the class labels, as seen by the model.

    We can use a different color map that has gradations, and show a legend so we can interpret the colors.


    The complete example of creating a decision surface using probabilities is listed below.


    Running the example predicts the probability of class membership for each point on the grid across the feature space and plots the result.

    Here, we can see that the model is unsure (lighter colors) around the middle of the domain, given the sampling noise in that area of the feature space. We can also see that the model is very confident (full colors) in the bottom-left and top-right halves of the domain.

    Together, the crisp class and probability decision surfaces are powerful diagnostic tools for understanding your model and how it divides the feature space for your predictive modeling task.

    Probability Decision Surface for Logistic Regression on a Binary Classification Task

    Probability Decision Surface for Logistic Regression on a Binary Classification Task

    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Summary

    In this tutorial, you discovered how to plot a decision surface for a classification machine learning algorithm.

    Specifically, you learned:

    • Decision surface is a diagnostic tool for understanding how a classification algorithm divides up the feature space.
    • How to plot a decision surface for using crisp class labels for a machine learning algorithm.
    • How to plot and interpret a decision surface using predicted probabilities.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Discover Fast Machine Learning in Python!

    Master Machine Learning With Python
    Develop Your Own Models in Minutes

    …with just a few lines of scikit-learn code

    Learn how in my new Ebook:
    Machine Learning Mastery With Python

    Covers self-study tutorials and end-to-end projects like:
    Loading data, visualization, modeling, tuning, and much more…

    Finally Bring Machine Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    1598763608_908_How-to-use-Seaborn-Data-Visualization-for-Machine-Learning.png

    How to use Seaborn Data Visualization for Machine Learning

    Last Updated on August 19, 2020

    Data visualization provides insight into the distribution and relationships between variables in a dataset.

    This insight can be helpful in selecting data preparation techniques to apply prior to modeling and the types of algorithms that may be most suited to the data.

    Seaborn is a data visualization library for Python that runs on top of the popular Matplotlib data visualization library, although it provides a simple interface and aesthetically better-looking plots.

    In this tutorial, you will discover a gentle introduction to Seaborn data visualization for machine learning.

    After completing this tutorial, you will know:

    • How to summarize the distribution of variables using bar charts, histograms, and box and whisker plots.
    • How to summarize relationships using line plots and scatter plots.
    • How to compare the distribution and relationships of variables for different class values on the same plot.

    Kick-start your project with my new book Machine Learning Mastery With Python, including step-by-step tutorials and the Python source code files for all examples.

    Let’s get started.

    How to use Seaborn Data Visualization for Machine Learning

    How to use Seaborn Data Visualization for Machine Learning
    Photo by Martin Pettitt, some rights reserved.

    Tutorial Overview

    This tutorial is divided into six parts; they are:

    • Seaborn Data Visualization Library
    • Line Plots
    • Bar Chart Plots
    • Histogram Plots
    • Box and Whisker Plots
    • Scatter Plots

    Seaborn Data Visualization Library

    The primary plotting library for Python is called Matplotlib.

    Seaborn is a plotting library that offers a simpler interface, sensible defaults for plots needed for machine learning, and most importantly, the plots are aesthetically better looking than those in Matplotlib.

    Seaborn requires that Matplotlib is installed first.

    You can install Matplotlib directly using pip, as follows:


    Once installed, you can confirm that the library can be loaded and used by printing the version number, as follows:


    Running the example prints the current version of the Matplotlib library.


    Next, the Seaborn library can be installed, also using pip:


    Once installed, we can also confirm the library can be loaded and used by printing the version number, as follows:


    Running the example prints the current version of the Seaborn library.


    To create Seaborn plots, you must import the Seaborn library and call functions to create the plots.

    Importantly, Seaborn plotting functions expect data to be provided as Pandas DataFrames. This means that if you are loading your data from CSV files, you must use Pandas functions like read_csv() to load your data as a DataFrame. When plotting, columns can then be specified via the DataFrame name or column index.

    To show the plot, you can call the show() function on Matplotlib library.


    Alternatively, the plots can be saved to file, such as a PNG formatted image file. The savefig() Matplotlib function can be used to save images.


    Now that we have Seaborn installed, let’s look at some common plots we may need when working with machine learning data.

    Line Plots

    A line plot is generally used to present observations collected at regular intervals.

    The x-axis represents the regular interval, such as time. The y-axis shows the observations, ordered by the x-axis and connected by a line.

    A line plot can be created in Seaborn by calling the lineplot() function and passing the x-axis data for the regular interval, and y-axis for the observations.

    We can demonstrate a line plot using a time series dataset of monthly car sales.

    The dataset has two columns: “Month” and “Sales.” Month will be used as the x-axis and Sales will be plotted on the y-axis.


    Tying this together, the complete example is listed below.


    Running the example first loads the time series dataset and creates a line plot of the data, clearly showing a trend and seasonality in the sales data.

    Line Plot of a Time Series Dataset

    Line Plot of a Time Series Dataset

    For more great examples of line plots with Seaborn, see: Visualizing statistical relationships.

    Bar Chart Plots

    A bar chart is generally used to present relative quantities for multiple categories.

    The x-axis represents the categories that are spaced evenly. The y-axis represents the quantity for each category and is drawn as a bar from the baseline to the appropriate level on the y-axis.

    A bar chart can be created in Seaborn by calling the countplot() function and passing the data.

    We will demonstrate a bar chart with a variable from the breast cancer classification dataset that is comprised of categorical input variables.

    We will just plot one variable, in this case, the first variable which is the age bracket.


    Tying this together, the complete example is listed below.


    Running the example first loads the breast cancer dataset and creates a bar chart plot of the data, showing each age group and the number of individuals (samples) that fall within reach group.

    Bar Chart Plot of Age Range Categorical Variable

    Bar Chart Plot of Age Range Categorical Variable

    We might also want to plot the counts for each category for a variable, such as the first variable, against the class label.

    This can be achieved using the countplot() function and specifying the class variable (column index 9) via the “hue” argument, as follows:


    Tying this together, the complete example is listed below.


    Running the example first loads the breast cancer dataset and creates a bar chart plot of the data, showing each age group and the number of individuals (samples) that fall within each group separated by the two class labels for the dataset.

    Bar Chart Plot of Age Range Categorical Variable by Class Label

    Bar Chart Plot of Age Range Categorical Variable by Class Label

    For more great examples of bar chart plots with Seaborn, see: Plotting with categorical data.

    Histogram Plots

    A histogram plot is generally used to summarize the distribution of a numerical data sample.

    The x-axis represents discrete bins or intervals for the observations. For example, observations with values between 1 and 10 may be split into five bins, the values [1,2] would be allocated to the first bin, [3,4] would be allocated to the second bin, and so on.

    The y-axis represents the frequency or count of the number of observations in the dataset that belong to each bin.

    Essentially, a data sample is transformed into a bar chart where each category on the x-axis represents an interval of observation values.

    A histogram can be created in Seaborn by calling the distplot() function and passing the variable.

    We will demonstrate a boxplot with a numerical variable from the diabetes classification dataset. We will just plot one variable, in this case, the first variable, which is the number of times that a patient was pregnant.


    Tying this together, the complete example is listed below.


    Running the example first loads the diabetes dataset and creates a histogram plot of the variable, showing the distribution of the values with a hard cut-off at zero.

    The plot shows both the histogram (counts of bins) as well as a smooth estimate of the probability density function.

    Histogram Plot of Number of Times Pregnant Numerical Variable

    Histogram Plot of Number of Times Pregnant Numerical Variable

    For more great examples of histogram plots with Seaborn, see: Visualizing the distribution of a dataset.

    Box and Whisker Plots

    A box and whisker plot, or boxplot for short, is generally used to summarize the distribution of a data sample.

    The x-axis is used to represent the data sample, where multiple boxplots can be drawn side by side on the x-axis if desired.

    The y-axis represents the observation values. A box is drawn to summarize the middle 50 percent of the dataset starting at the observation at the 25th percentile and ending at the 75th percentile. This is called the interquartile range, or IQR. The median, or 50th percentile, is drawn with a line.

    Lines called whiskers are drawn extending from both ends of the box, calculated as (1.5 * IQR) to demonstrate the expected range of sensible values in the distribution. Observations outside the whiskers might be outliers and are drawn with small circles.

    A boxplot can be created in Seaborn by calling the boxplot() function and passing the data.

    We will demonstrate a boxplot with a numerical variable from the diabetes classification dataset. We will just plot one variable, in this case, the first variable, which is the number of times that a patient was pregnant.


    Tying this together, the complete example is listed below.


    Running the example first loads the diabetes dataset and creates a boxplot plot of the first input variable, showing the distribution of the number of times patients were pregnant.

    We can see the median just above 2.5 times, some outliers up around 15 times (wow!).

    Box and Whisker Plot of Number of Times Pregnant Numerical Variable

    Box and Whisker Plot of Number of Times Pregnant Numerical Variable

    We might also want to plot the distribution of the numerical variable for each value of a categorical variable, such as the first variable, against the class label.

    This can be achieved by calling the boxplot() function and passing the class variable as the x-axis and the numerical variable as the y-axis.


    Tying this together, the complete example is listed below.


    Running the example first loads the diabetes dataset and creates a boxplot of the data, showing the distribution of the number of times pregnant as a numerical variable for the two-class labels.

    Box and Whisker Plot of Number of Times Pregnant Numerical Variable by Class Label

    Box and Whisker Plot of Number of Times Pregnant Numerical Variable by Class Label

    Scatter Plots

    A scatter plot, or scatterplot, is generally used to summarize the relationship between two paired data samples.

    Paired data samples mean that two measures were recorded for a given observation, such as the weight and height of a person.

    The x-axis represents observation values for the first sample, and the y-axis represents the observation values for the second sample. Each point on the plot represents a single observation.

    A scatterplot can be created in Seaborn by calling the scatterplot() function and passing the two numerical variables.

    We will demonstrate a scatterplot with two numerical variables from the diabetes classification dataset. We will plot the first versus the second variable, in this case, the first variable, which is the number of times that a patient was pregnant, and the second is the plasma glucose concentration after a two hour oral glucose tolerance test (more details of the variables here).


    Tying this together, the complete example is listed below.


    Running the example first loads the diabetes dataset and creates a scatter plot of the first two input variables.

    We can see a somewhat uniform relationship between the two variables.

    Scatter Plot of Number of Times Pregnant vs. Plasma Glucose Numerical Variables

    Scatter Plot of Number of Times Pregnant vs. Plasma Glucose Numerical Variables

    We might also want to plot the relationship for the pair of numerical variables against the class label.

    This can be achieved using the scatterplot() function and specifying the class variable (column index 8) via the “hue” argument, as follows:


    Tying this together, the complete example is listed below.


    Running the example first loads the diabetes dataset and creates a scatter plot of the first two variables vs. class label.

    Scatter Plot of Number of Times Pregnant vs. Plasma Glucose Numerical Variables by Class Label

    Scatter Plot of Number of Times Pregnant vs. Plasma Glucose Numerical Variables by Class Label

    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Tutorials
    APIs

    Summary

    In this tutorial, you discovered a gentle introduction to Seaborn data visualization for machine learning.

    Specifically, you learned:

    • How to summarize the distribution of variables using bar charts, histograms, and box and whisker plots.
    • How to summarize relationships using line plots and scatter plots.
    • How to compare the distribution and relationships of variables for different class values on the same plot.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Discover Fast Machine Learning in Python!

    Master Machine Learning With Python
    Develop Your Own Models in Minutes

    …with just a few lines of scikit-learn code

    Learn how in my new Ebook:
    Machine Learning Mastery With Python

    Covers self-study tutorials and end-to-end projects like:
    Loading data, visualization, modeling, tuning, and much more…

    Finally Bring Machine Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    Deep-Learning-Models-for-Multi-Output-Regression.jpg

    Deep Learning Models for Multi-Output Regression

    Last Updated on August 28, 2020

    Multi-output regression involves predicting two or more numerical variables.

    Unlike normal regression where a single value is predicted for each sample, multi-output regression requires specialized machine learning algorithms that support outputting multiple variables for each prediction.

    Deep learning neural networks are an example of an algorithm that natively supports multi-output regression problems. Neural network models for multi-output regression tasks can be easily defined and evaluated using the Keras deep learning library.

    In this tutorial, you will discover how to develop deep learning models for multi-output regression.

    After completing this tutorial, you will know:

    • Multi-output regression is a predictive modeling task that involves two or more numerical output variables.
    • Neural network models can be configured for multi-output regression tasks.
    • How to evaluate a neural network for multi-output regression and make a prediction for new data.

    Let’s get started.

    Deep Learning Models for Multi-Output Regression

    Deep Learning Models for Multi-Output Regression
    Photo by Christian Collins, some rights reserved.

    Tutorial Overview

    This tutorial is divided into three parts; they are:

  • Multi-Output Regression
  • Neural Networks for Multi-Outputs
  • Neural Network for Multi-Output Regression
  • Multi-Output Regression

    Regression is a predictive modeling task that involves predicting a numerical output given some input.

    It is different from classification tasks that involve predicting a class label.

    Typically, a regression task involves predicting a single numeric value. Although, some tasks require predicting more than one numeric value. These tasks are referred to as multiple-output regression, or multi-output regression for short.

    In multi-output regression, two or more outputs are required for each input sample, and the outputs are required simultaneously. The assumption is that the outputs are a function of the inputs.

    We can create a synthetic multi-output regression dataset using the make_regression() function in the scikit-learn library.

    Our dataset will have 1,000 samples with 10 input features, five of which will be relevant to the output and five of which will be redundant. The dataset will have three numeric outputs for each sample.

    The complete example of creating and summarizing the synthetic multi-output regression dataset is listed below.


    Running the example creates the dataset and summarizes the shape of the input and output elements.

    We can see that, as expected, there are 1,000 samples, each with 10 input features and three output features.


    Next, let’s look at how we can develop neural network models for multiple-output regression tasks.

    Neural Networks for Multi-Outputs

    Many machine learning algorithms support multi-output regression natively.

    Popular examples are decision trees and ensembles of decision trees. A limitation of decision trees for multi-output regression is that the relationships between inputs and outputs can be blocky or highly structured based on the training data.

    Neural network models also support multi-output regression and have the benefit of learning a continuous function that can model a more graceful relationship between changes in input and output.

    Multi-output regression can be supported directly by neural networks simply by specifying the number of target variables there are in the problem as the number of nodes in the output layer. For example, a task that has three output variables will require a neural network output layer with three nodes in the output layer, each with the linear (default) activation function.

    We can demonstrate this using the Keras deep learning library.

    We will define a multilayer perceptron (MLP) model for the multi-output regression task defined in the previous section.

    Each sample has 10 inputs and three outputs, therefore, the network requires an input layer that expects 10 inputs specified via the “input_dim” argument in the first hidden layer and three nodes in the output layer.

    We will use the popular ReLU activation function in the hidden layer. The hidden layer has 20 nodes, which were chosen after some trial and error. We will fit the model using mean absolute error (MAE) loss and the Adam version of stochastic gradient descent.

    The definition of the network for the multi-output regression task is listed below.


    You may want to adapt this model for your own multi-output regression task, therefore, we can create a function to define and return the model where the number of input and number of output variables are provided as arguments.


    Now that we are familiar with how to define an MLP for multi-output regression, let’s explore how this model can be evaluated.

    Neural Network for Multi-Output Regression

    If the dataset is small, it is good practice to evaluate neural network models repeatedly on the same dataset and report the mean performance across the repeats.

    This is because of the stochastic nature of the learning algorithm.

    Additionally, it is good practice to use k-fold cross-validation instead of train/test splits of a dataset to get an unbiased estimate of model performance when making predictions on new data. Again, only if there is not too much data and the process can be completed in a reasonable time.

    Taking this into account, we will evaluate the MLP model on the multi-output regression task using repeated k-fold cross-validation with 10 folds and three repeats.

    Each fold the model is defined, fit, and evaluated. The scores are collected and can be summarized by reporting the mean and standard deviation.

    The evaluate_model() function below takes the dataset, evaluates the model, and returns a list of evaluation scores, in this case, MAE scores.


    We can then load our dataset and evaluate the model and report the mean performance.

    Tying this together, the complete example is listed below.


    Running the example reports the MAE for each fold and each repeat, to give an idea of the evaluation progress.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    At the end, the mean and standard deviation MAE is reported. In this case, the model is shown to achieve a MAE of about 8.184.

    You can use this code as a template for evaluating MLP models on your own multi-output regression tasks. The number of nodes and layers in the model can easily be adapted and tailored to the complexity of your dataset.


    Once a model configuration is chosen, we can use it to fit a final model on all available data and make a prediction for new data.

    The example below demonstrates this by first fitting the MLP model on the entire multi-output regression dataset, then calling the predict() function on the saved model in order to make a prediction for a new row of data.


    Running the example fits the model and makes a prediction for a new row.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    As expected, the prediction contains three output variables required for the multi-output regression task.


    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Summary

    In this tutorial, you discovered how to develop deep learning models for multi-output regression.

    Specifically, you learned:

    • Multi-output regression is a predictive modeling task that involves two or more numerical output variables.
    • Neural network models can be configured for multi-output regression tasks.
    • How to evaluate a neural network for multi-output regression and make a prediction for new data.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Develop Deep Learning Projects with Python!

    Deep Learning with Python
     What If You Could Develop A Network in Minutes

    …with just a few lines of Python

    Discover how in my new Ebook:
    Deep Learning With Python

    It covers end-to-end projects on topics like:
    Multilayer Perceptrons, Convolutional Nets and Recurrent Neural Nets, and more…

    Finally Bring Deep Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    HyperOpt-for-Automated-Machine-Learning-With-Scikit-Learn.jpg

    HyperOpt for Automated Machine Learning With Scikit-Learn

    Automated Machine Learning (AutoML) refers to techniques for automatically discovering well-performing models for predictive modeling tasks with very little user involvement.

    HyperOpt is an open-source library for large scale AutoML and HyperOpt-Sklearn is a wrapper for HyperOpt that supports AutoML with HyperOpt for the popular Scikit-Learn machine learning library, including the suite of data preparation transforms and classification and regression algorithms.

    In this tutorial, you will discover how to use HyperOpt for automatic machine learning with Scikit-Learn in Python.

    After completing this tutorial, you will know:

    • Hyperopt-Sklearn is an open-source library for AutoML with scikit-learn data preparation and machine learning models.
    • How to use Hyperopt-Sklearn to automatically discover top-performing models for classification tasks.
    • How to use Hyperopt-Sklearn to automatically discover top-performing models for regression tasks.

    Let’s get started.

    HyperOpt for Automated Machine Learning With Scikit-Learn

    HyperOpt for Automated Machine Learning With Scikit-Learn
    Photo by Neil Williamson, some rights reserved.

    Tutorial Overview

    This tutorial is divided into four parts; they are:

  • HyperOpt and HyperOpt-Sklearn
  • How to Install and Use HyperOpt-Sklearn
  • HyperOpt-Sklearn for Classification
  • HyperOpt-Sklearn for Regression
  • HyperOpt and HyperOpt-Sklearn

    HyperOpt is an open-source Python library for Bayesian optimization developed by James Bergstra.

    It is designed for large-scale optimization for models with hundreds of parameters and allows the optimization procedure to be scaled across multiple cores and multiple machines.

    The library was explicitly used to optimize machine learning pipelines, including data preparation, model selection, and model hyperparameters.

    Our approach is to expose the underlying expression graph of how a performance metric (e.g. classification accuracy on validation examples) is computed from hyperparameters that govern not only how individual processing steps are applied, but even which processing steps are included.

    — Making a Science of Model Search: Hyperparameter Optimization in Hundreds of Dimensions for Vision Architectures, 2013.

    HyperOpt is challenging to use directly, requiring the optimization procedure and search space to be carefully specified.

    An extension to HyperOpt was created called HyperOpt-Sklearn that allows the HyperOpt procedure to be applied to data preparation and machine learning models provided by the popular Scikit-Learn open-source machine learning library.

    HyperOpt-Sklearn wraps the HyperOpt library and allows for the automatic search of data preparation methods, machine learning algorithms, and model hyperparameters for classification and regression tasks.

    … we introduce Hyperopt-Sklearn: a project that brings the benefits of automatic algorithm configuration to users of Python and scikit-learn. Hyperopt-Sklearn uses Hyperopt to describe a search space over possible configurations of Scikit-Learn components, including preprocessing and classification modules.

    — Hyperopt-Sklearn: Automatic Hyperparameter Configuration for Scikit-Learn, 2014.

    Now that we are familiar with HyperOpt and HyperOpt-Sklearn, let’s look at how to use HyperOpt-Sklearn.

    How to Install and Use HyperOpt-Sklearn

    The first step is to install the HyperOpt library.

    This can be achieved using the pip package manager as follows:


    Once installed, we can confirm that the installation was successful and check the version of the library by typing the following command:


    This will summarize the installed version of HyperOpt, confirming that a modern version is being used.


    Next, we must install the HyperOpt-Sklearn library.

    This too can be installed using pip, although we must perform this operation manually by cloning the repository and running the installation from the local files, as follows:


    Again, we can confirm that the installation was successful by checking the version number with the following command:


    This will summarize the installed version of HyperOpt-Sklearn, confirming that a modern version is being used.


    Now that the required libraries are installed, we can review the HyperOpt-Sklearn API.

    Using HyperOpt-Sklearn is straightforward. The search process is defined by creating and configuring an instance of the HyperoptEstimator class.

    The algorithm used for the search can be specified via the “algo” argument, the number of evaluations performed in the search is specified via the “max_evals” argument, and a limit can be imposed on evaluating each pipeline via the “trial_timeout” argument.


    Many different optimization algorithms are available, including:

    • Random Search
    • Tree of Parzen Estimators
    • Annealing
    • Tree
    • Gaussian Process Tree

    The “Tree of Parzen Estimators” is a good default, and you can learn more about the types of algorithms in the paper “Algorithms for Hyper-Parameter Optimization. [PDF]”

    For classification tasks, the “classifier” argument specifies the search space of models, and for regression, the “regressor” argument specifies the search space of models, both of which can be set to use predefined lists of models provided by the library, e.g. “any_classifier” and “any_regressor“.

    Similarly, the search space of data preparation is specified via the “preprocessing” argument and can also use a pre-defined list of preprocessing steps via “any_preprocessing.


    For more on the other arguments to the search, you can review the source code for the class directly:

    Once the search is defined, it can be executed by calling the fit() function.


    At the end of the run, the best-performing model can be evaluated on new data by calling the score() function.


    Finally, we can retrieve the Pipeline of transforms, models, and model configurations that performed the best on the training dataset via the best_model() function.


    Now that we are familiar with the API, let’s look at some worked examples.

    HyperOpt-Sklearn for Classification

    In this section, we will use HyperOpt-Sklearn to discover a model for the sonar dataset.

    The sonar dataset is a standard machine learning dataset comprised of 208 rows of data with 60 numerical input variables and a target variable with two class values, e.g. binary classification.

    Using a test harness of repeated stratified 10-fold cross-validation with three repeats, a naive model can achieve an accuracy of about 53 percent. A top-performing model can achieve accuracy on this same test harness of about 88 percent. This provides the bounds of expected performance on this dataset.

    The dataset involves predicting whether sonar returns indicate a rock or simulated mine.

    No need to download the dataset; we will download it automatically as part of our worked examples.

    The example below downloads the dataset and summarizes its shape.


    Running the example downloads the dataset and splits it into input and output elements. As expected, we can see that there are 208 rows of data with 60 input variables.


    Next, let’s use HyperOpt-Sklearn to find a good model for the sonar dataset.

    We can perform some basic data preparation, including converting the target string to class labels, then split the dataset into train and test sets.


    Next, we can define the search procedure. We will explore all classification algorithms and all data transforms available to the library and use the TPE, or Tree of Parzen Estimators, search algorithm, described in “Algorithms for Hyper-Parameter Optimization.”

    The search will evaluate 50 pipelines and limit each evaluation to 30 seconds.


    We then start the search.


    At the end of the run, we will report the performance of the model on the holdout dataset and summarize the best performing pipeline.


    Tying this together, the complete example is listed below.


    Running the example may take a few minutes.

    The progress of the search will be reported and you will see some warnings that you can safely ignore.

    At the end of the run, the best-performing model is evaluated on the holdout dataset and the Pipeline discovered is printed for later use.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    In this case, we can see that the chosen model achieved an accuracy of about 85.5 percent on the holdout test set. The Pipeline involves a gradient boosting model with no pre-processing.


    The printed model can then be used directly, e.g. the code copy-pasted into another project.

    Next, let’s take a look at using HyperOpt-Sklearn for a regression predictive modeling problem.

    HyperOpt-Sklearn for Regression

    In this section, we will use HyperOpt-Sklearn to discover a model for the housing dataset.

    The housing dataset is a standard machine learning dataset comprised of 506 rows of data with 13 numerical input variables and a numerical target variable.

    Using a test harness of repeated stratified 10-fold cross-validation with three repeats, a naive model can achieve a mean absolute error (MAE) of about 6.6. A top-performing model can achieve a MAE on this same test harness of about 1.9. This provides the bounds of expected performance on this dataset.

    The dataset involves predicting the house price given details of the house suburb in the American city of Boston.

    No need to download the dataset; we will download it automatically as part of our worked examples.

    The example below downloads the dataset and summarizes its shape.


    Running the example downloads the dataset and splits it into input and output elements. As expected, we can see that there are 63 rows of data with one input variable.


    Next, we can use HyperOpt-Sklearn to find a good model for the auto insurance dataset.

    Using HyperOpt-Sklearn for regression is the same as using it for classification, except the “regressor” argument must be specified.

    In this case, we want to optimize the MAE, therefore, we will set the “loss_fn” argument to the mean_absolute_error() function provided by the scikit-learn library.


    Tying this together, the complete example is listed below.


    Running the example may take a few minutes.

    The progress of the search will be reported and you will see some warnings that you can safely ignore.

    At the end of the run, the best performing model is evaluated on the holdout dataset and the Pipeline discovered is printed for later use.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    In this case, we can see that the chosen model achieved a MAE of about 0.883 on the holdout test set, which appears skillful. The Pipeline involves an XGBRegressor model with no pre-processing.

    Note: for the search to use XGBoost, you must have the XGBoost library installed.


    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Summary

    In this tutorial, you discovered how to use HyperOpt for automatic machine learning with Scikit-Learn in Python.

    Specifically, you learned:

    • Hyperopt-Sklearn is an open-source library for AutoML with scikit-learn data preparation and machine learning models.
    • How to use Hyperopt-Sklearn to automatically discover top-performing models for classification tasks.
    • How to use Hyperopt-Sklearn to automatically discover top-performing models for regression tasks.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Discover Fast Machine Learning in Python!

    Master Machine Learning With Python
    Develop Your Own Models in Minutes

    …with just a few lines of scikit-learn code

    Learn how in my new Ebook:
    Machine Learning Mastery With Python

    Covers self-study tutorials and end-to-end projects like:
    Loading data, visualization, modeling, tuning, and much more…

    Finally Bring Machine Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    Multi-Label-Classification-with-Deep-Learning.jpg

    Multi-Label Classification with Deep Learning

    Last Updated on August 31, 2020

    Multi-label classification involves predicting zero or more class labels.

    Unlike normal classification tasks where class labels are mutually exclusive, multi-label classification requires specialized machine learning algorithms that support predicting multiple mutually non-exclusive classes or “labels.”

    Deep learning neural networks are an example of an algorithm that natively supports multi-label classification problems. Neural network models for multi-label classification tasks can be easily defined and evaluated using the Keras deep learning library.

    In this tutorial, you will discover how to develop deep learning models for multi-label classification.

    After completing this tutorial, you will know:

    • Multi-label classification is a predictive modeling task that involves predicting zero or more mutually non-exclusive class labels.
    • Neural network models can be configured for multi-label classification tasks.
    • How to evaluate a neural network for multi-label classification and make a prediction for new data.

    Let’s get started.

    Multi-Label Classification with Deep Learning

    Multi-Label Classification with Deep Learning
    Photo by Trevor Marron, some rights reserved.

    Tutorial Overview

    This tutorial is divided into three parts; they are:

    • Multi-Label Classification
    • Neural Networks for Multiple Labels
    • Neural Network for Multi-Label Classification

    Multi-Label Classification

    Classification is a predictive modeling problem that involves outputting a class label given some input

    It is different from regression tasks that involve predicting a numeric value.

    Typically, a classification task involves predicting a single label. Alternately, it might involve predicting the likelihood across two or more class labels. In these cases, the classes are mutually exclusive, meaning the classification task assumes that the input belongs to one class only.

    Some classification tasks require predicting more than one class label. This means that class labels or class membership are not mutually exclusive. These tasks are referred to as multiple label classification, or multi-label classification for short.

    In multi-label classification, zero or more labels are required as output for each input sample, and the outputs are required simultaneously. The assumption is that the output labels are a function of the inputs.

    We can create a synthetic multi-label classification dataset using the make_multilabel_classification() function in the scikit-learn library.

    Our dataset will have 1,000 samples with 10 input features. The dataset will have three class label outputs for each sample and each class will have one or two values (0 or 1, e.g. present or not present).

    The complete example of creating and summarizing the synthetic multi-label classification dataset is listed below.


    Running the example creates the dataset and summarizes the shape of the input and output elements.

    We can see that, as expected, there are 1,000 samples, each with 10 input features and three output features.

    The first 10 rows of inputs and outputs are summarized and we can see that all inputs for this dataset are numeric and that output class labels have 0 or 1 values for each of the three class labels.


    Next, let’s look at how we can develop neural network models for multi-label classification tasks.

    Neural Networks for Multiple Labels

    Some machine learning algorithms support multi-label classification natively.

    Neural network models can be configured to support multi-label classification and can perform well, depending on the specifics of the classification task.

    Multi-label classification can be supported directly by neural networks simply by specifying the number of target labels there is in the problem as the number of nodes in the output layer. For example, a task that has three output labels (classes) will require a neural network output layer with three nodes in the output layer.

    Each node in the output layer must use the sigmoid activation. This will predict a probability of class membership for the label, a value between 0 and 1. Finally, the model must be fit with the binary cross-entropy loss function.

    In summary, to configure a neural network model for multi-label classification, the specifics are:

    • Number of nodes in the output layer matches the number of labels.
    • Sigmoid activation for each node in the output layer.
    • Binary cross-entropy loss function.

    We can demonstrate this using the Keras deep learning library.

    We will define a Multilayer Perceptron (MLP) model for the multi-label classification task defined in the previous section.

    Each sample has 10 inputs and three outputs; therefore, the network requires an input layer that expects 10 inputs specified via the “input_dim” argument in the first hidden layer and three nodes in the output layer.

    We will use the popular ReLU activation function in the hidden layer. The hidden layer has 20 nodes that were chosen after some trial and error. We will fit the model using binary cross-entropy loss and the Adam version of stochastic gradient descent.

    The definition of the network for the multi-label classification task is listed below.


    You may want to adapt this model for your own multi-label classification task; therefore, we can create a function to define and return the model where the number of input and output variables is provided as arguments.


    Now that we are familiar with how to define an MLP for multi-label classification, let’s explore how this model can be evaluated.

    Neural Network for Multi-Label Classification

    If the dataset is small, it is good practice to evaluate neural network models repeatedly on the same dataset and report the mean performance across the repeats.

    This is because of the stochastic nature of the learning algorithm.

    Additionally, it is good practice to use k-fold cross-validation instead of train/test splits of a dataset to get an unbiased estimate of model performance when making predictions on new data. Again, only if there is not too much data that the process can be completed in a reasonable time.

    Taking this into account, we will evaluate the MLP model on the multi-output regression task using repeated k-fold cross-validation with 10 folds and three repeats.

    The MLP model will predict the probability for each class label by default. This means it will predict three probabilities for each sample. These can be converted to crisp class labels by rounding the values to either 0 or 1. We can then calculate the classification accuracy for the crisp class labels.


    The scores are collected and can be summarized by reporting the mean and standard deviation across all repeats and cross-validation folds.

    The evaluate_model() function below takes the dataset, evaluates the model, and returns a list of evaluation scores, in this case, accuracy scores.


    We can then load our dataset and evaluate the model and report the mean performance.

    Tying this together, the complete example is listed below.


    Running the example reports the classification accuracy for each fold and each repeat, to give an idea of the evaluation progress.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    At the end, the mean and standard deviation accuracy is reported. In this case, the model is shown to achieve an accuracy of about 81.2 percent.

    You can use this code as a template for evaluating MLP models on your own multi-label classification tasks. The number of nodes and layers in the model can easily be adapted and tailored to the complexity of your dataset.


    Once a model configuration is chosen, we can use it to fit a final model on all available data and make a prediction for new data.

    The example below demonstrates this by first fitting the MLP model on the entire multi-label classification dataset, then calling the predict() function on the saved model in order to make a prediction for a new row of data.


    Running the example fits the model and makes a prediction for a new row. As expected, the prediction contains three output variables required for the multi-label classification task: the probabilities of each class label.


    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Summary

    In this tutorial, you discovered how to develop deep learning models for multi-label classification.

    Specifically, you learned:

    • Multi-label classification is a predictive modeling task that involves predicting zero or more mutually non-exclusive class labels.
    • Neural network models can be configured for multi-label classification tasks.
    • How to evaluate a neural network for multi-label classification and make a prediction for new data.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Develop Deep Learning Projects with Python!

    Deep Learning with Python
     What If You Could Develop A Network in Minutes

    …with just a few lines of Python

    Discover how in my new Ebook:
    Deep Learning With Python

    It covers end-to-end projects on topics like:
    Multilayer Perceptrons, Convolutional Nets and Recurrent Neural Nets, and more…

    Finally Bring Deep Learning To

    Your Own Projects

    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo

    A-Gentle-Introduction-to-Computational-Learning-Theory.jpg

    A Gentle Introduction to Computational Learning Theory

    Last Updated on August 19, 2020

    Computational learning theory, or statistical learning theory, refers to mathematical frameworks for quantifying learning tasks and algorithms.

    These are sub-fields of machine learning that a machine learning practitioner does not need to know in great depth in order to achieve good results on a wide range of problems. Nevertheless, it is a sub-field where having a high-level understanding of some of the more prominent methods may provide insight into the broader task of learning from data.

    In this post, you will discover a gentle introduction to computational learning theory for machine learning.

    After reading this post, you will know:

    • Computational learning theory uses formal methods to study learning tasks and learning algorithms.
    • PAC learning provides a way to quantify the computational difficulty of a machine learning task.
    • VC Dimension provides a way to quantify the computational capacity of a machine learning algorithm.

    Kick-start your project with my new book Probability for Machine Learning, including step-by-step tutorials and the Python source code files for all examples.

    Let’s get started.

    A Gentle Introduction to Computational Learning Theory

    A Gentle Introduction to Computational Learning Theory
    Photo by someone10x, some rights reserved.

    Tutorial Overview

    This tutorial is divided into three parts; they are:

  • Computational Learning Theory
  • PAC Learning (Theory of Learning Problems)
  • VC Dimension (Theory of Learning Algorithms)
  • Computational Learning Theory

    Computational learning theory, or CoLT for short, is a field of study concerned with the use of formal mathematical methods applied to learning systems.

    It seeks to use the tools of theoretical computer science to quantify learning problems. This includes characterizing the difficulty of learning specific tasks.

    Computational learning theory may be thought of as an extension or sibling of statistical learning theory, or SLT for short, that uses formal methods to quantify learning algorithms.

    • Computational Learning Theory (CoLT): Formal study of learning tasks.
    • Statistical Learning Theory (SLT): Formal study of learning algorithms.

    This division of learning tasks vs. learning algorithms is arbitrary, and in practice, there is a lot of overlap between the two fields.

    One can extend statistical learning theory by taking computational complexity of the learner into account. This field is called computational learning theory or COLT.

    — Page 210, Machine Learning: A Probabilistic Perspective, 2012.

    They might be considered synonyms in modern usage.

    … a theoretical framework known as computational learning theory, also some- times called statistical learning theory.

    — Page 344, Pattern Recognition and Machine Learning, 2006.

    The focus in computational learning theory is typically on supervised learning tasks. Formal analysis of real problems and real algorithms is very challenging. As such, it is common to reduce the complexity of the analysis by focusing on binary classification tasks and even simple binary rule-based systems. As such, the practical application of the theorems may be limited or challenging to interpret for real problems and algorithms.

    The main unanswered question in learning is this: How can we be sure that our learning algorithm has produced a hypothesis that will predict the correct value for previously unseen inputs?

    — Page 713, Artificial Intelligence: A Modern Approach, 3rd edition, 2009.

    Questions explored in computational learning theory might include:

    • How do we know a model has a good approximation for the target function?
    • What hypothesis space should be used?
    • How do we know if we have a local or globally good solution?
    • How do we avoid overfitting?
    • How many data examples are needed?

    As a machine learning practitioner, it can be useful to know about computational learning theory and some of the main areas of investigation. The field provides a useful grounding for what we are trying to achieve when fitting models on data, and it may provide insight into the methods.

    There are many subfields of study, although perhaps two of the most widely discussed areas of study from computational learning theory are:

    • PAC Learning.
    • VC Dimension.

    Tersely, we can say that PAC Learning is the theory of machine learning problems and VC dimension is the theory of machine learning algorithms.

    You may encounter the topics as a practitioner and it is useful to have a thumbnail idea of what they are about. Let’s take a closer look at each.

    If you would like to dive deeper into the field of computational learning theory, I recommend the book:

    PAC Learning (Theory of Learning Problems)

    Probability approximately correct learning, or PAC learning, refers to a theoretical machine learning framework developed by Leslie Valiant.

    PAC learning seeks to quantify the difficulty of a learning task and might be considered the premier sub-field of computational learning theory.

    Consider that in supervised learning, we are trying to approximate an unknown underlying mapping function from inputs to outputs. We don’t know what this mapping function looks like, but we suspect it exists, and we have examples of data produced by the function.

    PAC learning is concerned with how much computational effort is required to find a hypothesis (fit model) that is a close match for the unknown target function.

    For more on the use of “hypothesis” in machine learning to refer to a fit model, see the tutorial:

    The idea is that a bad hypothesis will be found out based on the predictions it makes on new data, e.g. based on its generalization error.

    A hypothesis that gets most or a large number of predictions correct, e.g. has a small generalization error, is probably a good approximation for the target function.

    The underlying principle is that any hypothesis that is seriously wrong will almost certainly be “found out” with high probability after a small number of examples, because it will make an incorrect prediction. Thus, any hypothesis that is consistent with a sufficiently large set of training examples is unlikely to be seriously wrong: that is, TELY it must be probably approximately correct.

    — Page 714, Artificial Intelligence: A Modern Approach, 3rd edition, 2009.

    This probabilistic language gives the theorem its name: “probability approximately correct.” That is, a hypothesis seeks to “approximate” a target function and is “probably” good if it has a low generalization error.

    A PAC learning algorithm refers to an algorithm that returns a hypothesis that is PAC.

    Using formal methods, a minimum generalization error can be specified for a supervised learning task. The theorem can then be used to estimate the expected number of samples from the problem domain that would be required to determine whether a hypothesis was PAC or not. That is, it provides a way to estimate the number of samples required to find a PAC hypothesis.

    The goal of the PAC framework is to understand how large a data set needs to be in order to give good generalization. It also gives bounds for the computational cost of learning …

    — Page 344, Pattern Recognition and Machine Learning, 2006.

    Additionally, a hypothesis space (machine learning algorithm) is efficient under the PAC framework if an algorithm can find a PAC hypothesis (fit model) in polynomial time.

    A hypothesis space is said to be efficiently PAC-learnable if there is a polynomial time algorithm that can identify a function that is PAC.

    — Page 210, Machine Learning: A Probabilistic Perspective, 2012.

    For more on PAC learning, refer to the seminal book on the topic titled:

    VC Dimension (Theory of Learning Algorithms)

    Vapnik–Chervonenkis theory, or VC theory for short, refers to a theoretical machine learning framework developed by Vladimir Vapnik and Alexey Chervonenkis.

    VC theory learning seeks to quantify the capability of a learning algorithm and might be considered the premier sub-field of statistical learning theory.

    VC theory is comprised of many elements, most notably the VC dimension.

    The VC dimension quantifies the complexity of a hypothesis space, e.g. the models that could be fit given a representation and learning algorithm.

    One way to consider the complexity of a hypothesis space (space of models that could be fit) is based on the number of distinct hypotheses it contains and perhaps how the space might be navigated. The VC dimension is a clever approach that instead measures the number of examples from the target problem that can be discriminated by hypotheses in the space.

    The VC dimension measures the complexity of the hypothesis space […] by the number of distinct instances from X that can be completely discriminated using H.

    — Page 214, Machine Learning, 1997.

    The VC dimension estimates the capability or capacity of a classification machine learning algorithm for a specific dataset (number and dimensionality of examples).

    Formally, the VC dimension is the largest number of examples from the training dataset that the space of hypothesis from the algorithm can “shatter.”

    The Vapnik-Chervonenkis dimension, VC(H), of hypothesis space H defined over instance space X is the size of the largest finite subset of X shattered by H.

    — Page 215, Machine Learning, 1997.

    Shatter or a shattered set, in the case of a dataset, means points in the feature space can be selected or separated from each other using hypotheses in the space such that the labels of examples in the separate groups are correct (whatever they happen to be).

    Whether a group of points can be shattered by an algorithm depends on the hypothesis space and the number of points.

    For example, a line (hypothesis space) can be used to shatter three points, but not four points.

    Any placement of three points on a 2d plane with class labels 0 or 1 can be “correctly” split by label with a line, e.g. shattered. But, there exists placements of four points on plane with binary class labels that cannot be correctly split by label with a line, e.g. cannot be shattered. Instead, another “algorithm” must be used, such as ovals.

    The figure below makes this clear.

    Example of a Line Hypothesis Shattering 3 Points and Ovals Shattering 4 Points

    Example of a Line Hypothesis Shattering 3 Points and Ovals Shattering 4 Points
    Taken from Page 81, The Nature of Statistical Learning Theory, 1999.

    Therefore, the VC dimension of a machine learning algorithm is the largest number of data points in a dataset that a specific configuration of the algorithm (hyperparameters) or specific fit model can shatter.

    A classifier that predicts the same value in all cases will have a VC dimension of 0, no points. A large VC dimension indicates that an algorithm is very flexible, although the flexibility may come at the cost of additional risk of overfitting.

    The VC dimension is used as part of the PAC learning framework.

    A key quantity in PAC learning is the Vapnik-Chervonenkis dimension, or VC dimension, which provides a measure of the complexity of a space of functions, and which allows the PAC framework to be extended to spaces containing an infinite number of functions.

    — Page 344, Pattern Recognition and Machine Learning, 2006.

    For more on PCA Learning, refer to the seminal book on the topic titled:

    Further Reading

    This section provides more resources on the topic if you are looking to go deeper.

    Books
    Articles

    Summary

    In this post, you discovered a gentle introduction to computational learning theory for machine learning.

    Specifically, you learned:

    • Computational learning theory uses formal methods to study learning tasks and learning algorithms.
    • PAC learning provides a way to quantify the computational difficulty of a machine learning task.
    • VC Dimension provides a way to quantify the computational capacity of a machine learning algorithm.

    Do you have any questions?
    Ask your questions in the comments below and I will do my best to answer.

    Get a Handle on Probability for Machine Learning!

    Probability for Machine Learning

    Develop Your Understanding of Probability
    …with just a few lines of python code

    Discover how in my new Ebook:
    Probability for Machine Learning

    It provides self-study tutorials and end-to-end projects on:
    Bayes Theorem, Bayesian Optimization, Distributions, Maximum Likelihood, Cross-Entropy, Calibrating Models

    and much more…

    Finally Harness Uncertainty in Your Projects
    Skip the Academics. Just Results.

    See What’s Inside

    Covid Abruzzo Basilicata Calabria Campania Emilia Romagna Friuli Venezia Giulia Lazio Liguria Lombardia Marche Molise Piemonte Puglia Sardegna Sicilia Toscana Trentino Alto Adige Umbria Valle d’Aosta Veneto Italia Agrigento Alessandria Ancona Aosta Arezzo Ascoli Piceno Asti Avellino Bari Barletta-Andria-Trani Belluno Benevento Bergamo Biella Bologna Bolzano Brescia Brindisi Cagliari Caltanissetta Campobasso Carbonia-Iglesias Caserta Catania Catanzaro Chieti Como Cosenza Cremona Crotone Cuneo Enna Fermo Ferrara Firenze Foggia Forlì-Cesena Frosinone Genova Gorizia Grosseto Imperia Isernia La Spezia L’Aquila Latina Lecce Lecco Livorno Lodi Lucca Macerata Mantova Massa-Carrara Matera Messina Milano Modena Monza e della Brianza Napoli Novara Nuoro Olbia-Tempio Oristano Padova Palermo Parma Pavia Perugia Pesaro e Urbino Pescara Piacenza Pisa Pistoia Pordenone Potenza Prato Ragusa Ravenna Reggio Calabria Reggio Emilia Rieti Rimini Roma Rovigo Salerno Medio Campidano Sassari Savona Siena Siracusa Sondrio Taranto Teramo Terni Torino Ogliastra Trapani Trento Treviso Trieste Udine Varese Venezia Verbano-Cusio-Ossola Vercelli Verona Vibo Valentia Vicenza Viterbo