AutoGluon Tabular - In Depth#

Open In Colab Open In SageMaker Studio Lab

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 = 1000  # 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())

test_data = TabularDataset('https://autogluon.s3.amazonaws.com/datasets/Inc/test.csv')
y_test = test_data[label]
test_data_nolabel = test_data.drop(columns=[label])  # delete label column

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              1000
unique               15
top        Craft-repair
freq                142
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.

Refer to the Search Space documentation to learn more about AutoGluon search space.

from autogluon.common import space

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': space.Real(1e-4, 1e-2, default=5e-4, log=True),  # learning rate used in training (real-valued hyperparameter searched on log-scale)
    'activation': space.Categorical('relu', 'softrelu', 'tanh'),  # activation function used in NN (categorical hyperparameter, default = first entry)
    'dropout_prob': 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': 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,
}  # Refer to TabularPredictor.fit docstring for all valid values

predictor = TabularPredictor(label=label, eval_metric=metric).fit(
    train_data,
    time_limit=time_limit,
    hyperparameters=hyperparameters,
    hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
)
Fitted model: NeuralNetTorch/a8f1b6aa ...
	0.355	 = Validation score   (accuracy)
	1.63s	 = Training   runtime
	0.01s	 = Validation runtime
Fitted model: NeuralNetTorch/4933d9fb ...
	0.31	 = Validation score   (accuracy)
	2.41s	 = Training   runtime
	0.01s	 = Validation runtime
Fitted model: NeuralNetTorch/4576442f ...
	0.32	 = Validation score   (accuracy)
	2.24s	 = Training   runtime
	0.01s	 = Validation runtime
Fitted model: NeuralNetTorch/df0262f4 ...
	0.325	 = Validation score   (accuracy)
	2.68s	 = Training   runtime
	0.01s	 = Validation runtime
Fitted model: NeuralNetTorch/581dada7 ...
	0.295	 = Validation score   (accuracy)
	2.11s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: WeightedEnsemble_L2 ... Training model for up to 119.9s of the 105.13s of remaining time.
	0.4	 = Validation score   (accuracy)
	0.24s	 = Training   runtime
	0.0s	 = Validation runtime
AutoGluon training complete, total runtime = 15.13s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230629_224512/")

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:   [' Other-service', ' Craft-repair', ' Exec-managerial', ' Sales', ' Other-service']
Evaluation: accuracy on test data: 0.344354591053332
Evaluations on test data:
{
    "accuracy": 0.344354591053332
}

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()
*** 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.400       0.034530  5.571919                0.000436           0.237189            2       True         11
1               LightGBM/T3      0.375       0.004271  0.313712                0.004271           0.313712            1       True          3
2               LightGBM/T5      0.375       0.006363  0.498348                0.006363           0.498348            1       True          5
3               LightGBM/T1      0.370       0.004265  0.717077                0.004265           0.717077            1       True          1
4               LightGBM/T4      0.360       0.008915  0.543975                0.008915           0.543975            1       True          4
5               LightGBM/T2      0.355       0.005358  0.596638                0.005358           0.596638            1       True          2
6   NeuralNetTorch/a8f1b6aa      0.355       0.011080  1.633288                0.011080           1.633288            1       True          6
7   NeuralNetTorch/df0262f4      0.325       0.013490  2.678938                0.013490           2.678938            1       True          9
8   NeuralNetTorch/4576442f      0.320       0.011146  2.241106                0.011146           2.241106            1       True          8
9   NeuralNetTorch/4933d9fb      0.310       0.012710  2.408154                0.012710           2.408154            1       True          7
10  NeuralNetTorch/581dada7      0.295       0.010751  2.114517                0.010751           2.114517            1       True         10
Number of models trained: 11
Types of models trained:
{'WeightedEnsembleModel', 'TabularNeuralNetTorchModel', 'LGBModel'}
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:169: 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.

label = 'class'  # Now lets predict the "class" column (binary classification)
test_data_nolabel = test_data.drop(columns=[label])
y_test = test_data[label]
save_path = 'agModels-predictClass'  # folder where to store trained models

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-20230629_224528/"
Beginning AutoGluon training ...
AutoGluon will save models to "AutogluonModels/ag-20230629_224528/"
AutoGluon Version:  0.8.1b20230629
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Disk Space Avail:   234.56 GB / 274.87 GB (85.3%)
Train Data Rows:    1000
Train Data Columns: 14
Label Column: class
Preprocessing data ...
AutoGluon infers your prediction problem is: 'binary' (because only two unique label-values observed).
	2 unique label values:  [' >50K', ' <=50K']
	If 'binary' 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'])
