Predicting Columns in a Table - In Depth

Tip: If you are new to AutoGluon, review Predicting Columns in a Table - Quick Start to learn the basics of the AutoGluon API. To learn how to add your own custom models to the set that AutoGluon trains, tunes, and ensembles, review Adding a custom model to AutoGluon.

This tutorial describes how you can exert greater control when using AutoGluon’s fit() or predict(). Recall that to maximize predictive performance, you should first try TabularPredictor() and fit() with all default arguments. Then, consider non-default arguments for TabularPredictor(eval_metric=...), and fit(presets=...). Later, you can experiment with other arguments to fit() covered in this in-depth tutorial like hyperparameter_tune_kwargs, hyperparameters, num_stack_levels, num_bag_folds, num_bag_sets, etc.

Using the same census data table as in the Predicting Columns in a Table - Quick Start tutorial, we’ll now predict the occupation of an individual - a multiclass classification problem. Start by importing AutoGluon’s TabularPredictor and TabularDataset, and loading the data.

from autogluon.tabular import TabularDataset, TabularPredictor

import numpy as np

train_data = TabularDataset('https://autogluon.s3.amazonaws.com/datasets/Inc/train.csv')
subsample_size = 500  # subsample subset of data for faster demo, try setting this to much larger values
train_data = train_data.sample(n=subsample_size, random_state=0)
print(train_data.head())

label = 'occupation'
print("Summary of occupation column: \n", train_data['occupation'].describe())

new_data = TabularDataset('https://autogluon.s3.amazonaws.com/datasets/Inc/test.csv')
test_data = new_data[5000:].copy()  # this should be separate data in your applications
y_test = test_data[label]
test_data_nolabel = test_data.drop(columns=[label])  # delete label column
val_data = new_data[:5000].copy()

metric = 'accuracy' # we specify eval-metric just for demo (unnecessary as it's the default)
       age workclass  fnlwgt      education  education-num  6118    51   Private   39264   Some-college             10
23204   58   Private   51662           10th              6
29590   40   Private  326310   Some-college             10
18116   37   Private  222450        HS-grad              9
33964   62   Private  109190      Bachelors             13

            marital-status        occupation    relationship    race      sex  6118    Married-civ-spouse   Exec-managerial            Wife   White   Female
23204   Married-civ-spouse     Other-service            Wife   White   Female
29590   Married-civ-spouse      Craft-repair         Husband   White     Male
18116        Never-married             Sales   Not-in-family   White     Male
33964   Married-civ-spouse   Exec-managerial         Husband   White     Male

       capital-gain  capital-loss  hours-per-week  native-country   class
6118              0             0              40   United-States    >50K
23204             0             0               8   United-States   <=50K
29590             0             0              44   United-States   <=50K
18116             0          2339              40     El-Salvador   <=50K
33964         15024             0              40   United-States    >50K
Summary of occupation column:
 count                  500
unique                  15
top        Exec-managerial
freq                    77
Name: occupation, dtype: object

Specifying hyperparameters and tuning them

We first demonstrate hyperparameter-tuning and how you can provide your own validation dataset that AutoGluon internally relies on to: tune hyperparameters, early-stop iterative training, and construct model ensembles. One reason you may specify validation data is when future test data will stem from a different distribution than training data (and your specified validation data is more representative of the future data that will likely be encountered).

If you don’t have a strong reason to provide your own validation dataset, we recommend you omit the tuning_data argument. This lets AutoGluon automatically select validation data from your provided training set (it uses smart strategies such as stratified sampling). For greater control, you can specify the holdout_frac argument to tell AutoGluon what fraction of the provided training data to hold out for validation.

Caution: Since AutoGluon tunes internal knobs based on this validation data, performance estimates reported on this data may be over-optimistic. For unbiased performance estimates, you should always call predict() on a separate dataset (that was never passed to fit()), as we did in the previous Quick-Start tutorial. We also emphasize that most options specified in this tutorial are chosen to minimize runtime for the purposes of demonstration and you should select more reasonable values in order to obtain high-quality models.

fit() trains neural networks and various types of tree ensembles by default. You can specify various hyperparameter values for each type of model. For each hyperparameter, you can either specify a single fixed value, or a search space of values to consider during hyperparameter optimization. Hyperparameters which you do not specify are left at default settings chosen automatically by AutoGluon, which may be fixed values or search spaces.

import autogluon.core as ag

nn_options = {  # specifies non-default hyperparameter values for neural network models
    'num_epochs': 10,  # number of training epochs (controls training time of NN models)
    'learning_rate': ag.space.Real(1e-4, 1e-2, default=5e-4, log=True),  # learning rate used in training (real-valued hyperparameter searched on log-scale)
    'activation': ag.space.Categorical('relu', 'softrelu', 'tanh'),  # activation function used in NN (categorical hyperparameter, default = first entry)
    'dropout_prob': ag.space.Real(0.0, 0.5, default=0.1),  # dropout probability (real-valued hyperparameter)
}

gbm_options = {  # specifies non-default hyperparameter values for lightGBM gradient boosted trees
    'num_boost_round': 100,  # number of boosting rounds (controls training time of GBM models)
    'num_leaves': ag.space.Int(lower=26, upper=66, default=36),  # number of leaves in trees (integer hyperparameter)
}

hyperparameters = {  # hyperparameters of each model type
                   'GBM': gbm_options,
                   'NN_TORCH': nn_options,  # NOTE: comment this line out if you get errors on Mac OSX
                  }  # When these keys are missing from hyperparameters dict, no models of that type are trained

time_limit = 2*60  # train various models for ~2 min
num_trials = 5  # try at most 5 different hyperparameter configurations for each type of model
search_strategy = 'auto'  # to tune hyperparameters using random search routine with a local scheduler

hyperparameter_tune_kwargs = {  # HPO is not performed unless hyperparameter_tune_kwargs is specified
    'num_trials': num_trials,
    'scheduler' : 'local',
    'searcher': search_strategy,
}

predictor = TabularPredictor(label=label, eval_metric=metric).fit(
    train_data, tuning_data=val_data, time_limit=time_limit,
    hyperparameters=hyperparameters, hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
)
Fitted model: NeuralNetTorch/48b30258 ...
    0.2719   = Validation score   (accuracy)
    2.32s    = Training   runtime
    0.05s    = Validation runtime
Fitted model: NeuralNetTorch/96e9190c ...
    0.3174   = Validation score   (accuracy)
    2.95s    = Training   runtime
    0.05s    = Validation runtime
Fitted model: NeuralNetTorch/487fdf43 ...
    0.3086   = Validation score   (accuracy)
    4.35s    = Training   runtime
    0.11s    = Validation runtime
Fitted model: NeuralNetTorch/b65e7337 ...
    0.2879   = Validation score   (accuracy)
    2.95s    = Training   runtime
    0.06s    = Validation runtime
Fitted model: NeuralNetTorch/a1ef2c18 ...
    0.2987   = Validation score   (accuracy)
    2.3s     = Training   runtime
    0.03s    = Validation runtime
Fitting model: WeightedEnsemble_L2 ... Training model for up to 119.88s of the 101.58s of remaining time.
    0.3461   = Validation score   (accuracy)
    1.17s    = Training   runtime
    0.0s     = Validation runtime
AutoGluon training complete, total runtime = 20.21s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230222_232425/")

We again demonstrate how to use the trained models to predict on the test data.

y_pred = predictor.predict(test_data_nolabel)
print("Predictions:  ", list(y_pred)[:5])
perf = predictor.evaluate(test_data, auxiliary_metrics=False)
Predictions:   [' Exec-managerial', ' Exec-managerial', ' Craft-repair', ' Other-service', ' Other-service']
Evaluation: accuracy on test data: 0.3252254141329419
Evaluations on test data:
{
    "accuracy": 0.3252254141329419
}

Use the following to view a summary of what happened during fit(). Now this command will show details of the hyperparameter-tuning process for each type of model:

results = predictor.fit_summary(show_plot=True)
* Summary of fit() *
Estimated performance of each model:
                      model  score_val  pred_time_val   fit_time  pred_time_val_marginal  fit_time_marginal  stack_level  can_infer  fit_order
0       WeightedEnsemble_L2   0.346114       0.541186  15.692666                0.001239           1.168711            2       True         11
1               LightGBM/T3   0.323765       0.022287   0.306765                0.022287           0.306765            1       True          3
2   NeuralNetTorch/96e9190c   0.317408       0.052687   2.953824                0.052687           2.953824            1       True          7
3               LightGBM/T5   0.310847       0.026893   0.416983                0.026893           0.416983            1       True          5
4   NeuralNetTorch/487fdf43   0.308591       0.107765   4.347329                0.107765           4.347329            1       True          8
5               LightGBM/T1   0.303260       0.059854   0.676473                0.059854           0.676473            1       True          1
6   NeuralNetTorch/a1ef2c18   0.298749       0.034524   2.298599                0.034524           2.298599            1       True         10
7               LightGBM/T2   0.289932       0.046737   0.621757                0.046737           0.621757            1       True          2
8   NeuralNetTorch/b65e7337   0.287882       0.060662   2.946708                0.060662           2.946708            1       True          9
9               LightGBM/T4   0.280910       0.141204   0.586306                0.141204           0.586306            1       True          4
10  NeuralNetTorch/48b30258   0.271888       0.047996   2.315919                0.047996           2.315919            1       True          6
Number of models trained: 11
Types of models trained:
{'WeightedEnsembleModel', 'LGBModel', 'TabularNeuralNetTorchModel'}
Bagging used: False
Multi-layer stack-ensembling used: False
Feature Metadata (Processed):
(raw dtype, special dtypes):
('category', [])  : 6 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
('int', ['bool']) : 2 | ['sex', 'class']
* End of fit() summary *
/home/ci/autogluon/core/src/autogluon/core/utils/plots.py:138: UserWarning: AutoGluon summary plots cannot be created because bokeh is not installed. To see plots, please do: "pip install bokeh==2.0.1"
  warnings.warn('AutoGluon summary plots cannot be created because bokeh is not installed. To see plots, please do: "pip install bokeh==2.0.1"')

In the above example, the predictive performance may be poor because we specified very little training to ensure quick runtimes. You can call fit() multiple times while modifying the above settings to better understand how these choices affect performance outcomes. For example: you can comment out the train_data.head command or increase subsample_size to train using a larger dataset, increase the num_epochs and num_boost_round hyperparameters, and increase the time_limit (which you should do for all code in these tutorials). To see more detailed output during the execution of fit(), you can also pass in the argument: verbosity = 3.

