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

    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

    Why-Do-I-Get-Different-Results-Each-Time-in-Machine.jpg

    Why Do I Get Different Results Each Time in Machine Learning?

    Last Updated on August 27, 2020

    Are you getting different results for your machine learning algorithm?

    Perhaps your results differ from a tutorial and you want to understand why.

    Perhaps your model is making different predictions each time it is trained, even when it is trained on the same data set each time.

    This is to be expected and might even be a feature of the algorithm, not a bug.

    In this tutorial, you will discover why you can expect different results when using machine learning algorithms.

    After completing this tutorial, you will know:

    • Machine learning algorithms will train different models if the training dataset is changed.
    • Stochastic machine learning algorithms use randomness during learning, ensuring a different model is trained each run.
    • Differences in the development environment, such as software versions and CPU type, can cause rounding error differences in predictions and model evaluations.

    Let’s get started.

    Why Do I Get Different Results Each Time in Machine Learning?

    Why Do I Get Different Results Each Time in Machine Learning?
    Photo by Bonnie Moreland, some rights reserved.

    Tutorial Overview

    This tutorial is divided into five parts; they are:

  • Help, I’m Getting Different Results!?
  • Differences Caused by Training Data
  • Differences Caused by Learning Algorithm
  • Differences Caused by Evaluation Procedure
  • Differences Caused by Platform
  • 1. Help, I’m Getting Different Results!?

    Don’t panic. Machine learning algorithms or models can give different results.

    It’s not your fault. In fact, it is often a feature, not a bug.

    We will clearly specify and explain the problem you are having.

    First, let’s get a handle on the basics.

    In applied machine learning, we run a machine learning “algorithm” on a dataset to get a machine learning “model.” The model can then be evaluated on data not used during training or used to make predictions on new data, also not seen during training.

    • Algorithm: Procedure run on data that results in a model (e.g. training or learning).
    • Model: Data structure and coefficients used to make predictions on data.

    For more on the difference between machine learning algorithms and models, see the tutorial:

    Supervised machine learning means we have examples (rows) with input and output variables (columns). We cannot write code to predict outputs given inputs because it is too hard, so we use machine learning algorithms to learn how to predict outputs from inputs given historical examples.

    This is called function approximation, and we are learning or searching for a function that maps inputs to outputs on our specific prediction task in such a way that it has skill, meaning the performance of the mapping is better than random and ideally better than all other algorithms and algorithm configurations we have tried.

    • Supervised Learning: Automatically learn a mapping function from examples of inputs to examples of outputs.

    In this sense, a machine learning model is a program we intend to use for some project or application; it just so happens that the program was learned from examples (using an algorithm) rather than written explicitly with if-statements and such. It’s a type of automatic programming.

    • Machine Learning Model: A “program” automatically learned from historical data.

    Unlike the programming that we may be used to, the programs may not be entirely deterministic.

    The machine learning models may be different each time they are trained. In turn, the models may make different predictions, and when evaluated, may have a different level of error or accuracy.

    There are at least four cases where you will get different results; they are:

    • Different results because of differences in training data.
    • Different results because of stochastic learning algorithms.
    • Different results because of stochastic evaluation procedures.
    • Different results because of differences in platform.

    Let’s take a closer look at each in turn.

    Did I miss a possible cause of a difference in results?
    Let me know in the comments below.

    2. Differences Caused by Training Data

    You will get different results when you run the same algorithm on different data.

    This is referred to as the variance of the machine learning algorithm. You may have heard of it in the context of the bias-variance trade-off.

    The variance is a measure of how sensitive the algorithm is to the specific data used during training.

    • Variance: How sensitive the algorithm is to the specific data used during training.

    A more sensitive algorithm has a larger variance, which will result in more difference in the model, and in turn, the predictions made and evaluation of the model. Conversely, a less sensitive algorithm has a smaller variance and will result in less difference in the resulting model with different training data, and in turn, less difference in the resulting predictions and model evaluation.

    • High Variance: Algorithm is more sensitive to the specific data used during training.
    • Low Variance: Algorithm is less sensitive to the specific data used during training.

    For more on the variance and the bias-variance trade-off, see the tutorial:

    All useful machine learning algorithms will have some variance, and some of the most effective algorithms will have a high variance.

    Algorithms with a high variance often require more training data than those algorithms with less variance. This is intuitive if we consider the model approximating a mapping function from inputs and outputs and the law of large numbers.

    Nevertheless, when you train a machine learning algorithm on different training data, you will get a different model that has different behavior. This means different training data will give models that make different predictions and have a different estimate of performance (e.g. error or accuracy).

    The amount of difference in the results will be related to how different the training data is for each model, and the variance of the specific model and model configuration you have chosen.

    What Should I Do?

    You can often reduce the variance of the model by changing a hyperparameter of the algorithm.

    For example, the k in k-nearest neighbors controls the variance of the algorithm, where small values like k=1 result in high variance and large values like k=21 result in low variance.

    You can reduce the variance by changing the algorithm. For example, simpler algorithms like linear regression and logistic regression have a lower variance than other types of algorithms.

    You can also lower the variance with a high variance algorithm by increasing the size of the training dataset, meaning you may need to collect more data.

    3. Differences Caused by Learning Algorithm

    You can get different results when you run the same algorithm on the same data due to the nature of the learning algorithm.

    This is the most likely reason that you’re reading this tutorial.

    You run the same code on the same dataset and get a model that makes different predictions or has a different performance each time, and you think it’s a bug or something. Am I right?

    It’s not a bug, it’s a feature.

    Some machine learning algorithms are deterministic. Just like the programming that you’re used to. That means, when the algorithm is given the same dataset, it learns the same model every time. An example is a linear regression or logistic regression algorithm.

    Some algorithms are not deterministic; instead, they are stochastic. This means that their behavior incorporates elements of randomness.

    Stochastic does not mean random. Stochastic machine learning algorithms are not learning a random model. They are learning a model conditional on the historical data you have provided. Instead, the specific small decisions made by the algorithm during the learning process can vary randomly.

    The impact is that each time the stochastic machine learning algorithm is run on the same data, it learns a slightly different model. In turn, the model may make slightly different predictions, and when evaluated using error or accuracy, may have a slightly different performance.

    For more on stochastic and what it means in machine learning, see the tutorial:

    Adding randomness to some of the decisions made by an algorithm can improve performance on hard problems. Learning a supervised learning mapping function with a limited sample of data from the domain is a very hard problem.

    Finding a good or best mapping function for a dataset is a type of search problem. We test different algorithms and test algorithm configurations that define the shape of the search space and give us a starting point in the search space. We then run the algorithms, which then navigate the search space to a single model.

    Adding randomness can help avoid the good solutions and help find the really good and great solutions in the search space. They allow the model to escape local optima or deceptive local optima where the learning algorithm might get such, and help find better solutions, even a global optima.

    For more on thinking about supervised learning as a search problem, see the tutorial:

    An example of an algorithm that uses randomness during learning is a neural network. It uses randomness in two ways:

    • Random initial weights (model coefficients).
    • Random shuffle of samples each epoch.

    Neural networks (deep learning) are a stochastic machine learning algorithm. The random initial weights allow the model to try learning from a different starting point in the search space each algorithm run and allow the learning algorithm to “break symmetry” during learning. The random shuffle of examples during training ensures that each gradient estimate and weight update is slightly different.

    For more on the stochastic nature of neural networks, see the tutorial:

    Another example is ensemble machine learning algorithms that are stochastic, such as bagging.

    Randomness is used in the sampling procedure of the training dataset that ensures a different decision tree is prepared for each contributing member in the ensemble. In ensemble learning, this is called ensemble diversity and is an approach to simulating independent predictions from a single training dataset.

    For more on the stochastic nature of bagging ensembles, see the tutorial:

    What Should I Do?

    The randomness used by learning algorithms can be controlled.

    For example, you set the seed used by the pseudorandom number generator to ensure that each time the algorithm is run, it gets the same randomness.

    For more on random number generators and setting fixing the seed, see the tutorial:

    This can be a good approach for tutorials, but not a good approach in practice. It leads to questions like:

    • What is the best seed for the pseudorandom number generator?

    There is no best seed for a stochastic machine learning algorithm. You are fighting the nature of the algorithm, forcing stochastic learning to be deterministic.

    You could make a case that the final model is fit using a fixed seed to ensure the same model is created from the same data before being used in production prior to any pre-deployment system testing. Nevertheless, as soon as the training dataset changes, the model will change.

    A better approach is to embrace the stochastic nature of machine learning algorithms.

    Consider that there is not a single model for your dataset. Instead, there is a stochastic process (the algorithm pipeline) that can generate models for your problem.

    For more on this, see the tutorial:

    You can then summarize the performance of these models — of the algorithm pipeline — as a distribution with mean expected error or accuracy and a standard deviation.

    You can then ensure you achieve the average performance of the models by fitting multiple final models on your dataset and averaging their predictions when you need to make a prediction on new data.

    For more on the ensemble approach to final models, see the tutorial:

    4. Differences Caused by Evaluation Procedure

    You can get different results when running the same algorithm with the same data due to the evaluation procedure.

    The two most common evaluation procedures are a train-test split and k-fold cross-validation.

    A train-test split involves randomly assigning rows to either be used to train the model or evaluate the model to meet a predefined train or test set size.

    For more on the train-test split, see the tutorial:

    The k-fold cross-validation procedure involves dividing a dataset into k non-overlapping partitions and using one fold as the test set and all other folds as the training set. A model is fit on the training set and evaluated on the holdout fold and this process is repeated k times, giving each fold an opportunity to be used as the holdout fold.

    For more on k-fold cross-validation, see the tutorial:

    Both of these model evaluation procedures are stochastic.

    Again, this does not mean that they are random; it means that small decisions made in the process involve randomness. Specifically, the choice of which rows are assigned to a given subset of the data.

    This use of randomness is a feature, not a bug.

    The use of randomness, in this case, allows the resampling to approximate an estimate of model performance that is independent of the specific data sample drawn from the domain. This approximation is biased because we only have a small sample of data to work with rather than the complete set of possible observations.

    Performance estimates provide an idea of the expected or average capability of the model when making predictions in the domain on data not seen during training. Regardless of the specific rows of data used to train or test the model, at least ideally.

    For more on the more general topic of statistical sampling, see the tutorial:

    As such, each evaluation of a deterministic machine learning algorithm, like a linear regression or a logistic regression, can give a different estimate of error or accuracy.

    What Should I Do?

    The solution in this case is much like the case for stochastic learning algorithms.

    The seed for the pseudorandom number generator can be fixed or the randomness of the procedure can be embraced.

    Unlike stochastic learning algorithms, both solutions are quite reasonable.

    If a large number of machine learning algorithms and algorithm configurations are being evaluated systematically on a predictive modeling task, it can be a good idea to fix the random seed of the evaluation procedure. Any value will do.

    The idea is that each candidate solution (each algorithm or configuration) will be evaluated in an identical manner. This ensures an apples-to-apples comparison. It also allows for the use of paired statistical hypothesis tests later, if needed, to check if differences between algorithms are statistically significant.

    Embracing the randomness can also be appropriate. This involves repeating the evaluation procedure many times and reporting a summary of the distribution of performance scores, such as the mean and standard deviation.

    Perhaps the least biased approach to repeated evaluation would be to use repeated k-fold cross-validation, such as three repeats with 10 folds (3×10), which is common, or five repeats with two folds (5×2), which is commonly used when comparing algorithms with statistical hypothesis tests.

    For a gentle introduction to using statistical hypothesis tests for comparing algoritms, see the tutorial:

    For a tutorial on comparing mean algorithm performance with a hypothesis test, see the tutorial:

    5. Differences Caused by Platform

    You can get different results when running the same algorithm on the same data on different computers.

    This can happen even if you fix the random number seed to address the stochastic nature of the learning algorithm and evaluation procedure.

    The cause in this case is the platform or development environment used to run the example, and the results are often different in minor ways, but not always.

    This includes:

    • Differences in the system architecture, e.g. CPU or GPU.
    • Differences in the operating system, e.g. MacOS or Linux.
    • Differences in the underlying math libraries, e.g. LAPACK or BLAS.
    • Differences in the Python version, e.g. 3.6 or 3.7.
    • Differences in the library version, e.g. scikit-learn 0.22 or 0.23.

    Machine learning algorithms are a type of numerical computation.

    This means that they typically involve a lot of math with floating point values. Differences in aspects, such as the architecture and operating system, can result in differences in round errors, which can compound with the number of calculations performed to give very different results.

    Additionally, differences in the version of libraries can mean the fixing of bugs and the changing of functionality that too can result in different results.

    Additionally, this also explains why you will get different results for the same algorithm on the same machine implemented by different languages, such as R and Python. Small differences in the implementation and/or differences in the underlying math libraries used will cause differences in the resulting model and predictions made by that model.

    What Should I Do?

    This does not mean that the platform itself can be treated as a hyperparameter and tuned for a predictive modeling problem.

    Instead, it means that the platform is an important factor when evaluating machine learning algorithms and should be fixed or fully described to ensure full reproducibility when moving from development to production, or in reporting performance in academic studies.

    One approach might be to use virtualization, such as docker or a virtual machine instance to ensure the environment is kept constant, if full reproducibility is critical to a project.

    Honestly, the effect is often very small in practice (at least in my limited experience) as long as major software versions are a good or close enough match.

    Further Reading

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

    Related Tutorials

    Summary

    In this tutorial, you discovered why you can expect different results when using machine learning algorithms.

    Specifically, you learned:

    • Machine learning algorithms will train different models if the training dataset is changed.
    • Stochastic machine learning algorithms use randomness during learning, ensuring a different model is trained each run.
    • Differences in the development environment, such as software versions and CPU type, can cause rounding error differences in predictions and model evaluations.

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

    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