Selected class <--> label mapping:  class 1 =  >50K, class 0 =  <=50K
	Note: For your binary classification, AutoGluon arbitrarily selected which label-value represents positive ( >50K) vs negative ( <=50K) class.
	To explicitly set the positive_class, either rename classes to 1 and 0, or specify positive_class in Predictor init.
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
	Available Memory:                    30684.81 MB
	Train Data (Original)  Memory Usage: 0.59 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 1 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...
	Stage 5 Generators:
		Fitting DropDuplicatesFeatureGenerator...
	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', 'occupation', 'relationship', ...]
	Types of features in processed data (raw dtype, special dtypes):
		('category', [])  : 7 | ['workclass', 'education', 'marital-status', 'occupation', 'relationship', ...]
		('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
		('int', ['bool']) : 1 | ['sex']
	0.1s = Fit runtime
	14 features in original data used to generate 14 features in processed data.
	Train Data (Processed) Memory Usage: 0.06 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.11s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
	To change this, specify the eval_metric parameter of Predictor()
User-specified model hyperparameters to be fit:
{
	'NN_TORCH': {'num_epochs': 2},
	'GBM': {'num_boost_round': 20},
}
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.823	 = Validation score   (accuracy)
	1.14s	 = Training   runtime
	0.02s	 = Validation runtime
Fitting model: NeuralNetTorch_BAG_L1 ...
	Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
	0.744	 = Validation score   (accuracy)
	1.66s	 = Training   runtime
	0.05s	 = Validation runtime
Fitting model: WeightedEnsemble_L2 ...
	0.823	 = Validation score   (accuracy)
	0.11s	 = 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.828	 = Validation score   (accuracy)
	0.49s	 = Training   runtime
	0.02s	 = Validation runtime
Fitting model: NeuralNetTorch_BAG_L2 ...
	Fitting 5 child models (S1F1 - S1F5) | Fitting with ParallelLocalFoldFittingStrategy
	0.748	 = Validation score   (accuracy)
	1.59s	 = Training   runtime
	0.07s	 = Validation runtime
Fitting model: WeightedEnsemble_L3 ...
	0.829	 = Validation score   (accuracy)
	0.11s	 = Training   runtime
	0.0s	 = Validation runtime
AutoGluon training complete, total runtime = 14.57s ... Best model: "WeightedEnsemble_L3"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230629_224528/")

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:

# Lets also specify the "f1" metric
predictor = TabularPredictor(label=label, eval_metric='f1', path=save_path).fit(
    train_data, auto_stack=True,
    time_limit=30, hyperparameters={'FASTAI': {'num_epochs': 10}, 'GBM': {'num_boost_round': 200}}  # last 2 arguments are for quick demo, omit them in real applications
)
predictor.leaderboard(test_data, silent=True)
Warning: path already exists! This predictor may overwrite an existing predictor! path="agModels-predictClass"
Stack configuration (auto_stack=True): num_stack_levels=0, num_bag_folds=8, num_bag_sets=20
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "agModels-predictClass/"
AutoGluon Version:  0.8.1b20230629
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Disk Space Avail:   234.55 GB / 274.87 GB (85.3%)
Train Data Rows:    1000
Train Data Columns: 14
Label Column: class
Preprocessing data ...
AutoGluon infers your prediction problem is: 'binary' (because only two unique label-values observed).
	2 unique label values:  [' >50K', ' <=50K']
	If 'binary' 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'])
Selected class <--> label mapping:  class 1 =  >50K, class 0 =  <=50K
	Note: For your binary classification, AutoGluon arbitrarily selected which label-value represents positive ( >50K) vs negative ( <=50K) class.
	To explicitly set the positive_class, either rename classes to 1 and 0, or specify positive_class in Predictor init.
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
	Available Memory:                    29546.8 MB
	Train Data (Original)  Memory Usage: 0.59 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 1 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...
	Stage 5 Generators:
		Fitting DropDuplicatesFeatureGenerator...
	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', 'occupation', 'relationship', ...]
	Types of features in processed data (raw dtype, special dtypes):
		('category', [])  : 7 | ['workclass', 'education', 'marital-status', 'occupation', 'relationship', ...]
		('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
		('int', ['bool']) : 1 | ['sex']
	0.1s = Fit runtime
	14 features in original data used to generate 14 features in processed data.
	Train Data (Processed) Memory Usage: 0.06 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.11s ...
AutoGluon will gauge predictive performance using evaluation metric: 'f1'
	To change this, specify the eval_metric parameter of Predictor()
User-specified model hyperparameters to be fit:
{
	'FASTAI': {'num_epochs': 10},
	'GBM': {'num_boost_round': 200},
}
Fitting 2 L1 models ...
Fitting model: LightGBM_BAG_L1 ... Training model for up to 29.89s of the 29.89s of remaining time.
	Fitting 8 child models (S1F1 - S1F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.6856	 = Validation score   (f1)
	1.06s	 = Training   runtime
	0.05s	 = Validation runtime
Fitting model: NeuralNetFastAI_BAG_L1 ... Training model for up to 25.36s of the 25.36s of remaining time.
	Fitting 8 child models (S1F1 - S1F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.6759	 = Validation score   (f1)
	4.46s	 = Training   runtime
	0.12s	 = Validation runtime
Repeating k-fold bagging: 2/20
Fitting model: LightGBM_BAG_L1 ... Training model for up to 17.36s of the 17.36s of remaining time.
	Fitting 8 child models (S2F1 - S2F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.6623	 = Validation score   (f1)
	2.43s	 = Training   runtime
	0.11s	 = Validation runtime
Fitting model: NeuralNetFastAI_BAG_L1 ... Training model for up to 12.44s of the 12.44s of remaining time.
	Fitting 8 child models (S2F1 - S2F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.6723	 = Validation score   (f1)
	8.99s	 = Training   runtime
	0.24s	 = Validation runtime
Completed 2/20 k-fold bagging repeats ...
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.89s of the 4.21s of remaining time.
	0.6779	 = Validation score   (f1)
	0.3s	 = Training   runtime
	0.0s	 = Validation runtime
AutoGluon training complete, total runtime = 26.1s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("agModels-predictClass/")
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.635375 0.662281 0.518836 0.107661 2.426651 0.518836 0.107661 2.426651 1 True 1
1 WeightedEnsemble_L2 0.614973 0.677895 3.262649 0.347172 11.708896 0.002009 0.002869 0.296009 2 True 3
2 NeuralNetFastAI_BAG_L1 0.613378 0.672340 2.741803 0.236642 8.986235 2.741803 0.236642 8.986235 1 True 2

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).

Decision Threshold Calibration#

Major metric score improvements can be achieved in binary classification for metrics such as "f1" and "balanced_accuracy" by adjusting the prediction decision threshold via calibrate_decision_threshold to a value other than the default 0.5.

Below is an example of the "f1" score achieved on the test data with and without calibrating the decision threshold:

print(f'Prior to calibration (predictor.decision_threshold={predictor.decision_threshold}):')
scores = predictor.evaluate(test_data)

calibrated_decision_threshold = predictor.calibrate_decision_threshold()
predictor.set_decision_threshold(calibrated_decision_threshold)

print(f'After calibration (predictor.decision_threshold={predictor.decision_threshold}):')
scores_calibrated = predictor.evaluate(test_data)
Prior to calibration (predictor.decision_threshold=0.5):
After calibration (predictor.decision_threshold=0.45):
Evaluation: f1 on test data: 0.6149732620320856
Evaluations on test data:
{
    "f1": 0.6149732620320856,
    "accuracy": 0.8378544375063978,
    "balanced_accuracy": 0.737231737428855,
    "mcc": 0.5210779963149204,
    "roc_auc": 0.8910228158452306,
    "precision": 0.7043429844097996,
    "recall": 0.5457290767903364
}
Calibrating decision threshold to optimize metric f1 | Checking 101 thresholds...
	Base Threshold: 0.500	| val: 0.6779
	Best Threshold: 0.450	| val: 0.6827
Updating predictor.decision_threshold from 0.5 -> 0.45
	This will impact how prediction probabilities are converted to predictions in binary classification.
	Prediction probabilities of the positive class >0.45 will be predicted as the positive class ( >50K). This can significantly impact metric scores.
	You can update this value via `predictor.set_decision_threshold`.
	You can calculate an optimal decision threshold on the validation data via `predictor.calibrate_decision_threshold()`.
Evaluation: f1 on test data: 0.6412422927609043
Evaluations on test data:
{
    "f1": 0.6412422927609043,
    "accuracy": 0.8391851776026206,
    "balanced_accuracy": 0.7587592402662017,
    "mcc": 0.5396100276722735,
    "roc_auc": 0.8910228158452306,
    "precision": 0.6812227074235808,
    "recall": 0.6056945642795514
}
for metric_name in scores:
    metric_score = scores[metric_name]
    metric_score_calibrated = scores_calibrated[metric_name]
    decision_threshold = predictor.decision_threshold
    print(f'decision_threshold={decision_threshold:.3f}\t| metric="{metric_name}"'
          f'\n\ttest_score uncalibrated: {metric_score:.4f}'
          f'\n\ttest_score   calibrated: {metric_score_calibrated:.4f}'
          f'\n\ttest_score        delta: {metric_score_calibrated-metric_score:.4f}')
decision_threshold=0.450	| metric="f1"
	test_score uncalibrated: 0.6150
	test_score   calibrated: 0.6412
	test_score        delta: 0.0263
decision_threshold=0.450	| metric="accuracy"
	test_score uncalibrated: 0.8379
	test_score   calibrated: 0.8392
	test_score        delta: 0.0013
decision_threshold=0.450	| metric="balanced_accuracy"
	test_score uncalibrated: 0.7372
	test_score   calibrated: 0.7588
	test_score        delta: 0.0215
decision_threshold=0.450	| metric="mcc"
	test_score uncalibrated: 0.5211
	test_score   calibrated: 0.5396
	test_score        delta: 0.0185
decision_threshold=0.450	| metric="roc_auc"
	test_score uncalibrated: 0.8910
	test_score   calibrated: 0.8910
	test_score        delta: 0.0000
decision_threshold=0.450	| metric="precision"
	test_score uncalibrated: 0.7043
	test_score   calibrated: 0.6812
	test_score        delta: -0.0231
decision_threshold=0.450	| metric="recall"
	test_score uncalibrated: 0.5457
	test_score   calibrated: 0.6057
	test_score        delta: 0.0600

Notice that calibrating for “f1” majorly improved the “f1” metric score, as well as the “balanced_accuracy” score, it harmed the “accuracy” score. Threshold calibration will often result in a tradeoff between performance on different metrics, and the user should keep this in mind.

Instead of calibrating for “f1” specifically, we can calibrate for any metric if we want to maximize the score of that metric:

predictor.set_decision_threshold(0.5)  # Reset decision threshold
for metric_name in ['f1', 'balanced_accuracy', 'mcc']:
    metric_score = predictor.evaluate(test_data, silent=True)[metric_name]
    calibrated_decision_threshold = predictor.calibrate_decision_threshold(metric=metric_name, verbose=False)
    metric_score_calibrated = predictor.evaluate(
        test_data, decision_threshold=calibrated_decision_threshold, silent=True
    )[metric_name]
    print(f'decision_threshold={calibrated_decision_threshold:.3f}\t| metric="{metric_name}"'
          f'\n\ttest_score uncalibrated: {metric_score:.4f}'
          f'\n\ttest_score   calibrated: {metric_score_calibrated:.4f}'
          f'\n\ttest_score        delta: {metric_score_calibrated-metric_score:.4f}')
decision_threshold=0.450	| metric="f1"
	test_score uncalibrated: 0.6150
	test_score   calibrated: 0.6412
	test_score        delta: 0.0263
decision_threshold=0.330	| metric="balanced_accuracy"
	test_score uncalibrated: 0.7372
	test_score   calibrated: 0.7951
	test_score        delta: 0.0578
decision_threshold=0.500	| metric="mcc"
	test_score uncalibrated: 0.5211
	test_score   calibrated: 0.5211
	test_score        delta: 0.0000
Updating predictor.decision_threshold from 0.45 -> 0.5
	This will impact how prediction probabilities are converted to predictions in binary classification.
	Prediction probabilities of the positive class >0.5 will be predicted as the positive class ( >50K). This can significantly impact metric scores.
	You can update this value via `predictor.set_decision_threshold`.
	You can calculate an optimal decision threshold on the validation data via `predictor.calibrate_decision_threshold()`.

Instead of calibrating the decision threshold post-fit, you can have it automatically occur during the fit call by specifying the fit parameter predictor.fit(..., calibrate_decision_threshold=True).

Additional usage examples are below:

# Will use the decision_threshold specified in `predictor.decision_threshold`, can be set via `predictor.set_decision_threshold`
# y_pred = predictor.predict(test_data)
# y_pred_08 = predictor.predict(test_data, decision_threshold=0.8)  # Specify a specific threshold to use only for this predict

# y_pred_proba = predictor.predict_proba(test_data)
# y_pred = predictor.get_pred_from_proba(y_pred_proba)  # Identical output to calling .predict(test_data)
# y_pred_08 = predictor.get_pred_from_proba(y_pred_proba, decision_threshold=0.8)  # Identical output to calling .predict(test_data, decision_threshold=0.8)

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',
 'occupation',
 'relationship',
 'race',
 'sex',
 'capital-gain',
 'capital-loss',
 'hours-per-week',
 'native-country']

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  \
0   31   Private  169085      11th              7   Married-civ-spouse   

  occupation relationship    race      sex  capital-gain  capital-loss  \
0      Sales         Wife   White   Female             0             0   

   hours-per-week  native-country  
0              20   United-States  
0     <=50K
Name: class, 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
<=50K >50K
0 0.866158 0.133842

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.635375 0.662281 0.411524 0.107661 2.426651 0.411524 0.107661 2.426651 1 True 1
1 WeightedEnsemble_L2 0.614973 0.677895 2.667837 0.347172 11.708896 0.002076 0.002869 0.296009 2 True 3
2 NeuralNetFastAI_BAG_L1 0.613378 0.672340 2.254238 0.236642 8.986235 2.254238 0.236642 8.986235 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 WeightedEnsemble_L2 0.677895 0.347172 11.708896 0.002869 0.296009 2 True 3 2 ... {'use_orig_features': False, 'max_base_models': 25, 'max_base_models_per_type': 5, 'save_bag_folds': True} {} {'max_memory_usage_ratio': 1.0, 'max_time_limit_ratio': 1.0, 'max_time_limit': None, 'min_time_limit': 0, 'valid_raw_types': None, 'valid_special_types': None, 'ignored_type_group_special': None, 'ignored_type_group_raw': None, 'get_features_kwargs': None, 'get_features_kwargs_extra': None, 'predict_1_batch_size': None, 'temperature_scalar': None, 'drop_unique': False} [LightGBM_BAG_L1, NeuralNetFastAI_BAG_L1] None {'ensemble_size': 100} {'ensemble_size': 14} {'max_memory_usage_ratio': 1.0, 'max_time_limit_ratio': 1.0, 'max_time_limit': None, 'min_time_limit': 0, 'valid_raw_types': None, 'valid_special_types': None, 'ignored_type_group_special': None, 'ignored_type_group_raw': None, 'get_features_kwargs': None, 'get_features_kwargs_extra': None, 'predict_1_batch_size': None, 'temperature_scalar': None, 'drop_unique': False} [LightGBM_BAG_L1, NeuralNetFastAI_BAG_L1] []
1 NeuralNetFastAI_BAG_L1 0.672340 0.236642 8.986235 0.236642 8.986235 1 True 2 14 ... {'use_orig_features': True, 'max_base_models': 25, 'max_base_models_per_type': 5, 'save_bag_folds': True} {} {'max_memory_usage_ratio': 1.0, 'max_time_limit_ratio': 1.0, 'max_time_limit': None, 'min_time_limit': 0, 'valid_raw_types': None, 'valid_special_types': None, 'ignored_type_group_special': None, 'ignored_type_group_raw': None, 'get_features_kwargs': None, 'get_features_kwargs_extra': None, 'predict_1_batch_size': None, 'temperature_scalar': None, 'drop_unique': False} [education, marital-status, capital-gain, hours-per-week, native-country, race, education-num, capital-loss, relationship, workclass, age, sex, fnlwgt, occupation] None {'layers': None, 'emb_drop': 0.1, 'ps': 0.1, 'bs': 'auto', 'lr': 0.01, 'epochs': 'auto', 'early.stopping.min_delta': 0.0001, 'early.stopping.patience': 20, 'smoothing': 0.0, 'num_epochs': 10} {'epochs': 30, 'best_epoch': 12} {'max_memory_usage_ratio': 1.0, 'max_time_limit_ratio': 1.0, 'max_time_limit': None, 'min_time_limit': 0, 'valid_raw_types': ['bool', 'int', 'float', 'category'], 'valid_special_types': None, 'ignored_type_group_special': ['text_ngram', 'text_as_category'], 'ignored_type_group_raw': None, 'get_features_kwargs': None, 'get_features_kwargs_extra': None, 'predict_1_batch_size': None, 'temperature_scalar': None} [] [WeightedEnsemble_L2]
2 LightGBM_BAG_L1 0.662281 0.107661 2.426651 0.107661 2.426651 1 True 1 14 ... {'use_orig_features': True, 'max_base_models': 25, 'max_base_models_per_type': 5, 'save_bag_folds': True} {} {'max_memory_usage_ratio': 1.0, 'max_time_limit_ratio': 1.0, 'max_time_limit': None, 'min_time_limit': 0, 'valid_raw_types': None, 'valid_special_types': None, 'ignored_type_group_special': None, 'ignored_type_group_raw': None, 'get_features_kwargs': None, 'get_features_kwargs_extra': None, 'predict_1_batch_size': None, 'temperature_scalar': None, 'drop_unique': False} [education, marital-status, capital-gain, hours-per-week, native-country, race, education-num, capital-loss, relationship, workclass, age, sex, fnlwgt, occupation] None {'learning_rate': 0.05, 'num_boost_round': 200} {'num_boost_round': 80} {'max_memory_usage_ratio': 1.0, 'max_time_limit_ratio': 1.0, 'max_time_limit': None, 'min_time_limit': 0, 'valid_raw_types': ['bool', 'int', 'float', 'category'], 'valid_special_types': None, 'ignored_type_group_special': None, 'ignored_type_group_raw': None, 'get_features_kwargs': None, 'get_features_kwargs_extra': None, 'predict_1_batch_size': None, 'temperature_scalar': None} [] [WeightedEnsemble_L2]

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.635375 0.848910 0.747600 -0.332945 0.662281 0.401095 0.107661 2.426651 0.401095 0.107661 2.426651 1 True 1
1 WeightedEnsemble_L2 0.614973 0.837854 0.737232 -0.375681 0.677895 2.658950 0.347172 11.708896 0.002023 0.002869 0.296009 2 True 3
2 NeuralNetFastAI_BAG_L1 0.613378 0.836114 0.736834 -0.381505 0.672340 2.255831 0.236642 8.986235 2.255831 0.236642 8.986235 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:  <=50K

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: f1 on test data: 0.6149732620320856
Evaluations on test data:
{
    "f1": 0.6149732620320856,
    "accuracy": 0.8378544375063978,
    "balanced_accuracy": 0.737231737428855,
    "mcc": 0.5210779963149204,
    "roc_auc": 0.8910228158452306,
    "precision": 0.7043429844097996,
    "recall": 0.5457290767903364
}

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

perf = predictor.evaluate(test_data)
Evaluation: f1 on test data: 0.6149732620320856
Evaluations on test data:
{
    "f1": 0.6149732620320856,
    "accuracy": 0.8378544375063978,
    "balanced_accuracy": 0.737231737428855,
    "mcc": 0.5210779963149204,
    "roc_auc": 0.8910228158452306,
    "precision": 0.7043429844097996,
    "recall": 0.5457290767903364
}

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 5000 rows with 5 shuffle sets...
	112.8s	= Expected runtime (22.56s per shuffle set)
	93.59s	= Actual runtime (Completed 5 of 5 shuffle sets)
importance stddev p_value n p99_high p99_low
education-num 0.093462 0.007080 0.000004 5 0.108040 0.078885
relationship 0.064041 0.005067 0.000005 5 0.074474 0.053609
marital-status 0.061409 0.006708 0.000017 5 0.075221 0.047597
capital-gain 0.048154 0.005399 0.000019 5 0.059272 0.037037
age 0.039870 0.008585 0.000243 5 0.057546 0.022194
occupation 0.025016 0.007808 0.001005 5 0.041093 0.008940
hours-per-week 0.016109 0.006233 0.002226 5 0.028942 0.003276
capital-loss 0.007209 0.001376 0.000152 5 0.010043 0.004376
race 0.003717 0.002476 0.014201 5 0.008815 -0.001382
sex 0.002848 0.006133 0.178848 5 0.015476 -0.009780
workclass 0.002734 0.005446 0.162229 5 0.013947 -0.008479
education 0.002488 0.003267 0.081893 5 0.009214 -0.004238
native-country -0.001754 0.002598 0.897164 5 0.003596 -0.007104
fnlwgt -0.004554 0.005823 0.922372 5 0.007436 -0.016544

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.

Optimization

Inference Speedup

Cost

Notes

refit_full

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

-Quality, +FitTime

Only provides speedup with bagging enabled.

persist_models

Up to 10x in online-inference

++MemoryUsage

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.

infer_limit

Configurable, ~up to 50x

-Quality (Relative to speedup)

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

distill

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

–Quality, ++FitTime

Not compatible with refit_full and infer_limit.

feature pruning

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

-Quality?, ++FitTime

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

use faster hardware

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

+Hardware

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.

manual hyperparameters adjustment

Usually at most 2x assuming infer_limit is already specified.

—Quality?, +++UserMLExpertise

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.

manual data preprocessing

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

++++UserMLExpertise, ++++UserCode

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
Predictions:  [' <=50K' ' <=50K' ' >50K' ' <=50K' ' <=50K' ' >50K' ' >50K' ' <=50K'
 ' <=50K' ' <=50K' ' <=50K' ' <=50K' ' <=50K' ' <=50K' ' <=50K' ' <=50K'
 ' <=50K' ' >50K' ' >50K' ' <=50K']
Persisting 3 models in memory. Models will require 0.02% of memory.
Evaluation: f1 on test data: 0.8333333333333333
Evaluations on test data:
{
    "f1": 0.8333333333333333,
    "accuracy": 0.9,
    "balanced_accuracy": 0.8571428571428572,
    "mcc": 0.7867957924694432,
    "precision": 1.0,
    "recall": 0.7142857142857143
}
Unpersisted 3 models: ['WeightedEnsemble_L2', 'LightGBM_BAG_L1', 'NeuralNetFastAI_BAG_L1']
['WeightedEnsemble_L2', 'LightGBM_BAG_L1', 'NeuralNetFastAI_BAG_L1']

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-20230629_224838/"
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230629_224838/"
AutoGluon Version:  0.8.1b20230629
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Disk Space Avail:   234.55 GB / 274.87 GB (85.3%)
Train Data Rows:    1000
Train Data Columns: 14
Label Column: class
Preprocessing data ...
AutoGluon infers your prediction problem is: 'binary' (because only two unique label-values observed).
	2 unique label values:  [' >50K', ' <=50K']
	If 'binary' 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'])
Selected class <--> label mapping:  class 1 =  >50K, class 0 =  <=50K
	Note: For your binary classification, AutoGluon arbitrarily selected which label-value represents positive ( >50K) vs negative ( <=50K) class.
	To explicitly set the positive_class, either rename classes to 1 and 0, or specify positive_class in Predictor init.
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
	Available Memory:                    30348.51 MB
	Train Data (Original)  Memory Usage: 0.59 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 1 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...
	Stage 5 Generators:
		Fitting DropDuplicatesFeatureGenerator...
	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', 'occupation', 'relationship', ...]
	Types of features in processed data (raw dtype, special dtypes):
		('category', [])  : 7 | ['workclass', 'education', 'marital-status', 'occupation', 'relationship', ...]
		('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
		('int', ['bool']) : 1 | ['sex']
	0.1s = Fit runtime
	14 features in original data used to generate 14 features in processed data.
	Train Data (Processed) Memory Usage: 0.06 MB (0.0% of available memory)
	1.611μs	= Feature Preprocessing Time (1 row | 10000 batch size)
		Feature Preprocessing requires 3.22% 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: 800, Val Rows: 200
User-specified model hyperparameters to be fit:
{
	'NN_TORCH': {},
	'GBM': [{'extra_trees': True, 'ag_args': {'name_suffix': 'XT'}}, {}, 'GBMLarge'],
	'CAT': {},
	'XGB': {},
	'FASTAI': {},
	'RF': [{'criterion': 'gini', 'ag_args': {'name_suffix': 'Gini', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'entropy', 'ag_args': {'name_suffix': 'Entr', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'squared_error', 'ag_args': {'name_suffix': 'MSE', 'problem_types': ['regression', 'quantile']}}],
	'XT': [{'criterion': 'gini', 'ag_args': {'name_suffix': 'Gini', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'entropy', 'ag_args': {'name_suffix': 'Entr', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'squared_error', 'ag_args': {'name_suffix': 'MSE', 'problem_types': ['regression', 'quantile']}}],
	'KNN': [{'weights': 'uniform', 'ag_args': {'name_suffix': 'Unif'}}, {'weights': 'distance', 'ag_args': {'name_suffix': 'Dist'}}],
}
Fitting 13 L1 models ...
Fitting model: KNeighborsUnif ... Training model for up to 29.73s of the 29.73s of remaining time.
	0.725	 = Validation score   (accuracy)
	0.06s	 = Training   runtime
	0.01s	 = Validation runtime
	4.999μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	4.999μs	 = Validation runtime (1 row | 10000 batch size)
Fitting model: KNeighborsDist ... Training model for up to 29.66s of the 29.66s of remaining time.
	0.71	 = Validation score   (accuracy)
	0.05s	 = Training   runtime
	0.01s	 = Validation runtime
	4.215μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	4.215μs	 = Validation runtime (1 row | 10000 batch size)
Fitting model: LightGBMXT ... Training model for up to 29.59s of the 29.59s of remaining time.
	0.85	 = Validation score   (accuracy)
	0.26s	 = Training   runtime
	0.0s	 = Validation runtime
	3.239μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	3.239μs	 = Validation runtime (1 row | 10000 batch size)
Fitting model: LightGBM ... Training model for up to 29.32s of the 29.32s of remaining time.
	0.84	 = Validation score   (accuracy)
	0.3s	 = Training   runtime
	0.0s	 = Validation runtime
	2.693μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	2.693μs	 = Validation runtime (1 row | 10000 batch size)
Fitting model: RandomForestGini ... Training model for up to 29.02s of the 29.02s of remaining time.
	0.84	 = Validation score   (accuracy)
	0.65s	 = Training   runtime
	0.06s	 = Validation runtime
	0.012ms	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	0.012ms	 = Validation runtime (1 row | 10000 batch size)
Fitting model: RandomForestEntr ... Training model for up to 28.29s of the 28.29s of remaining time.
	0.835	 = Validation score   (accuracy)
	0.61s	 = Training   runtime
	0.06s	 = Validation runtime
	0.012ms	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	0.012ms	 = Validation runtime (1 row | 10000 batch size)
Fitting model: CatBoost ... Training model for up to 27.61s of the 27.61s of remaining time.
	0.86	 = Validation score   (accuracy)
	1.89s	 = Training   runtime
	0.01s	 = Validation runtime
	2.878μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	2.878μs	 = Validation runtime (1 row | 10000 batch size)
Fitting model: ExtraTreesGini ... Training model for up to 25.71s of the 25.7s of remaining time.
	0.815	 = Validation score   (accuracy)
	0.62s	 = Training   runtime
	0.06s	 = Validation runtime
	0.013ms	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	0.013ms	 = Validation runtime (1 row | 10000 batch size)
Fitting model: ExtraTreesEntr ... Training model for up to 25.01s of the 25.0s of remaining time.
	0.82	 = Validation score   (accuracy)
	0.62s	 = Training   runtime
	0.06s	 = Validation runtime
	0.013ms	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	0.013ms	 = Validation runtime (1 row | 10000 batch size)
Fitting model: NeuralNetFastAI ... Training model for up to 24.31s of the 24.31s of remaining time.
No improvement since epoch 7: early stopping
	0.86	 = Validation score   (accuracy)
	1.06s	 = Training   runtime
	0.01s	 = 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 23.22s of the 23.22s of remaining time.
	0.85	 = Validation score   (accuracy)
	0.26s	 = Training   runtime
	0.01s	 = Validation runtime
	4.305μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	4.305μs	 = Validation runtime (1 row | 10000 batch size)
Fitting model: NeuralNetTorch ... Training model for up to 22.94s of the 22.94s of remaining time.
	0.85	 = Validation score   (accuracy)
	2.29s	 = Training   runtime
	0.01s	 = Validation runtime
	5.412μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	5.412μs	 = Validation runtime (1 row | 10000 batch size)
Fitting model: LightGBMLarge ... Training model for up to 20.64s of the 20.64s of remaining time.
	0.815	 = Validation score   (accuracy)
	0.83s	 = Training   runtime
	0.01s	 = Validation runtime
	7.615μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	7.615μs	 = Validation runtime (1 row | 10000 batch size)
Removing 6/13 base models to satisfy inference constraint (constraint=0.046ms) ...
	0.102ms	-> 0.097ms	(KNeighborsDist)
	0.097ms	-> 0.092ms	(KNeighborsUnif)
	0.092ms	-> 0.079ms	(ExtraTreesGini)
	0.079ms	-> 0.072ms	(LightGBMLarge)
	0.072ms	-> 0.058ms	(ExtraTreesEntr)
	0.058ms	-> 0.046ms	(RandomForestEntr)
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.73s of the 19.75s of remaining time.
	0.86	 = Validation score   (accuracy)
	0.34s	 = Training   runtime
	0.0s	 = Validation runtime
	1.418μs	 = Validation runtime (1 row | 10000 batch size | MARGINAL)
	4.296μs	 = Validation runtime (1 row | 10000 batch size)
AutoGluon training complete, total runtime = 10.6s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230629_224838/")
Persisting 2 models in memory. Models will require 0.0% of memory.
model score_val pred_time_val fit_time pred_time_val_marginal fit_time_marginal stack_level can_infer fit_order
0 CatBoost 0.860 0.005336 1.892233 0.005336 1.892233 1 True 7
1 WeightedEnsemble_L2 0.860 0.006024 2.229711 0.000688 0.337478 2 True 14
2 NeuralNetFastAI 0.860 0.010851 1.064865 0.010851 1.064865 1 True 10
3 LightGBMXT 0.850 0.004835 0.256675 0.004835 0.256675 1 True 3
4 XGBoost 0.850 0.006991 0.264151 0.006991 0.264151 1 True 11
5 NeuralNetTorch 0.850 0.010384 2.286078 0.010384 2.286078 1 True 12
6 LightGBM 0.840 0.004554 0.296107 0.004554 0.296107 1 True 4
7 RandomForestGini 0.840 0.058617 0.648715 0.058617 0.648715 1 True 5
8 RandomForestEntr 0.835 0.060862 0.608762 0.060862 0.608762 1 True 6
9 ExtraTreesEntr 0.820 0.058943 0.619735 0.058943 0.619735 1 True 9
10 LightGBMLarge 0.815 0.005783 0.831465 0.005783 0.831465 1 True 13
11 ExtraTreesGini 0.815 0.058373 0.623895 0.058373 0.623895 1 True 8
12 KNeighborsUnif 0.725 0.013988 0.055229 0.013988 0.055229 1 True 1
13 KNeighborsDist 0.710 0.013970 0.047173 0.013970 0.047173 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 195785.1 rows per second. (User-specified Throughput = 20000.0)
Model uses 10.2% 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)
Alternative ensembles you can use for prediction: ['WeightedEnsemble_L2Best']
Fitting model: WeightedEnsemble_L2Best ...
	0.6779	 = Validation score   (f1)
	0.29s	 = Training   runtime
	0.0s	 = Validation runtime
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.677895 0.347072 11.700172 0.002769 0.287285 2 True 4
1 NeuralNetFastAI_BAG_L1 0.672340 0.236642 8.986235 0.236642 8.986235 1 True 2
2 LightGBM_BAG_L1 0.662281 0.107661 2.426651 0.107661 2.426651 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-predictClass/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)
Name of each refit-full model corresponding to a previous bagged ensemble:
{'LightGBM_BAG_L1': 'LightGBM_BAG_L1_FULL', 'NeuralNetFastAI_BAG_L1': 'NeuralNetFastAI_BAG_L1_FULL', 'WeightedEnsemble_L2': 'WeightedEnsemble_L2_FULL'}
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.17s	 = Training   runtime
Fitting 1 L1 models ...
Fitting model: NeuralNetFastAI_BAG_L1_FULL ...
	Stopping at the best epoch learned earlier - 12.
	0.46s	 = Training   runtime
Fitting model: WeightedEnsemble_L2_FULL | Skipping fit via cloning parent ...
	0.3s	 = Training   runtime
Updated best model to "WeightedEnsemble_L2_FULL" (Previously "WeightedEnsemble_L2"). AutoGluon will default to using "WeightedEnsemble_L2_FULL" for predict() and predict_proba().
Refit complete, total runtime = 0.75s
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_FULL 0.637458 NaN 0.024615 NaN 0.165800 0.024615 NaN 0.165800 1 True 4
1 LightGBM_BAG_L1 0.635375 0.662281 0.380208 0.107661 2.426651 0.380208 0.107661 2.426651 1 True 1
2 WeightedEnsemble_L2 0.614973 0.677895 2.570773 0.347172 11.708896 0.002109 0.002869 0.296009 2 True 3
3 NeuralNetFastAI_BAG_L1 0.613378 0.672340 2.188456 0.236642 8.986235 2.188456 0.236642 8.986235 1 True 2
4 WeightedEnsemble_L2_FULL 0.560238 NaN 0.169592 NaN 0.925058 0.002377 NaN 0.296009 2 True 6
5 NeuralNetFastAI_BAG_L1_FULL 0.558315 NaN 0.142601 NaN 0.463248 0.142601 NaN 0.463248 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, silent=True)
[1000]	valid_set's l2: 0.101118
[2000]	valid_set's l2: 0.0995154
[3000]	valid_set's l2: 0.0990427
['LightGBM_DSTL', 'CatBoost_DSTL', 'RandomForestMSE_DSTL', 'NeuralNetTorch_DSTL', 'WeightedEnsemble_L2_DSTL']
predictions from LightGBM_DSTL: [' <=50K', ' <=50K', ' <=50K', ' <=50K', ' <=50K']
Distilling with teacher='WeightedEnsemble_L2_FULL', teacher_preds=soft, augment_method=spunge ...
SPUNGE: Augmenting training data with 4000 synthetic samples for distillation...
Distilling with each of these student models: ['LightGBM_DSTL', 'CatBoost_DSTL', 'RandomForestMSE_DSTL', 'NeuralNetTorch_DSTL']
Fitting 4 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.
	-0.0989	 = Validation score   (-mean_squared_error)
	2.51s	 = Training   runtime
	0.03s	 = Validation runtime
Fitting model: CatBoost_DSTL ... Training model for up to 27.31s of the 27.31s of remaining time.
	Note: model has different eval_metric than default.
	-0.1032	 = Validation score   (-mean_squared_error)
	1.92s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: RandomForestMSE_DSTL ... Training model for up to 25.38s of the 25.37s of remaining time.
	Note: model has different eval_metric than default.
	-0.1161	 = Validation score   (-mean_squared_error)
	1.09s	 = Training   runtime
	0.06s	 = Validation runtime
Fitting model: NeuralNetTorch_DSTL ... Training model for up to 24.16s of the 24.16s of remaining time.
	Note: model has different eval_metric than default.
	-0.1081	 = Validation score   (-mean_squared_error)
	9.62s	 = 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 14.52s of remaining time.
	Note: model has different eval_metric than default.
	-0.0984	 = Validation score   (-mean_squared_error)
	0.1s	 = 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             CatBoost_DSTL   0.649351       0.005704  1.921343                0.005704           1.921343            1       True          8
1       NeuralNetTorch_DSTL   0.586667       0.010680  9.619369                0.010680           9.619369            1       True         10
2             LightGBM_DSTL   0.578947       0.027704  2.514069                0.027704           2.514069            1       True          7
3  WeightedEnsemble_L2_DSTL   0.578947       0.033834  4.540181                0.000425           0.104769            2       True         11
4      RandomForestMSE_DSTL   0.531646       0.059350  1.086057                0.059350           1.086057            1       True          9
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_FULL 0.637458 NaN 0.024140 NaN 0.165800 0.024140 NaN 0.165800 1 True 4
1 LightGBM_BAG_L1 0.635375 0.662281 0.382775 0.107661 2.426651 0.382775 0.107661 2.426651 1 True 1
2 WeightedEnsemble_L2 0.614973 0.677895 2.608946 0.347172 11.708896 0.002160 0.002869 0.296009 2 True 3
3 NeuralNetFastAI_BAG_L1 0.613378 0.672340 2.224011 0.236642 8.986235 2.224011 0.236642 8.986235 1 True 2
4 CatBoost_DSTL 0.583861 0.649351 0.017885 0.005704 1.921343 0.017885 0.005704 1.921343 1 True 8
5 WeightedEnsemble_L2_DSTL 0.579536 0.578947 1.093615 0.033834 4.540181 0.002413 0.000425 0.104769 2 True 11
6 LightGBM_DSTL 0.578919 0.578947 1.073318 0.027704 2.514069 1.073318 0.027704 2.514069 1 True 7
7 WeightedEnsemble_L2_FULL 0.560238 NaN 0.167991 NaN 0.925058 0.002092 NaN 0.296009 2 True 6
8 NeuralNetFastAI_BAG_L1_FULL 0.558315 NaN 0.141759 NaN 0.463248 0.141759 NaN 0.463248 1 True 5
9 RandomForestMSE_DSTL 0.557154 0.531646 0.221704 0.059350 1.086057 0.221704 0.059350 1.086057 1 True 9
10 NeuralNetTorch_DSTL 0.549847 0.586667 0.043171 0.010680 9.619369 0.043171 0.010680 9.619369 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-20230629_224924/"
Presets specified: ['good_quality', 'optimize_for_deployment']
Stack configuration (auto_stack=True): num_stack_levels=0, num_bag_folds=8, num_bag_sets=20
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230629_224924/"
AutoGluon Version:  0.8.1b20230629
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Disk Space Avail:   234.40 GB / 274.87 GB (85.3%)
Train Data Rows:    1000
Train Data Columns: 14
Label Column: class
Preprocessing data ...
AutoGluon infers your prediction problem is: 'binary' (because only two unique label-values observed).
	2 unique label values:  [' >50K', ' <=50K']
	If 'binary' 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'])
Selected class <--> label mapping:  class 1 =  >50K, class 0 =  <=50K
	Note: For your binary classification, AutoGluon arbitrarily selected which label-value represents positive ( >50K) vs negative ( <=50K) class.
	To explicitly set the positive_class, either rename classes to 1 and 0, or specify positive_class in Predictor init.
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
	Available Memory:                    30154.23 MB
	Train Data (Original)  Memory Usage: 0.59 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 1 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...
	Stage 5 Generators:
		Fitting DropDuplicatesFeatureGenerator...
	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', 'occupation', 'relationship', ...]
	Types of features in processed data (raw dtype, special dtypes):
		('category', [])  : 7 | ['workclass', 'education', 'marital-status', 'occupation', 'relationship', ...]
		('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
		('int', ['bool']) : 1 | ['sex']
	0.1s = Fit runtime
	14 features in original data used to generate 14 features in processed data.
	Train Data (Processed) Memory Usage: 0.06 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.11s ...
AutoGluon will gauge predictive performance using evaluation metric: 'accuracy'
	To change this, specify the eval_metric parameter of Predictor()
User-specified model hyperparameters to be fit:
{
	'NN_TORCH': {},
	'GBM': [{'extra_trees': True, 'ag_args': {'name_suffix': 'XT'}}, {}, 'GBMLarge'],
	'CAT': {},
	'XGB': {},
	'FASTAI': {},
	'RF': [{'criterion': 'gini', 'max_depth': 15, 'ag_args': {'name_suffix': 'Gini', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'entropy', 'max_depth': 15, 'ag_args': {'name_suffix': 'Entr', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'squared_error', 'max_depth': 15, 'ag_args': {'name_suffix': 'MSE', 'problem_types': ['regression', 'quantile']}}],
	'XT': [{'criterion': 'gini', 'max_depth': 15, 'ag_args': {'name_suffix': 'Gini', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'entropy', 'max_depth': 15, 'ag_args': {'name_suffix': 'Entr', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'squared_error', 'max_depth': 15, 'ag_args': {'name_suffix': 'MSE', 'problem_types': ['regression', 'quantile']}}],
}
Fitting 11 L1 models ...
Fitting model: LightGBMXT_BAG_L1 ... Training model for up to 29.89s of the 29.89s of remaining time.
	Fitting 8 child models (S1F1 - S1F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.859	 = Validation score   (accuracy)
	0.61s	 = Training   runtime
	0.05s	 = Validation runtime
Fitting model: LightGBM_BAG_L1 ... Training model for up to 26.11s of the 26.1s of remaining time.
	Fitting 8 child models (S1F1 - S1F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.859	 = Validation score   (accuracy)
	0.84s	 = Training   runtime
	0.06s	 = Validation runtime
Fitting model: RandomForestGini_BAG_L1 ... Training model for up to 21.64s of the 21.64s of remaining time.
	0.835	 = Validation score   (accuracy)
	0.51s	 = Training   runtime
	0.18s	 = Validation runtime
Fitting model: RandomForestEntr_BAG_L1 ... Training model for up to 20.92s of the 20.91s of remaining time.
	0.835	 = Validation score   (accuracy)
	0.57s	 = Training   runtime
	0.11s	 = Validation runtime
Fitting model: CatBoost_BAG_L1 ... Training model for up to 20.22s of the 20.22s of remaining time.
	Fitting 8 child models (S1F1 - S1F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.855	 = Validation score   (accuracy)
	4.31s	 = Training   runtime
	0.05s	 = Validation runtime
Fitting model: ExtraTreesGini_BAG_L1 ... Training model for up to 12.74s of the 12.74s of remaining time.
	0.831	 = Validation score   (accuracy)
	0.52s	 = Training   runtime
	0.11s	 = Validation runtime
Fitting model: ExtraTreesEntr_BAG_L1 ... Training model for up to 12.09s of the 12.09s of remaining time.
	0.828	 = Validation score   (accuracy)
	0.48s	 = Training   runtime
	0.11s	 = Validation runtime
Fitting model: NeuralNetFastAI_BAG_L1 ... Training model for up to 11.47s of the 11.47s of remaining time.
	Fitting 8 child models (S1F1 - S1F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.849	 = Validation score   (accuracy)
	4.33s	 = Training   runtime
	0.11s	 = Validation runtime
Fitting model: XGBoost_BAG_L1 ... Training model for up to 3.99s of the 3.99s of remaining time.
	Fitting 8 child models (S1F1 - S1F8) | Fitting with ParallelLocalFoldFittingStrategy
	0.858	 = Validation score   (accuracy)
	1.09s	 = Training   runtime
	0.08s	 = Validation runtime
Completed 1/20 k-fold bagging repeats ...
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.89s of the -0.91s of remaining time.
	0.86	 = Validation score   (accuracy)
	0.53s	 = Training   runtime
	0.0s	 = Validation runtime
AutoGluon training complete, total runtime = 31.47s ... 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.17s	 = Training   runtime
Fitting 1 L1 models ...
Fitting model: XGBoost_BAG_L1_FULL ...
	0.05s	 = Training   runtime
Fitting model: WeightedEnsemble_L2_FULL | Skipping fit via cloning parent ...
	0.53s	 = Training   runtime
Refit complete, total runtime = 0.26s
Deleting model LightGBMXT_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/LightGBMXT_BAG_L1/ will be removed.
Deleting model LightGBM_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/LightGBM_BAG_L1/ will be removed.
Deleting model RandomForestGini_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/RandomForestGini_BAG_L1/ will be removed.
Deleting model RandomForestEntr_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/RandomForestEntr_BAG_L1/ will be removed.
Deleting model CatBoost_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/CatBoost_BAG_L1/ will be removed.
Deleting model ExtraTreesGini_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/ExtraTreesGini_BAG_L1/ will be removed.
Deleting model ExtraTreesEntr_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/ExtraTreesEntr_BAG_L1/ will be removed.
Deleting model NeuralNetFastAI_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/NeuralNetFastAI_BAG_L1/ will be removed.
Deleting model XGBoost_BAG_L1. All files under AutogluonModels/ag-20230629_224924/models/XGBoost_BAG_L1/ will be removed.
Deleting model WeightedEnsemble_L2. All files under AutogluonModels/ag-20230629_224924/models/WeightedEnsemble_L2/ will be removed.
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230629_224924/")

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-20230629_224956/"
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230629_224956/"
AutoGluon Version:  0.8.1b20230629
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Disk Space Avail:   234.40 GB / 274.87 GB (85.3%)
Train Data Rows:    1000
Train Data Columns: 14
Label Column: class
Preprocessing data ...
AutoGluon infers your prediction problem is: 'binary' (because only two unique label-values observed).
	2 unique label values:  [' >50K', ' <=50K']
	If 'binary' 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'])
Selected class <--> label mapping:  class 1 =  >50K, class 0 =  <=50K
	Note: For your binary classification, AutoGluon arbitrarily selected which label-value represents positive ( >50K) vs negative ( <=50K) class.
	To explicitly set the positive_class, either rename classes to 1 and 0, or specify positive_class in Predictor init.
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
	Available Memory:                    29700.85 MB
	Train Data (Original)  Memory Usage: 0.59 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 1 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...
	Stage 5 Generators:
		Fitting DropDuplicatesFeatureGenerator...
	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', 'occupation', 'relationship', ...]
	Types of features in processed data (raw dtype, special dtypes):
		('category', [])  : 7 | ['workclass', 'education', 'marital-status', 'occupation', 'relationship', ...]
		('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
		('int', ['bool']) : 1 | ['sex']
	0.1s = Fit runtime
	14 features in original data used to generate 14 features in processed data.
	Train Data (Processed) Memory Usage: 0.06 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: 800, Val Rows: 200
User-specified model hyperparameters to be fit:
{
	'NN_TORCH': {},
	'GBM': [{'extra_trees': True, 'ag_args': {'name_suffix': 'XT'}}, {}, 'GBMLarge'],
	'CAT': {},
	'XGB': {},
	'FASTAI': {},
}
Fitting 7 L1 models ...
Fitting model: LightGBMXT ... Training model for up to 29.88s of the 29.88s of remaining time.
	0.85	 = Validation score   (accuracy)
	0.25s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: LightGBM ... Training model for up to 29.62s of the 29.62s of remaining time.
	0.84	 = Validation score   (accuracy)
	0.37s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: CatBoost ... Training model for up to 29.23s of the 29.23s of remaining time.
	0.86	 = Validation score   (accuracy)
	1.95s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: NeuralNetFastAI ... Training model for up to 27.27s of the 27.27s of remaining time.
No improvement since epoch 7: early stopping
	0.86	 = Validation score   (accuracy)
	0.89s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: XGBoost ... Training model for up to 26.35s of the 26.35s of remaining time.
	0.85	 = Validation score   (accuracy)
	0.22s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: NeuralNetTorch ... Training model for up to 26.12s of the 26.12s of remaining time.
	0.85	 = Validation score   (accuracy)
	2.28s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: LightGBMLarge ... Training model for up to 23.83s of the 23.83s of remaining time.
	0.815	 = Validation score   (accuracy)
	0.76s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.88s of the 23.03s of remaining time.
	0.86	 = Validation score   (accuracy)
	0.19s	 = Training   runtime
	0.0s	 = Validation runtime
AutoGluon training complete, total runtime = 7.19s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230629_224956/")

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 Networks):

excluded_model_types = ['KNN', 'NN_TORCH']
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-20230629_225003/"
Beginning AutoGluon training ... Time limit = 30s
AutoGluon will save models to "AutogluonModels/ag-20230629_225003/"
AutoGluon Version:  0.8.1b20230629
Python Version:     3.8.13
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
Disk Space Avail:   234.40 GB / 274.87 GB (85.3%)
Train Data Rows:    1000
Train Data Columns: 14
Label Column: class
Preprocessing data ...
AutoGluon infers your prediction problem is: 'binary' (because only two unique label-values observed).
	2 unique label values:  [' >50K', ' <=50K']
	If 'binary' 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'])
Selected class <--> label mapping:  class 1 =  >50K, class 0 =  <=50K
	Note: For your binary classification, AutoGluon arbitrarily selected which label-value represents positive ( >50K) vs negative ( <=50K) class.
	To explicitly set the positive_class, either rename classes to 1 and 0, or specify positive_class in Predictor init.
Using Feature Generators to preprocess the data ...
Fitting AutoMLPipelineFeatureGenerator...
	Available Memory:                    30107.27 MB
	Train Data (Original)  Memory Usage: 0.59 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 1 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...
	Stage 5 Generators:
		Fitting DropDuplicatesFeatureGenerator...
	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', 'occupation', 'relationship', ...]
	Types of features in processed data (raw dtype, special dtypes):
		('category', [])  : 7 | ['workclass', 'education', 'marital-status', 'occupation', 'relationship', ...]
		('int', [])       : 6 | ['age', 'fnlwgt', 'education-num', 'capital-gain', 'capital-loss', ...]
		('int', ['bool']) : 1 | ['sex']
	0.1s = Fit runtime
	14 features in original data used to generate 14 features in processed data.
	Train Data (Processed) Memory Usage: 0.06 MB (0.0% of available memory)
Data preprocessing and feature engineering runtime = 0.11s ...
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: 800, Val Rows: 200
User-specified model hyperparameters to be fit:
{
	'NN_TORCH': {},
	'GBM': [{'extra_trees': True, 'ag_args': {'name_suffix': 'XT'}}, {}, 'GBMLarge'],
	'CAT': {},
	'XGB': {},
	'FASTAI': {},
	'RF': [{'criterion': 'gini', 'ag_args': {'name_suffix': 'Gini', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'entropy', 'ag_args': {'name_suffix': 'Entr', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'squared_error', 'ag_args': {'name_suffix': 'MSE', 'problem_types': ['regression', 'quantile']}}],
	'XT': [{'criterion': 'gini', 'ag_args': {'name_suffix': 'Gini', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'entropy', 'ag_args': {'name_suffix': 'Entr', 'problem_types': ['binary', 'multiclass']}}, {'criterion': 'squared_error', 'ag_args': {'name_suffix': 'MSE', 'problem_types': ['regression', 'quantile']}}],
	'KNN': [{'weights': 'uniform', 'ag_args': {'name_suffix': 'Unif'}}, {'weights': 'distance', 'ag_args': {'name_suffix': 'Dist'}}],
}
Excluded models: ['KNN', 'NN_TORCH'] (Specified by `excluded_model_types`)
Fitting 10 L1 models ...
Fitting model: LightGBMXT ... Training model for up to 29.89s of the 29.89s of remaining time.
	0.85	 = Validation score   (accuracy)
	0.21s	 = Training   runtime
	0.0s	 = Validation runtime
Fitting model: LightGBM ... Training model for up to 29.67s of the 29.67s of remaining time.
	0.84	 = Validation score   (accuracy)
	0.27s	 = Training   runtime
	0.0s	 = Validation runtime
Fitting model: RandomForestGini ... Training model for up to 29.39s of the 29.39s of remaining time.
	0.84	 = Validation score   (accuracy)
	0.51s	 = Training   runtime
	0.07s	 = Validation runtime
Fitting model: RandomForestEntr ... Training model for up to 28.8s of the 28.79s of remaining time.
	0.835	 = Validation score   (accuracy)
	0.49s	 = Training   runtime
	0.06s	 = Validation runtime
Fitting model: CatBoost ... Training model for up to 28.23s of the 28.22s of remaining time.
	0.86	 = Validation score   (accuracy)
	1.81s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: ExtraTreesGini ... Training model for up to 26.4s of the 26.4s of remaining time.
	0.815	 = Validation score   (accuracy)
	0.48s	 = Training   runtime
	0.06s	 = Validation runtime
Fitting model: ExtraTreesEntr ... Training model for up to 25.85s of the 25.85s of remaining time.
	0.82	 = Validation score   (accuracy)
	0.49s	 = Training   runtime
	0.06s	 = Validation runtime
Fitting model: NeuralNetFastAI ... Training model for up to 25.28s of the 25.28s of remaining time.
No improvement since epoch 7: early stopping
	0.86	 = Validation score   (accuracy)
	0.9s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: XGBoost ... Training model for up to 24.36s of the 24.36s of remaining time.
	0.85	 = Validation score   (accuracy)
	0.22s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: LightGBMLarge ... Training model for up to 24.13s of the 24.13s of remaining time.
	0.815	 = Validation score   (accuracy)
	0.77s	 = Training   runtime
	0.01s	 = Validation runtime
Fitting model: WeightedEnsemble_L2 ... Training model for up to 29.89s of the 23.32s of remaining time.
	0.875	 = Validation score   (accuracy)
	0.31s	 = Training   runtime
	0.0s	 = Validation runtime
AutoGluon training complete, total runtime = 7.01s ... Best model: "WeightedEnsemble_L2"
TabularPredictor saved. To load, use: predictor = TabularPredictor.load("AutogluonModels/ag-20230629_225003/")

(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.