Model ensembling with stacking/bagging

Beyond hyperparameter-tuning with a correctly-specified evaluation metric, two other methods to boost predictive performance are bagging and stack-ensembling. You’ll often see performance improve if you specify num_bag_folds = 5-10, num_stack_levels = 1-3 in the call to fit(), but this will increase training times and memory/disk usage.

predictor = TabularPredictor(label=label, eval_metric=metric).fit(train_data,
    num_bag_folds=5, num_bag_sets=1, num_stack_levels=1,
    hyperparameters = {'NN_TORCH': {'num_epochs': 2}, 'GBM': {'num_boost_round': 20}},  # last  argument is just for quick demo here, omit it in real applications
)
No path specified. Models will be saved in: "AutogluonModels/ag-20230222_232447/"
Beginning AutoGluon training ...
AutoGluon will save models to "AutogluonModels/ag-20230222_232447/"
AutoGluon Version:  0.7.0b20230222
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Train Data Rows:    500
Train Data Columns: 14
Label Column: occupation
Preprocessing data ...
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == object).
    First 10 (of 15) unique label values:  [' Exec-managerial', ' Other-service', ' Craft-repair', ' Sales', ' Prof-specialty', ' Protective-serv', ' ?', ' Adm-clerical', ' Machine-op-inspct', ' Tech-support']
    If 'multiclass' is not the correct problem_type, please manually specify the problem_type parameter during predictor init (You may specify problem_type as one of: ['binary', 'multiclass', 'regression'])
Warning: Some classes in the training set have fewer than 10 examples. AutoGluon will only keep 12 out of 15 classes for training and will not try to predict the rare classes. To keep more classes, increase the number of datapoints from these rare classes in the training data or reduce label_count_threshold.
Fraction of data from classes with at least 10 examples that will be kept for training models: 0.978
Train Data Class Count: 12
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
    Available Memory:                    30963.95 MB
    Train Data (Original)  Memory Usage: 0.28 MB (0.0% of available memory)
    Inferring data type of each feature based on column values. Set feature_metadata_in to manually specify special dtypes of the features.
    Stage 1 Generators:
            Fitting AsTypeFeatureGenerator...
                    Note: Converting 2 features to boolean dtype as they only contain 2 unique values.
    Stage 2 Generators:
            Fitting FillNaFeatureGenerator...
    Stage 3 Generators:
            Fitting IdentityFeatureGenerator...
            Fitting CategoryFeatureGenerator...
                    Fitting CategoryMemoryMinimizeFeatureGenerator...
    Stage 4 Generators:
            Fitting DropUniqueFeatureGenerator...
    Types of features in original data (raw dtype, special dtypes):
            ('int', [])    : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('object', []) : 8 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
    Types of features in processed data (raw dtype, special dtypes):
            ('category', [])  : 6 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
            ('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('int', ['bool']) : 2 | ['sex', 'class']
    0.1s = Fit runtime
    14 features in original data used to generate 14 features in processed data.
    Train Data (Processed) Memory Usage: 0.03 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.09s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
    To change this, specify the eval_metric parameter of Predictor()
AutoGluon will fit 2 stack levels (L1 to L2) ...
Fitting 2 L1 models ...
Fitting model: LightGBM_BAG_L1 ...
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3067   = Validation score   (accuracy)
    1.08s    = Training   runtime
    0.03s    = Validation runtime
Fitting model: NeuralNetTorch_BAG_L1 ...
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.1575   = Validation score   (accuracy)
    2.45s    = Training   runtime
    0.06s    = Validation runtime
Fitting model: WeightedEnsemble_L2 ...
    0.3067   = Validation score   (accuracy)
    0.1s     = Training   runtime
    0.0s     = Validation runtime
Fitting 2 L2 models ...
Fitting model: LightGBM_BAG_L2 ...
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.2924   = Validation score   (accuracy)
    0.89s    = Training   runtime
    0.03s    = Validation runtime
Fitting model: NeuralNetTorch_BAG_L2 ...
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.1677   = Validation score   (accuracy)
    1.84s    = Training   runtime
    0.11s    = Validation runtime
Fitting model: WeightedEnsemble_L3 ...
    0.2924   = Validation score   (accuracy)
    0.1s     = Training   runtime
    0.0s     = Validation runtime
AutoGluon training complete, total runtime = 19.18s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230222_232447/")

You should not provide tuning_data when stacking/bagging, and instead provide all your available data as train_data (which AutoGluon will split in more intellgent ways). num_bag_sets controls how many times the k-fold bagging process is repeated to further reduce variance (increasing this may further boost accuracy but will substantially increase training times, inference latency, and memory/disk usage). Rather than manually searching for good bagging/stacking values yourself, AutoGluon will automatically select good values for you if you specify auto_stack instead:

save_path = 'agModels-predictOccupation'  # folder where to store trained models

predictor = TabularPredictor(label=label, eval_metric=metric, path=save_path).fit(
    train_data, auto_stack=True,
    time_limit=30, hyperparameters={'NN_TORCH': {'num_epochs': 2}, 'GBM': {'num_boost_round': 20}}  # last 2 arguments are for quick demo, omit them in real applications
)
Stack configuration (auto_stack=True): num_stack_levels=0, num_bag_folds=5, num_bag_sets=20
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "agModels-predictOccupation/"
AutoGluon Version:  0.7.0b20230222
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Train Data Rows:    500
Train Data Columns: 14
Label Column: occupation
Preprocessing data ...
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == object).
    First 10 (of 15) unique label values:  [' Exec-managerial', ' Other-service', ' Craft-repair', ' Sales', ' Prof-specialty', ' Protective-serv', ' ?', ' Adm-clerical', ' Machine-op-inspct', ' Tech-support']
    If 'multiclass' is not the correct problem_type, please manually specify the problem_type parameter during predictor init (You may specify problem_type as one of: ['binary', 'multiclass', 'regression'])
