{"id":3850,"date":"2020-09-08T19:00:21","date_gmt":"2020-09-08T19:00:21","guid":{"rendered":"https:\/\/www.aiproblog.com\/index.php\/2020\/09\/08\/tpot-for-automated-machine-learning-in-python\/"},"modified":"2020-09-08T19:00:21","modified_gmt":"2020-09-08T19:00:21","slug":"tpot-for-automated-machine-learning-in-python","status":"publish","type":"post","link":"https:\/\/www.aiproblog.com\/index.php\/2020\/09\/08\/tpot-for-automated-machine-learning-in-python\/","title":{"rendered":"TPOT for Automated Machine Learning in Python"},"content":{"rendered":"<p>Author: Jason Brownlee<\/p>\n<div>\n<p>Automated Machine Learning (AutoML) refers to techniques for automatically discovering well-performing models for predictive modeling tasks with very little user involvement.<\/p>\n<p>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.<\/p>\n<p>In this tutorial, you will discover how to use TPOT for AutoML with Scikit-Learn machine learning algorithms in Python.<\/p>\n<p>After completing this tutorial, you will know:<\/p>\n<ul>\n<li>TPOT is an open-source library for AutoML with scikit-learn data preparation and machine learning models.<\/li>\n<li>How to use TPOT to automatically discover top-performing models for classification tasks.<\/li>\n<li>How to use TPOT to automatically discover top-performing models for regression tasks.<\/li>\n<\/ul>\n<p>Let&rsquo;s get started.<\/p>\n<div id=\"attachment_10480\" style=\"width: 810px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" aria-describedby=\"caption-attachment-10480\" loading=\"lazy\" class=\"size-full wp-image-10480\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2020\/06\/TPOT-for-Automated-Machine-Learning-in-Python.jpg\" alt=\"TPOT for Automated Machine Learning in Python\" width=\"800\" height=\"536\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/06\/TPOT-for-Automated-Machine-Learning-in-Python.jpg 800w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/06\/TPOT-for-Automated-Machine-Learning-in-Python-300x201.jpg 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/06\/TPOT-for-Automated-Machine-Learning-in-Python-768x515.jpg 768w\" sizes=\"(max-width: 800px) 100vw, 800px\"><\/p>\n<p id=\"caption-attachment-10480\" class=\"wp-caption-text\">TPOT for Automated Machine Learning in Python<br \/>Photo by <a href=\"https:\/\/flickr.com\/photos\/theaudiochick\/5385120043\/\">Gwen<\/a>, some rights reserved.<\/p>\n<\/div>\n<h2>Tutorial Overview<\/h2>\n<p>This tutorial is divided into four parts; they are:<\/p>\n<ol>\n<li>TPOT for Automated Machine Learning<\/li>\n<li>Install and Use TPOT<\/li>\n<li>TPOT for Classification<\/li>\n<li>TPOT for Regression<\/li>\n<\/ol>\n<h2>TPOT for Automated Machine Learning<\/h2>\n<p><a href=\"https:\/\/epistasislab.github.io\/tpot\/\">Tree-based Pipeline Optimization Tool<\/a>, or TPOT for short, is a Python library for automated machine learning.<\/p>\n<p>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.<\/p>\n<blockquote>\n<p>&hellip; an evolutionary algorithm called the Tree-based Pipeline Optimization Tool (TPOT) that automatically designs and optimizes machine learning pipelines.<\/p>\n<\/blockquote>\n<p>&mdash; <a href=\"https:\/\/dl.acm.org\/doi\/10.1145\/2908812.2908918\">Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science<\/a>, 2016.<\/p>\n<p>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.<\/p>\n<blockquote>\n<p>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.<\/p>\n<\/blockquote>\n<p>&mdash; <a href=\"https:\/\/dl.acm.org\/doi\/10.1145\/2908812.2908918\">Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science<\/a>, 2016.<\/p>\n<p>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.<\/p>\n<div id=\"attachment_10479\" style=\"width: 1326px\" class=\"wp-caption aligncenter\"><img decoding=\"async\" aria-describedby=\"caption-attachment-10479\" loading=\"lazy\" class=\"size-full wp-image-10479\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2020\/03\/Overview-of-the-TPOT-Pipeline-Search.png\" alt=\"Overview of the TPOT Pipeline Search\" width=\"1316\" height=\"656\" srcset=\"http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/03\/Overview-of-the-TPOT-Pipeline-Search.png 1316w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/03\/Overview-of-the-TPOT-Pipeline-Search-300x150.png 300w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/03\/Overview-of-the-TPOT-Pipeline-Search-1024x510.png 1024w, http:\/\/3qeqpr26caki16dnhd19sv6by6v.wpengine.netdna-cdn.com\/wp-content\/uploads\/2020\/03\/Overview-of-the-TPOT-Pipeline-Search-768x383.png 768w\" sizes=\"(max-width: 1316px) 100vw, 1316px\"><\/p>\n<p id=\"caption-attachment-10479\" class=\"wp-caption-text\">Overview of the TPOT Pipeline Search<br \/>Taken from: Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science, 2016.<\/p>\n<\/div>\n<p>Now that we are familiar with what TPOT is, let&rsquo;s look at how we can install and use TPOT to find an effective model pipeline.<\/p>\n<h2>Install and Use TPOT<\/h2>\n<p>The first step is to install the TPOT library, which can be achieved using pip, as follows:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">pip install tpot<\/pre>\n<p>Once installed, we can import the library and print the version number to confirm it was installed successfully:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># check tpot version\r\nimport tpot\r\nprint('tpot: %s' % tpot.__version__)<\/pre>\n<p>Running the example prints the version number.<\/p>\n<p>Your version number should be the same or higher.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">tpot: 0.11.1<\/pre>\n<p>Using TPOT is straightforward.<\/p>\n<p>It involves creating an instance of the <a href=\"https:\/\/epistasislab.github.io\/tpot\/api\/\">TPOTRegressor or TPOTClassifier class<\/a>, configuring it for the search, and then exporting the model pipeline that was found to achieve the best performance on your dataset.<\/p>\n<p>Configuring the class involves two main elements.<\/p>\n<p>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.<\/p>\n<p>For example, <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.model_selection.RepeatedKFold.html\">RepeatedKFold<\/a> for regression with &lsquo;<em>neg_mean_absolute_error<\/em>&lsquo; metric for regression:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# define evaluation procedure\r\ncv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n# define search\r\nmodel = TPOTRegressor(... scoring='neg_mean_absolute_error', cv=cv)<\/pre>\n<p>Or a <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.model_selection.RepeatedStratifiedKFold.html\">RepeatedStratifiedKFold<\/a> for regression with &lsquo;<em>accuracy<\/em>&lsquo; metric for classification:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# define evaluation procedure\r\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n# define search\r\nmodel = TPOTClassifier(... scoring='accuracy', cv=cv)<\/pre>\n<p>The other element is the nature of the stochastic global search procedure.<\/p>\n<p>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.<\/p>\n<p>For example, a modest population size of 100 and 5 or 10 generations is a good starting point.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# define search\r\nmodel = TPOTClassifier(generations=5, population_size=50, ...)<\/pre>\n<p>At the end of a search, a Pipeline is found that performs the best.<\/p>\n<p>This Pipeline can be exported as code into a Python file that you can later copy-and-paste into your own project.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# export the best model\r\nmodel.export('tpot_model.py')<\/pre>\n<p>Now that we are familiar with how to use TPOT, let&rsquo;s look at some worked examples with real data.<\/p>\n<h2>TPOT for Classification<\/h2>\n<p>In this section, we will use TPOT to discover a model for the sonar dataset.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>The dataset involves predicting whether sonar returns indicate a rock or simulated mine.<\/p>\n<ul>\n<li><a href=\"https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/sonar.csv\">Sonar Dataset (sonar.csv)<\/a><\/li>\n<li><a href=\"https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/sonar.names\">Sonar Dataset Description (sonar.names)<\/a><\/li>\n<\/ul>\n<p>No need to download the dataset; we will download it automatically as part of our worked examples.<\/p>\n<p>The example below downloads the dataset and summarizes its shape.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># summarize the sonar dataset\r\nfrom pandas import read_csv\r\n# load dataset\r\nurl = 'https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/sonar.csv'\r\ndataframe = read_csv(url, header=None)\r\n# split into input and output elements\r\ndata = dataframe.values\r\nX, y = data[:, :-1], data[:, -1]\r\nprint(X.shape, y.shape)<\/pre>\n<p>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.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">(208, 60) (208,)<\/pre>\n<p>Next, let&rsquo;s use TPOT to find a good model for the sonar dataset.<\/p>\n<p>First, we can define the method for evaluating models. We will use a good practice of <a href=\"https:\/\/machinelearningmastery.com\/k-fold-cross-validation\/\">repeated stratified k-fold cross-validation<\/a> with three repeats and 10 folds.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# define model evaluation\r\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)<\/pre>\n<p>We will use a population size of 50 for five generations for the search and use all cores on the system by setting &ldquo;<em>n_jobs<\/em>&rdquo; to -1.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# define search\r\nmodel = TPOTClassifier(generations=5, population_size=50, cv=cv, scoring='accuracy', verbosity=2, random_state=1, n_jobs=-1)<\/pre>\n<p>Finally, we can start the search and ensure that the best-performing model is saved at the end of the run.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# perform the search\r\nmodel.fit(X, y)\r\n# export the best model\r\nmodel.export('tpot_sonar_best_model.py')<\/pre>\n<p>Tying this together, the complete example is listed below.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># example of tpot for the sonar classification dataset\r\nfrom pandas import read_csv\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold\r\nfrom tpot import TPOTClassifier\r\n# load dataset\r\nurl = 'https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/sonar.csv'\r\ndataframe = read_csv(url, header=None)\r\n# split into input and output elements\r\ndata = dataframe.values\r\nX, y = data[:, :-1], data[:, -1]\r\n# minimally prepare dataset\r\nX = X.astype('float32')\r\ny = LabelEncoder().fit_transform(y.astype('str'))\r\n# define model evaluation\r\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n# define search\r\nmodel = TPOTClassifier(generations=5, population_size=50, cv=cv, scoring='accuracy', verbosity=2, random_state=1, n_jobs=-1)\r\n# perform the search\r\nmodel.fit(X, y)\r\n# export the best model\r\nmodel.export('tpot_sonar_best_model.py')<\/pre>\n<p>Running the example may take a few minutes, and you will see a progress bar on the command line.<\/p>\n<p><strong>Note<\/strong>: Your <a href=\"https:\/\/machinelearningmastery.com\/different-results-each-time-in-machine-learning\/\">results may vary<\/a> 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.<\/p>\n<p>The accuracy of top-performing models will be reported along the way.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">Generation 1 - Current best internal CV score: 0.8650793650793651\r\nGeneration 2 - Current best internal CV score: 0.8650793650793651\r\nGeneration 3 - Current best internal CV score: 0.8650793650793651\r\nGeneration 4 - Current best internal CV score: 0.8650793650793651\r\nGeneration 5 - Current best internal CV score: 0.8667460317460318\r\n\r\nBest pipeline: GradientBoostingClassifier(GaussianNB(input_matrix), learning_rate=0.1, max_depth=7, max_features=0.7000000000000001, min_samples_leaf=15, min_samples_split=10, n_estimators=100, subsample=0.9000000000000001)<\/pre>\n<p>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.<\/p>\n<p>The top-performing pipeline is then saved to a file named &ldquo;<em>tpot_sonar_best_model.py<\/em>&ldquo;.<\/p>\n<p>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.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.pipeline import make_pipeline, make_union\r\nfrom tpot.builtins import StackingEstimator\r\nfrom tpot.export_utils import set_param_recursive\r\n\r\n# NOTE: Make sure that the outcome column is labeled 'target' in the data file\r\ntpot_data = pd.read_csv('PATH\/TO\/DATA\/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)\r\nfeatures = tpot_data.drop('target', axis=1)\r\ntraining_features, testing_features, training_target, testing_target = \r\n            train_test_split(features, tpot_data['target'], random_state=1)\r\n\r\n# Average CV score on the training set was: 0.8667460317460318\r\nexported_pipeline = make_pipeline(\r\n    StackingEstimator(estimator=GaussianNB()),\r\n    GradientBoostingClassifier(learning_rate=0.1, max_depth=7, max_features=0.7000000000000001, min_samples_leaf=15, min_samples_split=10, n_estimators=100, subsample=0.9000000000000001)\r\n)\r\n# Fix random state for all the steps in exported pipeline\r\nset_param_recursive(exported_pipeline.steps, 'random_state', 1)\r\n\r\nexported_pipeline.fit(training_features, training_target)\r\nresults = exported_pipeline.predict(testing_features)<\/pre>\n<p><strong>Note<\/strong>: as-is, this code does not execute, by design. It is a template that you can copy-and-paste into your project.<\/p>\n<p>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.<\/p>\n<p>We can adapt this code to fit a final model on all available data and make a prediction for new data.<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># example of fitting a final model and making a prediction on the sonar dataset\r\nfrom pandas import read_csv\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import RepeatedStratifiedKFold\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.pipeline import make_pipeline\r\nfrom tpot.builtins import StackingEstimator\r\nfrom tpot.export_utils import set_param_recursive\r\n# load dataset\r\nurl = 'https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/sonar.csv'\r\ndataframe = read_csv(url, header=None)\r\n# split into input and output elements\r\ndata = dataframe.values\r\nX, y = data[:, :-1], data[:, -1]\r\n# minimally prepare dataset\r\nX = X.astype('float32')\r\ny = LabelEncoder().fit_transform(y.astype('str'))\r\n# Average CV score on the training set was: 0.8667460317460318\r\nexported_pipeline = make_pipeline(\r\n    StackingEstimator(estimator=GaussianNB()),\r\n    GradientBoostingClassifier(learning_rate=0.1, max_depth=7, max_features=0.7000000000000001, min_samples_leaf=15, min_samples_split=10, n_estimators=100, subsample=0.9000000000000001)\r\n)\r\n# Fix random state for all the steps in exported pipeline\r\nset_param_recursive(exported_pipeline.steps, 'random_state', 1)\r\n# fit the model\r\nexported_pipeline.fit(X, y)\r\n# make a prediction on a new row of data\r\nrow = [0.0200,0.0371,0.0428,0.0207,0.0954,0.0986,0.1539,0.1601,0.3109,0.2111,0.1609,0.1582,0.2238,0.0645,0.0660,0.2273,0.3100,0.2999,0.5078,0.4797,0.5783,0.5071,0.4328,0.5550,0.6711,0.6415,0.7104,0.8080,0.6791,0.3857,0.1307,0.2604,0.5121,0.7547,0.8537,0.8507,0.6692,0.6097,0.4943,0.2744,0.0510,0.2834,0.2825,0.4256,0.2641,0.1386,0.1051,0.1343,0.0383,0.0324,0.0232,0.0027,0.0065,0.0159,0.0072,0.0167,0.0180,0.0084,0.0090,0.0032]\r\nyhat = exported_pipeline.predict([row])\r\nprint('Predicted: %.3f' % yhat[0])<\/pre>\n<p>Running the example fits the best-performing model on the dataset and makes a prediction for a single row of new data.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">Predicted: 1.000<\/pre>\n<\/p>\n<h2>TPOT for Regression<\/h2>\n<p>In this section, we will use TPOT to discover a model for the auto insurance dataset.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>The dataset involves predicting the total amount in claims (thousands of Swedish Kronor) given the number of claims for different geographical regions.<\/p>\n<ul>\n<li><a href=\"https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/auto-insurance.csv\">Auto Insurance Dataset (auto-insurance.csv)<\/a><\/li>\n<li><a href=\"https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/auto-insurance.names\">Auto Insurance Dataset Description (auto-insurance.names)<\/a><\/li>\n<\/ul>\n<p>No need to download the dataset; we will download it automatically as part of our worked examples.<\/p>\n<p>The example below downloads the dataset and summarizes its shape.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># summarize the auto insurance dataset\r\nfrom pandas import read_csv\r\n# load dataset\r\nurl = 'https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/auto-insurance.csv'\r\ndataframe = read_csv(url, header=None)\r\n# split into input and output elements\r\ndata = dataframe.values\r\nX, y = data[:, :-1], data[:, -1]\r\nprint(X.shape, y.shape)<\/pre>\n<p>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.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">(63, 1) (63,)<\/pre>\n<p>Next, we can use TPOT to find a good model for the auto insurance dataset.<\/p>\n<p>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.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# define evaluation procedure\r\ncv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)<\/pre>\n<p>We will use a population size of 50 for 5 generations for the search and use all cores on the system by setting &ldquo;<em>n_jobs<\/em>&rdquo; to -1.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# define search\r\nmodel = TPOTRegressor(generations=5, population_size=50, scoring='neg_mean_absolute_error', cv=cv, verbosity=2, random_state=1, n_jobs=-1)<\/pre>\n<p>Finally, we can start the search and ensure that the best-performing model is saved at the end of the run.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# perform the search\r\nmodel.fit(X, y)\r\n# export the best model\r\nmodel.export('tpot_insurance_best_model.py')<\/pre>\n<p>Tying this together, the complete example is listed below.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># example of tpot for the insurance regression dataset\r\nfrom pandas import read_csv\r\nfrom sklearn.model_selection import RepeatedKFold\r\nfrom tpot import TPOTRegressor\r\n# load dataset\r\nurl = 'https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/auto-insurance.csv'\r\ndataframe = read_csv(url, header=None)\r\n# split into input and output elements\r\ndata = dataframe.values\r\ndata = data.astype('float32')\r\nX, y = data[:, :-1], data[:, -1]\r\n# define evaluation procedure\r\ncv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1)\r\n# define search\r\nmodel = TPOTRegressor(generations=5, population_size=50, scoring='neg_mean_absolute_error', cv=cv, verbosity=2, random_state=1, n_jobs=-1)\r\n# perform the search\r\nmodel.fit(X, y)\r\n# export the best model\r\nmodel.export('tpot_insurance_best_model.py')<\/pre>\n<p>Running the example may take a few minutes, and you will see a progress bar on the command line.<\/p>\n<p><strong>Note<\/strong>: Your <a href=\"https:\/\/machinelearningmastery.com\/different-results-each-time-in-machine-learning\/\">results may vary<\/a> 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.<\/p>\n<p>The MAE of top-performing models will be reported along the way.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">Generation 1 - Current best internal CV score: -29.147625969129034\r\nGeneration 2 - Current best internal CV score: -29.147625969129034\r\nGeneration 3 - Current best internal CV score: -29.147625969129034\r\nGeneration 4 - Current best internal CV score: -29.147625969129034\r\nGeneration 5 - Current best internal CV score: -29.147625969129034\r\n\r\nBest pipeline: LinearSVR(input_matrix, C=1.0, dual=False, epsilon=0.0001, loss=squared_epsilon_insensitive, tol=0.001)<\/pre>\n<p>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.<\/p>\n<p>The top-performing pipeline is then saved to a file named &ldquo;<em>tpot_insurance_best_model.py<\/em>&ldquo;.<\/p>\n<p>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.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import LinearSVR\r\n\r\n# NOTE: Make sure that the outcome column is labeled 'target' in the data file\r\ntpot_data = pd.read_csv('PATH\/TO\/DATA\/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)\r\nfeatures = tpot_data.drop('target', axis=1)\r\ntraining_features, testing_features, training_target, testing_target = \r\n            train_test_split(features, tpot_data['target'], random_state=1)\r\n\r\n# Average CV score on the training set was: -29.147625969129034\r\nexported_pipeline = LinearSVR(C=1.0, dual=False, epsilon=0.0001, loss=\"squared_epsilon_insensitive\", tol=0.001)\r\n# Fix random state in exported estimator\r\nif hasattr(exported_pipeline, 'random_state'):\r\n    setattr(exported_pipeline, 'random_state', 1)\r\n\r\nexported_pipeline.fit(training_features, training_target)\r\nresults = exported_pipeline.predict(testing_features)<\/pre>\n<p><strong>Note<\/strong>: as-is, this code does not execute, by design. It is a template that you can copy-paste into your project.<\/p>\n<p>In this case, we can see that the best-performing model is a pipeline comprised of a linear support vector machine model.<\/p>\n<p>We can adapt this code to fit a final model on all available data and make a prediction for new data.<\/p>\n<p>The complete example is listed below.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># example of fitting a final model and making a prediction on the insurance dataset\r\nfrom pandas import read_csv\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.svm import LinearSVR\r\n# load dataset\r\nurl = 'https:\/\/raw.githubusercontent.com\/jbrownlee\/Datasets\/master\/auto-insurance.csv'\r\ndataframe = read_csv(url, header=None)\r\n# split into input and output elements\r\ndata = dataframe.values\r\ndata = data.astype('float32')\r\nX, y = data[:, :-1], data[:, -1]\r\n# Average CV score on the training set was: -29.147625969129034\r\nexported_pipeline = LinearSVR(C=1.0, dual=False, epsilon=0.0001, loss=\"squared_epsilon_insensitive\", tol=0.001)\r\n# Fix random state in exported estimator\r\nif hasattr(exported_pipeline, 'random_state'):\r\n    setattr(exported_pipeline, 'random_state', 1)\r\n# fit the model\r\nexported_pipeline.fit(X, y)\r\n# make a prediction on a new row of data\r\nrow = [108]\r\nyhat = exported_pipeline.predict([row])\r\nprint('Predicted: %.3f' % yhat[0])<\/pre>\n<p>Running the example fits the best-performing model on the dataset and makes a prediction for a single row of new data.<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">Predicted: 389.612<\/pre>\n<\/p>\n<h2>Further Reading<\/h2>\n<p>This section provides more resources on the topic if you are looking to go deeper.<\/p>\n<ul>\n<li><a href=\"https:\/\/dl.acm.org\/doi\/10.1145\/2908812.2908918\">Evaluation of a Tree-based Pipeline Optimization Tool for Automating Data Science<\/a>, 2016.<\/li>\n<li><a href=\"https:\/\/epistasislab.github.io\/tpot\/\">TPOT Documentation<\/a>.<\/li>\n<li><a href=\"https:\/\/github.com\/EpistasisLab\/tpot\">TPOT GitHub Project<\/a>.<\/li>\n<\/ul>\n<h2>Summary<\/h2>\n<p>In this tutorial, you discovered how to use TPOT for AutoML with Scikit-Learn machine learning algorithms in Python.<\/p>\n<p>Specifically, you learned:<\/p>\n<ul>\n<li>TPOT is an open-source library for AutoML with scikit-learn data preparation and machine learning models.<\/li>\n<li>How to use TPOT to automatically discover top-performing models for classification tasks.<\/li>\n<li>How to use TPOT to automatically discover top-performing models for regression tasks.<\/li>\n<\/ul>\n<p><strong>Do you have any questions?<\/strong><br \/>\nAsk your questions in the comments below and I will do my best to answer.<\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/tpot-for-automated-machine-learning-in-python\/\">TPOT for Automated Machine Learning in Python<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/\">Machine Learning Mastery<\/a>.<\/p>\n<\/div>\n<p><a href=\"https:\/\/machinelearningmastery.com\/tpot-for-automated-machine-learning-in-python\/\">Go to Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Author: Jason Brownlee Automated Machine Learning (AutoML) refers to techniques for automatically discovering well-performing models for predictive modeling tasks with very little user involvement. TPOT [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/www.aiproblog.com\/index.php\/2020\/09\/08\/tpot-for-automated-machine-learning-in-python\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":3851,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"footnotes":""},"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/3850"}],"collection":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/comments?post=3850"}],"version-history":[{"count":0,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/3850\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media\/3851"}],"wp:attachment":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media?parent=3850"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/categories?post=3850"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/tags?post=3850"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}