Warning: Some classes in the training set have fewer than 10 examples. AutoGluon will only keep 12 out of 15 classes for training and will not try to predict the rare classes. To keep more classes, increase the number of datapoints from these rare classes in the training data or reduce label_count_threshold.
Fraction of data from classes with at least 10 examples that will be kept for training models: 0.978
Train Data Class Count: 12
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
    Available Memory:                    29818.71 MB
    Train Data (Original)  Memory Usage: 0.28 MB (0.0% of available memory)
    Inferring data type of each feature based on column values. Set feature_metadata_in to manually specify special dtypes of the features.
    Stage 1 Generators:
            Fitting AsTypeFeatureGenerator...
                    Note: Converting 2 features to boolean dtype as they only contain 2 unique values.
    Stage 2 Generators:
            Fitting FillNaFeatureGenerator...
    Stage 3 Generators:
            Fitting IdentityFeatureGenerator...
            Fitting CategoryFeatureGenerator...
                    Fitting CategoryMemoryMinimizeFeatureGenerator...
    Stage 4 Generators:
            Fitting DropUniqueFeatureGenerator...
    Types of features in original data (raw dtype, special dtypes):
            ('int', [])    : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('object', []) : 8 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
    Types of features in processed data (raw dtype, special dtypes):
            ('category', [])  : 6 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
            ('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('int', ['bool']) : 2 | ['sex', 'class']
    0.1s = Fit runtime
    14 features in original data used to generate 14 features in processed data.
    Train Data (Processed) Memory Usage: 0.03 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.09s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
    To change this, specify the eval_metric parameter of Predictor()
Fitting 2 L1 models ...
Fitting model: LightGBM_BAG_L1 ... Training model for up to 29.91s of the 29.91s of remaining time.
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3067   = Validation score   (accuracy)
    0.59s    = Training   runtime
    0.03s    = Validation runtime
Fitting model: NeuralNetTorch_BAG_L1 ... Training model for up to 26.13s of the 26.13s of remaining time.
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.1575   = Validation score   (accuracy)
    1.81s    = Training   runtime
    0.06s    = Validation runtime
Repeating k-fold bagging: 2/20
Fitting model: LightGBM_BAG_L1 ... Training model for up to 21.12s of the 21.11s of remaining time.
    Fitting 5 child models (S2F1 - S2F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3149   = Validation score   (accuracy)
    1.25s    = Training   runtime
    0.06s    = Validation runtime
Fitting model: NeuralNetTorch_BAG_L1 ... Training model for up to 17.29s of the 17.29s of remaining time.
    Fitting 5 child models (S2F1 - S2F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.1595   = Validation score   (accuracy)
    3.66s    = Training   runtime
    0.11s    = Validation runtime
Repeating k-fold bagging: 3/20
Fitting model: LightGBM_BAG_L1 ... Training model for up to 12.37s of the 12.37s of remaining time.
    Fitting 5 child models (S3F1 - S3F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3292   = Validation score   (accuracy)
    1.93s    = Training   runtime
    0.08s    = Validation runtime
Fitting model: NeuralNetTorch_BAG_L1 ... Training model for up to 8.51s of the 8.51s of remaining time.
    Fitting 5 child models (S3F1 - S3F5) | Fitting with ParallelLocalFoldFittingStrategy
    Time limit exceeded... Skipping NeuralNetTorch_BAG_L1.
Completed 3/20 k-fold bagging repeats ...
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.91s of the 3.97s of remaining time.
2023-02-22 23:25:32,341     ERROR worker.py:400 -- Unhandled error (suppress with 'RAY_IGNORE_UNHANDLED_ERRORS=1'): The worker died unexpectedly while executing this task. Check python-core-worker-.log files for more information.
2023-02-22 23:25:32,344     ERROR worker.py:400 -- Unhandled error (suppress with 'RAY_IGNORE_UNHANDLED_ERRORS=1'): The worker died unexpectedly while executing this task. Check python-core-worker-.log files for more information.
2023-02-22 23:25:32,345     ERROR worker.py:400 -- Unhandled error (suppress with 'RAY_IGNORE_UNHANDLED_ERRORS=1'): The worker died unexpectedly while executing this task. Check python-core-worker-.log files for more information.
2023-02-22 23:25:32,905     ERROR worker.py:400 -- Unhandled error (suppress with 'RAY_IGNORE_UNHANDLED_ERRORS=1'): The worker died unexpectedly while executing this task. Check python-core-worker-.log files for more information.
    0.3292   = Validation score   (accuracy)
    0.0s     = Training   runtime
    0.0s     = Validation runtime
AutoGluon training complete, total runtime = 26.71s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("agModels-predictOccupation/")

Often stacking/bagging will produce superior accuracy than hyperparameter-tuning, but you may try combining both techniques (note: specifying presets='best_quality' in fit() simply sets auto_stack=True).

Prediction options (inference)

Even if you’ve started a new Python session since last calling fit(), you can still load a previously trained predictor from disk:

predictor = TabularPredictor.load(save_path)  # `predictor.path` is another way to get the relative path needed to later load predictor.

Above save_path is the same folder previously passed to TabularPredictor, in which all the trained models have been saved. You can train easily models on one machine and deploy them on another. Simply copy the save_path folder to the new machine and specify its new path in TabularPredictor.load().

To find out the required feature columns to make predictions, call predictor.features():

predictor.features()
['age',
 'workclass',
 'fnlwgt',
 'education',
 'education-num',
 'marital-status',
 'relationship',
 'race',
 'sex',
 'capital-gain',
 'capital-loss',
 'hours-per-week',
 'native-country',
 'class']

We can make a prediction on an individual example rather than a full dataset:

datapoint = test_data_nolabel.iloc[[0]]  # Note: .iloc[0] won't work because it returns pandas Series instead of DataFrame
print(datapoint)
predictor.predict(datapoint)
      age workclass  fnlwgt      education  education-num marital-status  5000   49   Private  259087   Some-college             10       Divorced

        relationship    race      sex  capital-gain  capital-loss  5000   Not-in-family   White   Female             0             0

      hours-per-week  native-country   class
5000              40   United-States   <=50K
5000     Exec-managerial
Name: occupation, dtype: object

To output predicted class probabilities instead of predicted classes, you can use:

predictor.predict_proba(datapoint)  # returns a DataFrame that shows which probability corresponds to which class
? Adm-clerical Armed-Forces Craft-repair Exec-managerial Farming-fishing Handlers-cleaners Machine-op-inspct Other-service Priv-house-serv Prof-specialty Protective-serv Sales Tech-support Transport-moving
5000 0.036423 0.163815 0.0 0.13473 0.234789 0.014535 0.034552 0.048815 0.058644 0.0 0.088821 0.0 0.106273 0.01641 0.062193

By default, predict() and predict_proba() will utilize the model that AutoGluon thinks is most accurate, which is usually an ensemble of many individual models. Here’s how to see which model this is:

predictor.get_model_best()
'WeightedEnsemble_L2'

We can instead specify a particular model to use for predictions (e.g. to reduce inference latency). Note that a ‘model’ in AutoGluon may refer to, for example, a single Neural Network, a bagged ensemble of many Neural Network copies trained on different training/validation splits, a weighted ensemble that aggregates the predictions of many other models, or a stacker model that operates on predictions output by other models. This is akin to viewing a Random Forest as one ‘model’ when it is in fact an ensemble of many decision trees.

Before deciding which model to use, let’s evaluate all of the models AutoGluon has previously trained on our test data:

predictor.leaderboard(test_data, silent=True)
model score_test score_val pred_time_test pred_time_val fit_time pred_time_test_marginal pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 LightGBM_BAG_L1 0.283078 0.329243 0.260877 0.082747 1.933482 0.260877 0.082747 1.933482 1 True 1
1 WeightedEnsemble_L2 0.283078 0.329243 0.263294 0.083263 1.937100 0.002418 0.000517 0.003618 2 True 3
2 NeuralNetTorch_BAG_L1 0.188299 0.159509 0.303772 0.114130 3.658016 0.303772 0.114130 3.658016 1 True 2

The leaderboard shows each model’s predictive performance on the test data (score_test) and validation data (score_val), as well as the time required to: produce predictions for the test data (pred_time_val), produce predictions on the validation data (pred_time_val), and train only this model (fit_time). Below, we show that a leaderboard can be produced without new data (just uses the data previously reserved for validation inside fit) and can display extra information about each model:

predictor.leaderboard(extra_info=True, silent=True)
model score_val pred_time_val fit_time pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order num_features ... hyperparameters hyperparameters_fit ag_args_fit features compile_time child_hyperparameters child_hyperparameters_fit child_ag_args_fit ancestors descendants
0 LightGBM_BAG_L1 0.329243 0.082747 1.933482 0.082747 1.933482 1 True 1 14 ... {'use_orig_features': True, 'max_base_models':... {} {'max_memory_usage_ratio': 1.0, 'max_time_limi... [age, education, capital-gain, hours-per-week,... None {'learning_rate': 0.05, 'num_boost_round': 20} {'num_boost_round': 13} {'max_memory_usage_ratio': 1.0, 'max_time_limi... [] [WeightedEnsemble_L2]
1 WeightedEnsemble_L2 0.329243 0.083263 1.937100 0.000517 0.003618 2 True 3 12 ... {'use_orig_features': False, 'max_base_models'... {} {'max_memory_usage_ratio': 1.0, 'max_time_limi... [LightGBM_BAG_L1_2, LightGBM_BAG_L1_4, LightGB... None {'ensemble_size': 100} {'ensemble_size': 1} {'max_memory_usage_ratio': 1.0, 'max_time_limi... [LightGBM_BAG_L1] []
2 NeuralNetTorch_BAG_L1 0.159509 0.114130 3.658016 0.114130 3.658016 1 True 2 14 ... {'use_orig_features': True, 'max_base_models':... {} {'max_memory_usage_ratio': 1.0, 'max_time_limi... [age, education, capital-gain, hours-per-week,... None {'num_epochs': 2, 'epochs_wo_improve': 20, 'ac... {'batch_size': 32, 'num_epochs': 2} {'max_memory_usage_ratio': 1.0, 'max_time_limi... [] []

3 rows × 30 columns

The expanded leaderboard shows properties like how many features are used by each model (num_features), which other models are ancestors whose predictions are required inputs for each model (ancestors), and how much memory each model and all its ancestors would occupy if simultaneously persisted (memory_size_w_ancestors). See the leaderboard documentation for full details.

To show scores for other metrics, you can specify the extra_metrics argument when passing in test_data:

predictor.leaderboard(test_data, extra_metrics=['accuracy', 'balanced_accuracy', 'log_loss'], silent=True)
model score_test accuracy balanced_accuracy log_loss score_val pred_time_test pred_time_val fit_time pred_time_test_marginal pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 LightGBM_BAG_L1 0.283078 0.283078 0.178895 -11.753647 0.329243 0.264905 0.082747 1.933482 0.264905 0.082747 1.933482 1 True 1
1 WeightedEnsemble_L2 0.283078 0.283078 0.178895 -11.753647 0.329243 0.266810 0.083263 1.937100 0.001905 0.000517 0.003618 2 True 3
2 NeuralNetTorch_BAG_L1 0.188299 0.188299 0.096338 -11.749236 0.159509 0.313527 0.114130 3.658016 0.313527 0.114130 3.658016 1 True 2

Notice that log_loss scores are negative. This is because metrics in AutoGluon are always shown in higher_is_better form. This means that metrics such as log_loss and root_mean_squared_error will have their signs FLIPPED, and values will be negative. This is necessary to avoid the user needing to know the metric to understand if higher is better when looking at leaderboard.

One additional caveat: It is possible that log_loss values can be -inf when computed via extra_metrics. This is because the models were not optimized with log_loss in mind during training and may have prediction probabilities giving a class 0 (particularly common with K-Nearest-Neighbors models). Because log_loss gives infinite error when the correct class was given 0 probability, this results in a score of -inf. It is therefore recommended that log_loss should not be used as a secondary metric to determine model quality. Either use log_loss as the eval_metric or avoid it altogether.

Here’s how to specify a particular model to use for prediction instead of AutoGluon’s default model-choice:

i = 0  # index of model to use
model_to_use = predictor.get_model_names()[i]
model_pred = predictor.predict(datapoint, model=model_to_use)
print("Prediction from %s model: %s" % (model_to_use, model_pred.iloc[0]))
Prediction from LightGBM_BAG_L1 model:  Exec-managerial

We can easily access various information about the trained predictor or a particular model:

all_models = predictor.get_model_names()
model_to_use = all_models[i]
specific_model = predictor._trainer.load_model(model_to_use)

# Objects defined below are dicts of various information (not printed here as they are quite large):
model_info = specific_model.get_info()
predictor_information = predictor.info()

The predictor also remembers what metric predictions should be evaluated with, which can be done with ground truth labels as follows:

y_pred_proba = predictor.predict_proba(test_data_nolabel)
perf = predictor.evaluate_predictions(y_true=y_test, y_pred=y_pred_proba)
Evaluation: accuracy on test data: 0.28307821346194173
Evaluations on test data:
{
    "accuracy": 0.28307821346194173,
    "balanced_accuracy": 0.17889516678234868,
    "mcc": 0.19219227485377302
}

Since the label columns remains in the test_data DataFrame, we can instead use the shorthand:

perf = predictor.evaluate(test_data)
Evaluation: accuracy on test data: 0.28307821346194173
Evaluations on test data:
{
    "accuracy": 0.28307821346194173,
    "balanced_accuracy": 0.17889516678234868,
    "mcc": 0.19219227485377302
}

Interpretability (feature importance)

To better understand our trained predictor, we can estimate the overall importance of each feature:

predictor.feature_importance(test_data)
Computing feature importance via permutation shuffling for 14 features using 4637 rows with 5 shuffle sets...
    20.46s  = Expected runtime (4.09s per shuffle set)
    12.57s  = Actual runtime (Completed 5 of 5 shuffle sets)
importance stddev p_value n p99_high p99_low
education-num 0.069355 0.002806 3.208365e-07 5 0.075133 0.063578
workclass 0.037265 0.002002 9.962103e-07 5 0.041388 0.033143
sex 0.036058 0.001175 1.352490e-07 5 0.038478 0.033638
hours-per-week 0.032219 0.005558 1.022038e-04 5 0.043664 0.020774
age 0.020617 0.004761 3.181865e-04 5 0.030419 0.010815
class 0.007850 0.001908 3.879995e-04 5 0.011779 0.003921
fnlwgt 0.002027 0.003740 1.461170e-01 5 0.009728 -0.005674
marital-status 0.001941 0.000341 1.097557e-04 5 0.002643 0.001239
relationship 0.001596 0.000947 9.831950e-03 5 0.003547 -0.000355
education 0.001035 0.000798 2.206371e-02 5 0.002679 -0.000608
capital-loss 0.000992 0.000472 4.672000e-03 5 0.001965 0.000019
race 0.000000 0.000000 5.000000e-01 5 0.000000 0.000000
native-country 0.000000 0.000000 5.000000e-01 5 0.000000 0.000000
capital-gain -0.001121 0.000933 9.726385e-01 5 0.000799 -0.003042

Computed via permutation-shuffling, these feature importance scores quantify the drop in predictive performance (of the already trained predictor) when one column’s values are randomly shuffled across rows. The top features in this list contribute most to AutoGluon’s accuracy (for predicting when/if a patient will be readmitted to the hospital). Features with non-positive importance score hardly contribute to the predictor’s accuracy, or may even be actively harmful to include in the data (consider removing these features from your data and calling fit again). These scores facilitate interpretability of the predictor’s global behavior (which features it relies on for all predictions). To get local explanations regarding which features influence a particular prediction, check out the example notebooks for explaining particular AutoGluon predictions using Shapely values.

Before making judgement on if AutoGluon is more or less interpretable than another solution, we recommend reading The Mythos of Model Interpretability by Zachary Lipton, which covers why often-claimed interpretable models such as trees and linear models are rarely meaningfully more interpretable than more advanced models.

Accelerating inference

We describe multiple ways to reduce the time it takes for AutoGluon to produce predictions.

Before providing code examples, it is important to understand that there are several ways to accelerate inference in AutoGluon. The table below lists the options in order of priority.

Opti miza tion

Inference Speedup

Cost

Notes

refi t_fu ll

At least 8x+, up to 160x (requires bagging)

-Qua lity , +Fit Time

Only provides speedup with bagging enabled.

pers ist_ mode ls

Up to 10x in online-inference

++Me mory Usag e

If memory is not sufficient to persist model, speedup is not gained. Speedup is most effective in online-inference and is not relevant in batch inference.

infe r_li mit

Configurable, ~up to 50x

-Qua lity (Rel ativ e to spee dup)

If bagging is enabled, always use refit_full if using infer_limit.

dist ill

~Equals combined speedup of refit_full and infer_limit set to extreme values

–Qua lity , ++Fi tTim e

Not compatible with refit_full and infer_limit.

feat ure prun ing

Typically at most 1.5x. More if willing to lower quality significantly.

-Qua lity ?, ++Fi tTim e

Dependent on the existence of unimportant features in data. Call predictor.feature_importance(tes t_data) to gauge which features could be removed.

use fast er hard ware

Usually at most 3x. Depends on hardware (ignoring GPU).

+Har dwar e

As an example, an EC2 c6i.2xlarge is ~1.6x faster than an m5.2xlarge for a similar price. Laptops in particular might be slow compared to cloud instances.

manu al hype rpar amet ers adju stme nt

Usually at most 2x assuming infer_limit is already specified.

—Qua lity ?, +++U serM LExp erti se

Can be very complicated and is not recommended. Potential ways to get speedups this way is to reduce the number of trees in LightGBM, XGBoost, CatBoost, RandomForest, and ExtraTrees.

manu al data prep roce ssin g

Usually at most 1.2x assuming all other optimizations are specified and setting is online-inference.

User MLEx pert ise, ++++ User Code

Only relevant for online-inference. This is not recommended as AutoGluon’s default preprocessing is highly optimized.

If bagging is enabled (num_bag_folds>0 or num_stack_levels>0 or using ‘best_quality’ preset), the order of inference optimizations should be:
1. refit_full
2. persist_models
3. infer_limit
If bagging is not enabled (num_bag_folds=0, num_stack_levels=0), the order of inference optimizations should be:
1. persist_models
2. infer_limit

If following these recommendations does not lead to a sufficiently fast model, you may consider the more advanced options in the table.

Keeping models in memory

By default, AutoGluon loads models into memory one at a time and only when they are needed for prediction. This strategy is robust for large stacked/bagged ensembles, but leads to slower prediction times. If you plan to repeatedly make predictions (e.g. on new datapoints one at a time rather than one large test dataset), you can first specify that all models required for inference should be loaded into memory as follows:

predictor.persist_models()

num_test = 20
preds = np.array(['']*num_test, dtype='object')
for i in range(num_test):
    datapoint = test_data_nolabel.iloc[[i]]
    pred_numpy = predictor.predict(datapoint, as_pandas=False)
    preds[i] = pred_numpy[0]

perf = predictor.evaluate_predictions(y_test[:num_test], preds, auxiliary_metrics=True)
print("Predictions: ", preds)

predictor.unpersist_models()  # free memory by clearing models, future predict() calls will load models from disk
Persisting 2 models in memory. Models will require 0.01% of memory.
Evaluation: accuracy on test data: 0.25
Evaluations on test data:
{
    "accuracy": 0.25,
    "balanced_accuracy": 0.3208333333333336,
    "mcc": 0.1275983604226418
}
Unpersisted 2 models: ['LightGBM_BAG_L1', 'WeightedEnsemble_L2']
Predictions:  [' Exec-managerial' ' Craft-repair' ' Craft-repair' ' Adm-clerical' ' ?'
 ' Exec-managerial' ' Exec-managerial' ' Sales' ' Exec-managerial'
 ' Adm-clerical' ' Other-service' ' Exec-managerial' ' Exec-managerial'
 ' Exec-managerial' ' Adm-clerical' ' ?' ' Craft-repair' ' Craft-repair'
 ' Exec-managerial' ' Craft-repair']
['LightGBM_BAG_L1', 'WeightedEnsemble_L2']

You can alternatively specify a particular model to persist via the models argument of persist_models(), or simply set models='all' to simultaneously load every single model that was trained during fit.

Inference speed as a fit constraint

If you know your latency constraint prior to fitting the predictor, you can specify it explicitly as a fit argument. AutoGluon will then automatically train models in a fashion that attempts to satisfy the constraint.

This constraint has two components: infer_limit and infer_limit_batch_size:
- infer_limit is the time in seconds to predict 1 row of data. For example, infer_limit=0.05 means 50 ms per row of data, or 20 rows / second throughput.
- infer_limit_batch_size is the amount of rows passed at once to predict when calculating per-row speed. This is very important because infer_limit_batch_size=1 (online-inference) is highly suboptimal as various operations have a fixed cost overhead regardless of data size. If you can pass your test data in bulk, you should specify infer_limit_batch_size=10000.
# At most 0.05 ms per row (20000 rows per second throughput)
infer_limit = 0.00005
# adhere to infer_limit with batches of size 10000 (batch-inference, easier to satisfy infer_limit)
infer_limit_batch_size = 10000
# adhere to infer_limit with batches of size 1 (online-inference, much harder to satisfy infer_limit)
# infer_limit_batch_size = 1  # Note that infer_limit<0.02 when infer_limit_batch_size=1 can be difficult to satisfy.
predictor_infer_limit = TabularPredictor(label=label, eval_metric=metric).fit(
    train_data=train_data,
    time_limit=30,
    infer_limit=infer_limit,
    infer_limit_batch_size=infer_limit_batch_size,
)

# NOTE: If bagging was enabled, it is important to call refit_full at this stage.
#  infer_limit assumes that the user will call refit_full after fit.
# predictor_infer_limit.refit_full()

# NOTE: To align with inference speed calculated during fit, models must be persisted.
predictor_infer_limit.persist_models()
# Below is an optimized version that only persists the minimum required models for prediction.
# predictor_infer_limit.persist_models('best')

predictor_infer_limit.leaderboard(silent=True)
No path specified. Models will be saved in: "AutogluonModels/ag-20230222_232600/"
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230222_232600/"
AutoGluon Version:  0.7.0b20230222
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Train Data Rows:    500
Train Data Columns: 14
Label Column: occupation
Preprocessing data ...
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == object).
    First 10 (of 15) unique label values:  [' Exec-managerial', ' Other-service', ' Craft-repair', ' Sales', ' Prof-specialty', ' Protective-serv', ' ?', ' Adm-clerical', ' Machine-op-inspct', ' Tech-support']
    If 'multiclass' is not the correct problem_type, please manually specify the problem_type parameter during predictor init (You may specify problem_type as one of: ['binary', 'multiclass', 'regression'])
Warning: Some classes in the training set have fewer than 10 examples. AutoGluon will only keep 12 out of 15 classes for training and will not try to predict the rare classes. To keep more classes, increase the number of datapoints from these rare classes in the training data or reduce label_count_threshold.
Fraction of data from classes with at least 10 examples that will be kept for training models: 0.978
Train Data Class Count: 12
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
    Available Memory:                    31003.94 MB
    Train Data (Original)  Memory Usage: 0.28 MB (0.0% of available memory)
    Inferring data type of each feature based on column values. Set feature_metadata_in to manually specify special dtypes of the features.
    Stage 1 Generators:
            Fitting AsTypeFeatureGenerator...
                    Note: Converting 2 features to boolean dtype as they only contain 2 unique values.
    Stage 2 Generators:
            Fitting FillNaFeatureGenerator...
    Stage 3 Generators:
            Fitting IdentityFeatureGenerator...
            Fitting CategoryFeatureGenerator...
                    Fitting CategoryMemoryMinimizeFeatureGenerator...
    Stage 4 Generators:
            Fitting DropUniqueFeatureGenerator...
    Types of features in original data (raw dtype, special dtypes):
            ('int', [])    : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('object', []) : 8 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
    Types of features in processed data (raw dtype, special dtypes):
            ('category', [])  : 6 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
            ('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('int', ['bool']) : 2 | ['sex', 'class']
    0.1s = Fit runtime
    14 features in original data used to generate 14 features in processed data.
    Train Data (Processed) Memory Usage: 0.03 MB (0.0% of available memory)
    1.652μs = Feature Preprocessing Time (1 row | 10000 batch size)
            Feature Preprocessing requires 3.3% of the overall inference constraint (0.05ms)
            0.048ms inference time budget remaining for models...
Data preprocessing and feature engineering runtime = 0.27s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
    To change this, specify the eval_metric parameter of Predictor()
Automatically generating train/validation split with holdout_frac=0.2, Train Rows: 391, Val Rows: 98
Fitting 13 L1 models ...
Fitting model: KNeighborsUnif ... Training model for up to 29.73s of the 29.73s of remaining time.
    0.1633   = Validation score   (accuracy)
    0.63s    = Training   runtime
    0.01s    = Validation runtime
    2.655μs  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    2.655μs  = Validation runtime (1 row | 10000 batch size)
Fitting model: KNeighborsDist ... Training model for up to 29.09s of the 29.09s of remaining time.
    0.1224   = Validation score   (accuracy)
    0.63s    = Training   runtime
    0.01s    = Validation runtime
    2.563μs  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    2.563μs  = Validation runtime (1 row | 10000 batch size)
Fitting model: NeuralNetFastAI ... Training model for up to 28.45s of the 28.44s of remaining time.
No improvement since epoch 6: early stopping
    0.3265   = Validation score   (accuracy)
    2.09s    = Training   runtime
    0.01s    = Validation runtime
    0.014ms  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    0.014ms  = Validation runtime (1 row | 10000 batch size)
Fitting model: LightGBMXT ... Training model for up to 26.33s of the 26.33s of remaining time.
    0.3571   = Validation score   (accuracy)
    0.75s    = Training   runtime
    0.01s    = Validation runtime
    0.012ms  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    0.012ms  = Validation runtime (1 row | 10000 batch size)
Fitting model: LightGBM ... Training model for up to 25.56s of the 25.55s of remaining time.
    0.3673   = Validation score   (accuracy)
    0.93s    = Training   runtime
    0.0s     = Validation runtime
    5.204μs  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    5.204μs  = Validation runtime (1 row | 10000 batch size)
Fitting model: RandomForestGini ... Training model for up to 24.61s of the 24.61s of remaining time.
    0.3061   = Validation score   (accuracy)
    0.96s    = Training   runtime
    0.08s    = Validation runtime
    0.014ms  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    0.014ms  = Validation runtime (1 row | 10000 batch size)
Fitting model: RandomForestEntr ... Training model for up to 23.53s of the 23.53s of remaining time.
    0.2959   = Validation score   (accuracy)
    0.9s     = Training   runtime
    0.08s    = Validation runtime
    0.014ms  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    0.014ms  = Validation runtime (1 row | 10000 batch size)
Fitting model: CatBoost ... Training model for up to 22.52s of the 22.51s of remaining time.
    0.3469   = Validation score   (accuracy)
    16.11s   = Training   runtime
    0.01s    = Validation runtime
    3.754μs  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    3.754μs  = Validation runtime (1 row | 10000 batch size)
Fitting model: ExtraTreesGini ... Training model for up to 6.39s of the 6.39s of remaining time.
    0.2653   = Validation score   (accuracy)
    0.86s    = Training   runtime
    0.07s    = Validation runtime
    0.014ms  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    0.014ms  = Validation runtime (1 row | 10000 batch size)
Fitting model: ExtraTreesEntr ... Training model for up to 5.42s of the 5.42s of remaining time.
    0.2857   = Validation score   (accuracy)
    0.88s    = Training   runtime
    0.07s    = Validation runtime
    0.015ms  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    0.015ms  = Validation runtime (1 row | 10000 batch size)
Fitting model: XGBoost ... Training model for up to 4.43s of the 4.43s of remaining time.
    0.398    = Validation score   (accuracy)
    0.82s    = Training   runtime
    0.0s     = Validation runtime
    3.588μs  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    3.588μs  = Validation runtime (1 row | 10000 batch size)
Fitting model: NeuralNetTorch ... Training model for up to 3.56s of the 3.56s of remaining time.
    0.3469   = Validation score   (accuracy)
    2.57s    = Training   runtime
    0.01s    = Validation runtime
    4.562μs  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    4.562μs  = Validation runtime (1 row | 10000 batch size)
Fitting model: LightGBMLarge ... Training model for up to 0.98s of the 0.98s of remaining time.
    Ran out of time, early stopping on iteration 79. Best iteration is:
    [5]     valid_set's multi_error: 0.734694
    0.2653   = Validation score   (accuracy)
    1.03s    = Training   runtime
    0.0s     = Validation runtime
    2.161μs  = Validation runtime (1 row | 10000 batch size | MARGINAL)
    2.161μs  = Validation runtime (1 row | 10000 batch size)
Removing 7/13 base models to satisfy inference constraint (constraint=0.046ms) ...
    0.109ms -> 0.106ms      (KNeighborsDist)
    0.106ms -> 0.103ms      (KNeighborsUnif)
    0.103ms -> 0.089ms      (ExtraTreesGini)
    0.089ms -> 0.087ms      (LightGBMLarge)
    0.087ms -> 0.072ms      (ExtraTreesEntr)
    0.072ms -> 0.058ms      (RandomForestEntr)
    0.058ms -> 0.044ms      (RandomForestGini)
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.73s of the -0.08s of remaining time.
    0.4184   = Validation score   (accuracy)
    0.18s    = Training   runtime
    0.0s     = Validation runtime
    0.23μs   = Validation runtime (1 row | 10000 batch size | MARGINAL)
    8.379μs  = Validation runtime (1 row | 10000 batch size)
AutoGluon training complete, total runtime = 30.29s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230222_232600/")
Persisting 3 models in memory. Models will require 0.02% of memory.
model score_val pred_time_val fit_time pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 WeightedEnsemble_L2 0.418367 0.015273 3.566303 0.000521 0.182040 2 True 14
1 XGBoost 0.397959 0.004712 0.817672 0.004712 0.817672 1 True 11
2 LightGBM 0.367347 0.004662 0.933984 0.004662 0.933984 1 True 5
3 LightGBMXT 0.357143 0.005747 0.752799 0.005747 0.752799 1 True 4
4 CatBoost 0.346939 0.005358 16.111912 0.005358 16.111912 1 True 8
5 NeuralNetTorch 0.346939 0.010040 2.566591 0.010040 2.566591 1 True 12
6 NeuralNetFastAI 0.326531 0.010206 2.094437 0.010206 2.094437 1 True 3
7 RandomForestGini 0.306122 0.075016 0.960979 0.075016 0.960979 1 True 6
8 RandomForestEntr 0.295918 0.077382 0.904692 0.077382 0.904692 1 True 7
9 ExtraTreesEntr 0.285714 0.071791 0.884460 0.071791 0.884460 1 True 10
10 LightGBMLarge 0.265306 0.004139 1.029088 0.004139 1.029088 1 True 13
11 ExtraTreesGini 0.265306 0.073031 0.859953 0.073031 0.859953 1 True 9
12 KNeighborsUnif 0.163265 0.005753 0.633229 0.005753 0.633229 1 True 1
13 KNeighborsDist 0.122449 0.006141 0.630841 0.006141 0.630841 1 True 2

Now we can test the inference speed of the final model and check if it satisfies the inference constraints.

test_data_batch = test_data.sample(infer_limit_batch_size, replace=True, ignore_index=True)

import time
time_start = time.time()
predictor_infer_limit.predict(test_data_batch)
time_end = time.time()

infer_time_per_row = (time_end - time_start) / len(test_data_batch)
rows_per_second = 1 / infer_time_per_row
infer_time_per_row_ratio = infer_time_per_row / infer_limit
is_constraint_satisfied = infer_time_per_row_ratio <= 1

print(f'Model is able to predict {round(rows_per_second, 1)} rows per second. (User-specified Throughput = {1 / infer_limit})')
print(f'Model uses {round(infer_time_per_row_ratio * 100, 1)}% of infer_limit time per row.')
print(f'Model satisfies inference constraint: {is_constraint_satisfied}')
Model is able to predict 95222.5 rows per second. (User-specified Throughput = 20000.0)
Model uses 21.0% of infer_limit time per row.
Model satisfies inference constraint: True

Using smaller ensemble or faster model for prediction

Without having to retrain any models, one can construct alternative ensembles that aggregate individual models’ predictions with different weighting schemes. These ensembles become smaller (and hence faster for prediction) if they assign nonzero weight to less models. You can produce a wide variety of ensembles with different accuracy-speed tradeoffs like this:

additional_ensembles = predictor.fit_weighted_ensemble(expand_pareto_frontier=True)
print("Alternative ensembles you can use for prediction:", additional_ensembles)

predictor.leaderboard(only_pareto_frontier=True, silent=True)
Fitting model: WeightedEnsemble_L2Best ...
    0.3333   = Validation score   (accuracy)
    0.1s     = Training   runtime
    0.0s     = Validation runtime
Alternative ensembles you can use for prediction: ['WeightedEnsemble_L2Best']
model score_val pred_time_val fit_time pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 WeightedEnsemble_L2Best 0.333333 0.197372 5.691186 0.000495 0.099688 2 True 4
1 LightGBM_BAG_L1 0.329243 0.082747 1.933482 0.082747 1.933482 1 True 1

The resulting leaderboard will contain the most accurate model for a given inference-latency. You can select whichever model exhibits acceptable latency from the leaderboard and use it for prediction.

model_for_prediction = additional_ensembles[0]
predictions = predictor.predict(test_data, model=model_for_prediction)
predictor.delete_models(models_to_delete=additional_ensembles, dry_run=False)  # delete these extra models so they don't affect rest of tutorial
Deleting model WeightedEnsemble_L2Best. All files under agModels-predictOccupation/models/WeightedEnsemble_L2Best/ will be removed.

Collapsing bagged ensembles via refit_full

For an ensemble predictor trained with bagging (as done above), recall there are ~10 bagged copies of each individual model trained on different train/validation folds. We can collapse this bag of ~10 models into a single model that’s fit to the full dataset, which can greatly reduce its memory/latency requirements (but may also reduce accuracy). Below we refit such a model for each original model but you can alternatively do this for just a particular model by specifying the model argument of refit_full().

refit_model_map = predictor.refit_full()
print("Name of each refit-full model corresponding to a previous bagged ensemble:")
print(refit_model_map)
predictor.leaderboard(test_data, silent=True)
Refitting models via predictor.refit_full using all of the data (combined train and validation)...
    Models trained in this way will have the suffix "_FULL" and have NaN validation score.
    This process is not bound by time_limit, but should take less time than the original predictor.fit call.
    To learn more, refer to the .refit_full method docstring which explains how "_FULL" models differ from normal models.
Fitting 1 L1 models ...
Fitting model: LightGBM_BAG_L1_FULL ...
    0.19s    = Training   runtime
Fitting 1 L1 models ...
Fitting model: NeuralNetTorch_BAG_L1_FULL ...
    0.15s    = Training   runtime
Fitting model: WeightedEnsemble_L2_FULL | Skipping fit via cloning parent ...
    0.0s     = Training   runtime
Updated best model to "LightGBM_BAG_L1_FULL" (Previously "LightGBM_BAG_L1"). AutoGluon will default to using "LightGBM_BAG_L1_FULL" for predict() and predict_proba().
Refit complete, total runtime = 0.44s
Name of each refit-full model corresponding to a previous bagged ensemble:
{'LightGBM_BAG_L1': 'LightGBM_BAG_L1_FULL', 'NeuralNetTorch_BAG_L1': 'NeuralNetTorch_BAG_L1_FULL', 'WeightedEnsemble_L2': 'WeightedEnsemble_L2_FULL'}
model score_test score_val pred_time_test pred_time_val fit_time pred_time_test_marginal pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 LightGBM_BAG_L1 0.283078 0.329243 0.245712 0.082747 1.933482 0.245712 0.082747 1.933482 1 True 1
1 WeightedEnsemble_L2 0.283078 0.329243 0.247924 0.083263 1.937100 0.002213 0.000517 0.003618 2 True 3
2 LightGBM_BAG_L1_FULL 0.273433 NaN 0.019007 NaN 0.186129 0.019007 NaN 0.186129 1 True 4
3 WeightedEnsemble_L2_FULL 0.273433 NaN 0.021243 NaN 0.189747 0.002236 NaN 0.003618 2 True 6
4 NeuralNetTorch_BAG_L1 0.188299 0.159509 0.333816 0.114130 3.658016 0.333816 0.114130 3.658016 1 True 2
5 NeuralNetTorch_BAG_L1_FULL 0.142168 NaN 0.032293 NaN 0.150118 0.032293 NaN 0.150118 1 True 5

This adds the refit-full models to the leaderboard and we can opt to use any of them for prediction just like any other model. Note pred_time_test and pred_time_val list the time taken to produce predictions with each model (in seconds) on the test/validation data. Since the refit-full models were trained using all of the data, there is no internal validation score (score_val) available for them. You can also call refit_full() with non-bagged models to refit the same models to your full dataset (there won’t be memory/latency gains in this case but test accuracy may improve).

Model distillation

While computationally-favorable, single individual models will usually have lower accuracy than weighted/stacked/bagged ensembles. Model Distillation offers one way to retain the computational benefits of a single model, while enjoying some of the accuracy-boost that comes with ensembling. The idea is to train the individual model (which we can call the student) to mimic the predictions of the full stack ensemble (the teacher). Like refit_full(), the distill() function will produce additional models we can opt to use for prediction.

student_models = predictor.distill(time_limit=30)  # specify much longer time limit in real applications
print(student_models)
preds_student = predictor.predict(test_data_nolabel, model=student_models[0])
print(f"predictions from {student_models[0]}:", list(preds_student)[:5])
predictor.leaderboard(test_data)
Distilling with teacher='LightGBM_BAG_L1_FULL', teacher_preds=soft, augment_method=spunge ...
SPUNGE: Augmenting training data with 1955 synthetic samples for distillation...
Distilling with each of these student models: ['LightGBM_DSTL', 'NeuralNetMXNet_DSTL', 'RandomForestMSE_DSTL', 'CatBoost_DSTL', 'NeuralNetTorch_DSTL']
Fitting 5 L1 models ...
Fitting model: LightGBM_DSTL ... Training model for up to 30.0s of the 30.0s of remaining time.
    Note: model has different eval_metric than default.
    -1.8047  = Validation score   (-soft_log_loss)
    7.25s    = Training   runtime
    0.03s    = Validation runtime
Fitting model: NeuralNetMXNet_DSTL ... Training model for up to 22.32s of the 22.32s of remaining time.
    Warning: Exception caused NeuralNetMXNet_DSTL to fail during training (ImportError)... Skipping this model.
            Unable to import dependency mxnet. A quick tip is to install via pip install mxnet --upgrade, or pip install mxnet_cu101 --upgrade
Fitting model: RandomForestMSE_DSTL ... Training model for up to 22.31s of the 22.3s of remaining time.
    Note: model has different eval_metric than default.
    -1.9263  = Validation score   (-soft_log_loss)
    0.89s    = Training   runtime
    0.06s    = Validation runtime
Fitting model: CatBoost_DSTL ... Training model for up to 21.24s of the 21.24s of remaining time.
/home/ci/opt/venv/lib/python3.8/site-packages/catboost/core.py:2266: UserWarning: Can't optimze method "evaluate" because self argument is used
  _check_train_params(params)
    Ran out of time, early stopping on iteration 80.
    Note: model has different eval_metric than default.
    -2.0062  = Validation score   (-soft_log_loss)
    20.93s   = Training   runtime
    0.0s     = Validation runtime
Fitting model: NeuralNetTorch_DSTL ... Training model for up to 0.3s of the 0.3s of remaining time.
/home/ci/opt/venv/lib/python3.8/site-packages/torch/nn/functional.py:2916: UserWarning: reduction: 'mean' divides the total loss by both the batch size and the support size.'batchmean' divides only by the batch size, and aligns with the KL div math definition.'mean' will be changed to behave the same as 'batchmean' in the next major release.
  warnings.warn(
    Ran out of time, stopping training early. (Stopping on epoch 2)
    Note: model has different eval_metric than default.
    -2.2737  = Validation score   (-soft_log_loss)
    0.3s     = Training   runtime
    0.01s    = Validation runtime
Completed 1/20 k-fold bagging repeats ...
Distilling with each of these student models: ['WeightedEnsemble_L2_DSTL']
Fitting model: WeightedEnsemble_L2_DSTL ... Training model for up to 30.0s of the -0.03s of remaining time.
    Note: model has different eval_metric than default.
    -1.8047  = Validation score   (-soft_log_loss)
    0.07s    = Training   runtime
    0.0s     = Validation runtime
Distilled model leaderboard:
                      model  score_val  pred_time_val   fit_time  pred_time_val_marginal  fit_time_marginal  stack_level  can_infer  fit_order
0             LightGBM_DSTL   0.377551       0.029010   7.249847                0.029010           7.249847            1       True          7
1  WeightedEnsemble_L2_DSTL   0.377551       0.029504   7.318262                0.000494           0.068416            2       True         11
2      RandomForestMSE_DSTL   0.357143       0.061562   0.893585                0.061562           0.893585            1       True          8
3             CatBoost_DSTL   0.326531       0.004758  20.929353                0.004758          20.929353            1       True          9
4       NeuralNetTorch_DSTL   0.153061       0.010328   0.298579                0.010328           0.298579            1       True         10
['LightGBM_DSTL', 'RandomForestMSE_DSTL', 'CatBoost_DSTL', 'NeuralNetTorch_DSTL', 'WeightedEnsemble_L2_DSTL']
predictions from LightGBM_DSTL: [' Exec-managerial', ' Exec-managerial', ' Craft-repair', ' Sales', ' Craft-repair']
                         model  score_test  score_val  pred_time_test  pred_time_val   fit_time  pred_time_test_marginal  pred_time_val_marginal  fit_time_marginal  stack_level  can_infer  fit_order
0                CatBoost_DSTL    0.329629   0.326531        0.022768       0.004758  20.929353                 0.022768                0.004758          20.929353            1       True          9
1         RandomForestMSE_DSTL    0.294821   0.357143        0.197440       0.061562   0.893585                 0.197440                0.061562           0.893585            1       True          8
2              LightGBM_BAG_L1    0.283078   0.329243        0.254132       0.082747   1.933482                 0.254132                0.082747           1.933482            1       True          1
3          WeightedEnsemble_L2    0.283078   0.329243        0.256527       0.083263   1.937100                 0.002395                0.000517           0.003618            2       True          3
4                LightGBM_DSTL    0.279723   0.377551        1.289583       0.029010   7.249847                 1.289583                0.029010           7.249847            1       True          7
5     WeightedEnsemble_L2_DSTL    0.279723   0.377551        1.292298       0.029504   7.318262                 0.002715                0.000494           0.068416            2       True         11
6         LightGBM_BAG_L1_FULL    0.273433        NaN        0.020258            NaN   0.186129                 0.020258                     NaN           0.186129            1       True          4
7     WeightedEnsemble_L2_FULL    0.273433        NaN        0.022694            NaN   0.189747                 0.002436                     NaN           0.003618            2       True          6
8        NeuralNetTorch_BAG_L1    0.188299   0.159509        0.324736       0.114130   3.658016                 0.324736                0.114130           3.658016            1       True          2
9   NeuralNetTorch_BAG_L1_FULL    0.142168        NaN        0.034678            NaN   0.150118                 0.034678                     NaN           0.150118            1       True          5
10         NeuralNetTorch_DSTL    0.141539   0.153061        0.035982       0.010328   0.298579                 0.035982                0.010328           0.298579            1       True         10
model score_test score_val pred_time_test pred_time_val fit_time pred_time_test_marginal pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 CatBoost_DSTL 0.329629 0.326531 0.022768 0.004758 20.929353 0.022768 0.004758 20.929353 1 True 9
1 RandomForestMSE_DSTL 0.294821 0.357143 0.197440 0.061562 0.893585 0.197440 0.061562 0.893585 1 True 8
2 LightGBM_BAG_L1 0.283078 0.329243 0.254132 0.082747 1.933482 0.254132 0.082747 1.933482 1 True 1
3 WeightedEnsemble_L2 0.283078 0.329243 0.256527 0.083263 1.937100 0.002395 0.000517 0.003618 2 True 3
4 LightGBM_DSTL 0.279723 0.377551 1.289583 0.029010 7.249847 1.289583 0.029010 7.249847 1 True 7
5 WeightedEnsemble_L2_DSTL 0.279723 0.377551 1.292298 0.029504 7.318262 0.002715 0.000494 0.068416 2 True 11
6 LightGBM_BAG_L1_FULL 0.273433 NaN 0.020258 NaN 0.186129 0.020258 NaN 0.186129 1 True 4
7 WeightedEnsemble_L2_FULL 0.273433 NaN 0.022694 NaN 0.189747 0.002436 NaN 0.003618 2 True 6
8 NeuralNetTorch_BAG_L1 0.188299 0.159509 0.324736 0.114130 3.658016 0.324736 0.114130 3.658016 1 True 2
9 NeuralNetTorch_BAG_L1_FULL 0.142168 NaN 0.034678 NaN 0.150118 0.034678 NaN 0.150118 1 True 5
10 NeuralNetTorch_DSTL 0.141539 0.153061 0.035982 0.010328 0.298579 0.035982 0.010328 0.298579 1 True 10

Faster presets or hyperparameters

Instead of trying to speed up a cumbersome trained model at prediction time, if you know inference latency or memory will be an issue at the outset, then you can adjust the training process accordingly to ensure fit() does not produce unwieldy models.

One option is to specify more lightweight presets:

presets = ['good_quality', 'optimize_for_deployment']
predictor_light = TabularPredictor(label=label, eval_metric=metric).fit(train_data, presets=presets, time_limit=30)
No path specified. Models will be saved in: "AutogluonModels/ag-20230222_232711/"
Presets specified: ['good_quality', 'optimize_for_deployment']
Stack configuration (auto_stack=True): num_stack_levels=0, num_bag_folds=5, num_bag_sets=20
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230222_232711/"
AutoGluon Version:  0.7.0b20230222
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Train Data Rows:    500
Train Data Columns: 14
Label Column: occupation
Preprocessing data ...
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == object).
    First 10 (of 15) unique label values:  [' Exec-managerial', ' Other-service', ' Craft-repair', ' Sales', ' Prof-specialty', ' Protective-serv', ' ?', ' Adm-clerical', ' Machine-op-inspct', ' Tech-support']
    If 'multiclass' is not the correct problem_type, please manually specify the problem_type parameter during predictor init (You may specify problem_type as one of: ['binary', 'multiclass', 'regression'])
Warning: Some classes in the training set have fewer than 10 examples. AutoGluon will only keep 12 out of 15 classes for training and will not try to predict the rare classes. To keep more classes, increase the number of datapoints from these rare classes in the training data or reduce label_count_threshold.
Fraction of data from classes with at least 10 examples that will be kept for training models: 0.978
Train Data Class Count: 12
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
    Available Memory:                    30507.48 MB
    Train Data (Original)  Memory Usage: 0.28 MB (0.0% of available memory)
    Inferring data type of each feature based on column values. Set feature_metadata_in to manually specify special dtypes of the features.
    Stage 1 Generators:
            Fitting AsTypeFeatureGenerator...
                    Note: Converting 2 features to boolean dtype as they only contain 2 unique values.
    Stage 2 Generators:
            Fitting FillNaFeatureGenerator...
    Stage 3 Generators:
            Fitting IdentityFeatureGenerator...
            Fitting CategoryFeatureGenerator...
                    Fitting CategoryMemoryMinimizeFeatureGenerator...
    Stage 4 Generators:
            Fitting DropUniqueFeatureGenerator...
    Types of features in original data (raw dtype, special dtypes):
            ('int', [])    : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('object', []) : 8 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
    Types of features in processed data (raw dtype, special dtypes):
            ('category', [])  : 6 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
            ('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('int', ['bool']) : 2 | ['sex', 'class']
    0.1s = Fit runtime
    14 features in original data used to generate 14 features in processed data.
    Train Data (Processed) Memory Usage: 0.03 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.09s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
    To change this, specify the eval_metric parameter of Predictor()
Fitting 11 L1 models ...
Fitting model: NeuralNetFastAI_BAG_L1 ... Training model for up to 29.91s of the 29.91s of remaining time.
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3129   = Validation score   (accuracy)
    2.8s     = Training   runtime
    0.07s    = Validation runtime
Fitting model: LightGBMXT_BAG_L1 ... Training model for up to 24.67s of the 24.67s of remaining time.
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3497   = Validation score   (accuracy)
    1.29s    = Training   runtime
    0.07s    = Validation runtime
Fitting model: LightGBM_BAG_L1 ... Training model for up to 20.56s of the 20.56s of remaining time.
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3395   = Validation score   (accuracy)
    1.4s     = Training   runtime
    0.03s    = Validation runtime
Fitting model: RandomForestGini_BAG_L1 ... Training model for up to 16.63s of the 16.63s of remaining time.
    0.3292   = Validation score   (accuracy)
    0.72s    = Training   runtime
    0.15s    = Validation runtime
Fitting model: RandomForestEntr_BAG_L1 ... Training model for up to 15.73s of the 15.73s of remaining time.
    0.2843   = Validation score   (accuracy)
    0.65s    = Training   runtime
    0.12s    = Validation runtime
Fitting model: CatBoost_BAG_L1 ... Training model for up to 14.92s of the 14.92s of remaining time.
    Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
    0.3292   = Validation score   (accuracy)
    12.38s   = Training   runtime
    0.03s    = Validation runtime
Fitting model: ExtraTreesGini_BAG_L1 ... Training model for up to 0.15s of the 0.14s of remaining time.
    Warning: Reducing model 'n_estimators' from 300 -> 49 due to low time. Expected time usage reduced from 0.9s -> 0.1s...
    0.2965   = Validation score   (accuracy)
    0.12s    = Training   runtime
    0.02s    = Validation runtime
Completed 1/20 k-fold bagging repeats ...
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.91s of the -0.03s of remaining time.
    0.3497   = Validation score   (accuracy)
    0.24s    = Training   runtime
    0.0s     = Validation runtime
AutoGluon training complete, total runtime = 30.29s ... Best model: "WeightedEnsemble_L2"
Automatically performing refit_full as a post-fit operation (due to .fit(..., refit_full=True)
Refitting models via predictor.refit_full using all of the data (combined train and validation)...
    Models trained in this way will have the suffix "_FULL" and have NaN validation score.
    This process is not bound by time_limit, but should take less time than the original predictor.fit call.
    To learn more, refer to the .refit_full method docstring which explains how "_FULL" models differ from normal models.
Fitting 1 L1 models ...
Fitting model: LightGBMXT_BAG_L1_FULL ...
    0.53s    = Training   runtime
Refit complete, total runtime = 0.61s
Deleting model NeuralNetFastAI_BAG_L1. All files under AutogluonModels/ag-20230222_232711/models/NeuralNetFastAI_BAG_L1/ will be removed.
Deleting model LightGBMXT_BAG_L1. All files under AutogluonModels/ag-20230222_232711/models/LightGBMXT_BAG_L1/ will be removed.
Deleting model LightGBM_BAG_L1. All files under AutogluonModels/ag-20230222_232711/models/LightGBM_BAG_L1/ will be removed.
Deleting model RandomForestGini_BAG_L1. All files under AutogluonModels/ag-20230222_232711/models/RandomForestGini_BAG_L1/ will be removed.
Deleting model RandomForestEntr_BAG_L1. All files under AutogluonModels/ag-20230222_232711/models/RandomForestEntr_BAG_L1/ will be removed.
Deleting model CatBoost_BAG_L1. All files under AutogluonModels/ag-20230222_232711/models/CatBoost_BAG_L1/ will be removed.
Deleting model ExtraTreesGini_BAG_L1. All files under AutogluonModels/ag-20230222_232711/models/ExtraTreesGini_BAG_L1/ will be removed.
Deleting model WeightedEnsemble_L2. All files under AutogluonModels/ag-20230222_232711/models/WeightedEnsemble_L2/ will be removed.
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230222_232711/")

Another option is to specify more lightweight hyperparameters:

predictor_light = TabularPredictor(label=label, eval_metric=metric).fit(train_data, hyperparameters='very_light', time_limit=30)
No path specified. Models will be saved in: "AutogluonModels/ag-20230222_232741/"
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230222_232741/"
AutoGluon Version:  0.7.0b20230222
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Train Data Rows:    500
Train Data Columns: 14
Label Column: occupation
Preprocessing data ...
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == object).
    First 10 (of 15) unique label values:  [' Exec-managerial', ' Other-service', ' Craft-repair', ' Sales', ' Prof-specialty', ' Protective-serv', ' ?', ' Adm-clerical', ' Machine-op-inspct', ' Tech-support']
    If 'multiclass' is not the correct problem_type, please manually specify the problem_type parameter during predictor init (You may specify problem_type as one of: ['binary', 'multiclass', 'regression'])
Warning: Some classes in the training set have fewer than 10 examples. AutoGluon will only keep 12 out of 15 classes for training and will not try to predict the rare classes. To keep more classes, increase the number of datapoints from these rare classes in the training data or reduce label_count_threshold.
Fraction of data from classes with at least 10 examples that will be kept for training models: 0.978
Train Data Class Count: 12
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
    Available Memory:                    30233.36 MB
    Train Data (Original)  Memory Usage: 0.28 MB (0.0% of available memory)
    Inferring data type of each feature based on column values. Set feature_metadata_in to manually specify special dtypes of the features.
    Stage 1 Generators:
            Fitting AsTypeFeatureGenerator...
                    Note: Converting 2 features to boolean dtype as they only contain 2 unique values.
    Stage 2 Generators:
            Fitting FillNaFeatureGenerator...
    Stage 3 Generators:
            Fitting IdentityFeatureGenerator...
            Fitting CategoryFeatureGenerator...
                    Fitting CategoryMemoryMinimizeFeatureGenerator...
    Stage 4 Generators:
            Fitting DropUniqueFeatureGenerator...
    Types of features in original data (raw dtype, special dtypes):
            ('int', [])    : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('object', []) : 8 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
    Types of features in processed data (raw dtype, special dtypes):
            ('category', [])  : 6 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
            ('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('int', ['bool']) : 2 | ['sex', 'class']
    0.1s = Fit runtime
    14 features in original data used to generate 14 features in processed data.
    Train Data (Processed) Memory Usage: 0.03 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.12s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
    To change this, specify the eval_metric parameter of Predictor()
Automatically generating train/validation split with holdout_frac=0.2, Train Rows: 391, Val Rows: 98
Fitting 7 L1 models ...
Fitting model: NeuralNetFastAI ... Training model for up to 29.88s of the 29.88s of remaining time.
No improvement since epoch 6: early stopping
    0.3265   = Validation score   (accuracy)
    0.52s    = Training   runtime
    0.01s    = Validation runtime
Fitting model: LightGBMXT ... Training model for up to 29.34s of the 29.34s of remaining time.
    0.3571   = Validation score   (accuracy)
    0.67s    = Training   runtime
    0.01s    = Validation runtime
Fitting model: LightGBM ... Training model for up to 28.65s of the 28.65s of remaining time.
    0.3673   = Validation score   (accuracy)
    0.97s    = Training   runtime
    0.01s    = Validation runtime
Fitting model: CatBoost ... Training model for up to 27.66s of the 27.66s of remaining time.
    0.3469   = Validation score   (accuracy)
    16.45s   = Training   runtime
    0.01s    = Validation runtime
Fitting model: XGBoost ... Training model for up to 11.2s of the 11.2s of remaining time.
    0.398    = Validation score   (accuracy)
    0.8s     = Training   runtime
    0.0s     = Validation runtime
Fitting model: NeuralNetTorch ... Training model for up to 10.34s of the 10.34s of remaining time.
    0.3469   = Validation score   (accuracy)
    2.68s    = Training   runtime
    0.01s    = Validation runtime
Fitting model: LightGBMLarge ... Training model for up to 7.65s of the 7.65s of remaining time.
    0.2653   = Validation score   (accuracy)
    2.34s    = Training   runtime
    0.0s     = Validation runtime
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.88s of the 5.27s of remaining time.
    0.4184   = Validation score   (accuracy)
    0.18s    = Training   runtime
    0.0s     = Validation runtime
AutoGluon training complete, total runtime = 24.93s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230222_232741/")

Here you can set hyperparameters to either ‘light’, ‘very_light’, or ‘toy’ to obtain progressively smaller (but less accurate) models and predictors. Advanced users may instead try manually specifying particular models’ hyperparameters in order to make them faster/smaller.

Finally, you may also exclude specific unwieldy models from being trained at all. Below we exclude models that tend to be slower (K Nearest Neighbors, Neural Network, models with custom larger-than-default hyperparameters):

excluded_model_types = ['KNN', 'NN_TORCH', 'custom']
predictor_light = TabularPredictor(label=label, eval_metric=metric).fit(train_data, excluded_model_types=excluded_model_types, time_limit=30)
No path specified. Models will be saved in: "AutogluonModels/ag-20230222_232806/"
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230222_232806/"
AutoGluon Version:  0.7.0b20230222
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Train Data Rows:    500
Train Data Columns: 14
Label Column: occupation
Preprocessing data ...
AutoGluon infers your prediction problem is: 'multiclass' (because dtype of label-column == object).
    First 10 (of 15) unique label values:  [' Exec-managerial', ' Other-service', ' Craft-repair', ' Sales', ' Prof-specialty', ' Protective-serv', ' ?', ' Adm-clerical', ' Machine-op-inspct', ' Tech-support']
    If 'multiclass' is not the correct problem_type, please manually specify the problem_type parameter during predictor init (You may specify problem_type as one of: ['binary', 'multiclass', 'regression'])
Warning: Some classes in the training set have fewer than 10 examples. AutoGluon will only keep 12 out of 15 classes for training and will not try to predict the rare classes. To keep more classes, increase the number of datapoints from these rare classes in the training data or reduce label_count_threshold.
Fraction of data from classes with at least 10 examples that will be kept for training models: 0.978
Train Data Class Count: 12
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
    Available Memory:                    30401.63 MB
    Train Data (Original)  Memory Usage: 0.28 MB (0.0% of available memory)
    Inferring data type of each feature based on column values. Set feature_metadata_in to manually specify special dtypes of the features.
    Stage 1 Generators:
            Fitting AsTypeFeatureGenerator...
                    Note: Converting 2 features to boolean dtype as they only contain 2 unique values.
    Stage 2 Generators:
            Fitting FillNaFeatureGenerator...
    Stage 3 Generators:
            Fitting IdentityFeatureGenerator...
            Fitting CategoryFeatureGenerator...
                    Fitting CategoryMemoryMinimizeFeatureGenerator...
    Stage 4 Generators:
            Fitting DropUniqueFeatureGenerator...
    Types of features in original data (raw dtype, special dtypes):
            ('int', [])    : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('object', []) : 8 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
    Types of features in processed data (raw dtype, special dtypes):
            ('category', [])  : 6 | ['workclass', 'education', 'marital-status', 'relationship', 'race', ...]
            ('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
            ('int', ['bool']) : 2 | ['sex', 'class']
    0.1s = Fit runtime
    14 features in original data used to generate 14 features in processed data.
    Train Data (Processed) Memory Usage: 0.03 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.08s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
    To change this, specify the eval_metric parameter of Predictor()
Automatically generating train/validation split with holdout_frac=0.2, Train Rows: 391, Val Rows: 98
Excluded Model Types: ['KNN', 'NN_TORCH', 'custom']
    Found 'NN_TORCH' model in hyperparameters, but 'NN_TORCH' is present in excluded_model_types and will be removed.
    Found 'KNN' model in hyperparameters, but 'KNN' is present in excluded_model_types and will be removed.
    Found 'KNN' model in hyperparameters, but 'KNN' is present in excluded_model_types and will be removed.
Fitting 10 L1 models ...
Fitting model: NeuralNetFastAI ... Training model for up to 29.92s of the 29.91s of remaining time.
No improvement since epoch 6: early stopping
    0.3265   = Validation score   (accuracy)
    0.48s    = Training   runtime
    0.01s    = Validation runtime
Fitting model: LightGBMXT ... Training model for up to 29.42s of the 29.42s of remaining time.
    0.3571   = Validation score   (accuracy)
    0.66s    = Training   runtime
    0.01s    = Validation runtime
Fitting model: LightGBM ... Training model for up to 28.74s of the 28.73s of remaining time.
    0.3673   = Validation score   (accuracy)
    0.91s    = Training   runtime
    0.0s     = Validation runtime
Fitting model: RandomForestGini ... Training model for up to 27.81s of the 27.81s of remaining time.
    0.3061   = Validation score   (accuracy)
    0.71s    = Training   runtime
    0.08s    = Validation runtime
Fitting model: RandomForestEntr ... Training model for up to 26.99s of the 26.99s of remaining time.
    0.2959   = Validation score   (accuracy)
    0.7s     = Training   runtime
    0.08s    = Validation runtime
Fitting model: CatBoost ... Training model for up to 26.18s of the 26.18s of remaining time.
    0.3469   = Validation score   (accuracy)
    16.27s   = Training   runtime
    0.01s    = Validation runtime
Fitting model: ExtraTreesGini ... Training model for up to 9.9s of the 9.9s of remaining time.
    0.2653   = Validation score   (accuracy)
    0.64s    = Training   runtime
    0.08s    = Validation runtime
Fitting model: ExtraTreesEntr ... Training model for up to 9.16s of the 9.16s of remaining time.
    0.2857   = Validation score   (accuracy)
    0.66s    = Training   runtime
    0.08s    = Validation runtime
Fitting model: XGBoost ... Training model for up to 8.39s of the 8.39s of remaining time.
    0.398    = Validation score   (accuracy)
    0.78s    = Training   runtime
    0.0s     = Validation runtime
Fitting model: LightGBMLarge ... Training model for up to 7.56s of the 7.56s of remaining time.
    0.2653   = Validation score   (accuracy)
    2.48s    = Training   runtime
    0.0s     = Validation runtime
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.92s of the 5.03s of remaining time.
    0.398    = Validation score   (accuracy)
    0.25s    = Training   runtime
    0.0s     = Validation runtime
AutoGluon training complete, total runtime = 25.24s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230222_232806/")

(Advanced) Cache preprocessed data

If you are repeatedly predicting on the same data you can cache the preprocessed version of the data and directly send the preprocessed data to predictor.predict for faster inference:

test_data_preprocessed = predictor.transform_features(test_data)

# The following call will be faster than a normal predict call because we are skipping the preprocessing stage.
predictions = predictor.predict(test_data_preprocessed, transform_features=False)

Note that this is only useful in situations where you are repeatedly predicting on the same data. If this significantly speeds up your use-case, consider whether your current approach makes sense or if a cache on the predictions is a better solution.

(Advanced) Disable preprocessing

If you would rather do data preprocessing outside of TabularPredictor, you can disable TabularPredictor’s preprocessing entirely via:

predictor.fit(..., feature_generator=None, feature_metadata=YOUR_CUSTOM_FEATURE_METADATA)

Be warned that this removes ALL guardrails on data sanitization. It is very likely that you will run into errors doing this unless you are very familiar with AutoGluon.

One instance where this can be helpful is if you have many problems that re-use the exact same data with the exact same features. If you had 30 tasks that re-use the same features, you could fit a autogluon.features feature generator once on the data, and then when you need to predict on the 30 tasks, preprocess the data only once and then send the preprocessed data to all 30 predictors.

If you encounter memory issues

To reduce memory usage during training, you may try each of the following strategies individually or combinations of them (these may harm accuracy):

  • In fit(), set excluded_model_types = ['KNN', 'XT' ,'RF'] (or some subset of these models).

  • Try different presets in fit().

  • In fit(), set hyperparameters = 'light' or hyperparameters = 'very_light'.

  • Text fields in your table require substantial memory for N-gram featurization. To mitigate this in fit(), you can either: (1) add 'ignore_text' to your presets list (to ignore text features), or (2) specify the argument:

from sklearn.feature_extraction.text import CountVectorizer
from autogluon.features.generators import AutoMLPipelineFeatureGenerator
feature_generator = AutoMLPipelineFeatureGenerator(vectorizer=CountVectorizer(min_df=30, ngram_range=(1, 3), max_features=MAX_NGRAM, dtype=np.uint8))

for example using MAX_NGRAM = 1000 (try various values under 10000 to reduce the number of N-gram features used to represent each text field)

In addition to reducing memory usage, many of the above strategies can also be used to reduce training times.

To reduce memory usage during inference:

  • If trying to produce predictions for a large test dataset, break the test data into smaller chunks as demonstrated in FAQ.

  • If models have been previously persisted in memory but inference-speed is not a major concern, call predictor.unpersist_models().

  • If models have been previously persisted in memory, bagging was used in fit(), and inference-speed is a concern: call predictor.refit_full() and use one of the refit-full models for prediction (ensure this is the only model persisted in memory).

If you encounter disk space issues

To reduce disk usage, you may try each of the following strategies individually or combinations of them:

  • Make sure to delete all predictor.path folders from previous fit() runs! These can eat up your free space if you call fit() many times. If you didn’t specify path, AutoGluon still automatically saved its models to a folder called: “AutogluonModels/ag-[TIMESTAMP]”, where TIMESTAMP records when fit() was called, so make sure to also delete these folders if you run low on free space.

  • Call predictor.save_space() to delete auxiliary files produced during fit().

  • Call predictor.delete_models(models_to_keep='best', dry_run=False) if you only intend to use this predictor for inference going forward (will delete files required for non-prediction-related functionality like fit_summary).

  • In fit(), you can add 'optimize_for_deployment' to the presets list, which will automatically invoke the previous two strategies after training.

  • Most of the above strategies to reduce memory usage will also reduce disk usage (but may harm accuracy).

References

The following paper describes how AutoGluon internally operates on tabular data:

Erickson et al. AutoGluon-Tabular: Robust and Accurate AutoML for Structured Data. Arxiv, 2020.

Next Steps

If you are interested in deployment optimization, refer to the Predicting Columns in a Table - Deployment Optimization tutorial.