.. _sec_custom_advancedhpo:
Getting started with Advanced HPO Algorithms
============================================
This tutorial provides a complete example of how to use AutoGluon's
state-of-the-art hyperparameter optimization (HPO) algorithms to tune a
basic Multi-Layer Perceptron (MLP) model, which is the most basic type
of neural network.
Loading libraries
-----------------
.. code:: python
# Basic utils for folder manipulations etc
import time
import multiprocessing # to count the number of CPUs available
# External tools to load and process data
import numpy as np
import pandas as pd
# MXNet (NeuralNets)
import mxnet as mx
from mxnet import gluon, autograd
from mxnet.gluon import nn
# AutoGluon and HPO tools
import autogluon.core as ag
from autogluon.mxnet.utils import load_and_split_openml_data
Check the version of MxNet, you should be fine with version >= 1.5
.. code:: python
mx.__version__
.. parsed-literal::
:class: output
'1.7.0'
You can also check the version of AutoGluon and the specific commit and
check that it matches what you want.
.. code:: python
import autogluon.core.version
ag.version.__version__
.. parsed-literal::
:class: output
'0.1.0b20210224'
Hyperparameter Optimization of a 2-layer MLP
--------------------------------------------
Setting up the context
~~~~~~~~~~~~~~~~~~~~~~
Here we declare a few "environment variables" setting the context for
what we're doing
.. code:: python
OPENML_TASK_ID = 6 # describes the problem we will tackle
RATIO_TRAIN_VALID = 0.33 # split of the training data used for validation
RESOURCE_ATTR_NAME = 'epoch' # how do we measure resources (will become clearer further)
REWARD_ATTR_NAME = 'objective' # how do we measure performance (will become clearer further)
NUM_CPUS = multiprocessing.cpu_count()
Preparing the data
~~~~~~~~~~~~~~~~~~
We will use a multi-way classification task from OpenML. Data
preparation includes:
- Missing values are imputed, using the 'mean' strategy of
``sklearn.impute.SimpleImputer``
- Split training set into training and validation
- Standardize inputs to mean 0, variance 1
.. code:: python
X_train, X_valid, y_train, y_valid, n_classes = load_and_split_openml_data(
OPENML_TASK_ID, RATIO_TRAIN_VALID, download_from_openml=False)
n_classes
.. parsed-literal::
:class: output
100%|██████████| 704/704 [00:00<00:00, 34971.16KB/s]
100%|██████████| 2521/2521 [00:00<00:00, 11286.95KB/s]
3KB [00:00, 4398.08KB/s]
8KB [00:00, 12056.93KB/s]
15KB [00:00, 12370.15KB/s]
2998KB [00:00, 23933.10KB/s]
881KB [00:00, 48962.26KB/s]
3KB [00:00, 4228.13KB/s]
.. parsed-literal::
:class: output
26
The problem has 26 classes.
Declaring a model specifying a hyperparameter space with AutoGluon
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Two layer MLP where we optimize over:
- the number of units on the first layer
- the number of units on the second layer
- the dropout rate after each layer
- the learning rate
- the scaling
- the ``@ag.args`` decorator allows us to specify the space we will
optimize over, this matches the
`ConfigSpace `__ syntax
The body of the function ``run_mlp_openml`` is pretty simple:
- it reads the hyperparameters given via the decorator
- it defines a 2 layer MLP with dropout
- it declares a trainer with the 'adam' loss function and a provided
learning rate
- it trains the NN with a number of epochs (most of that is boilerplate
code from ``mxnet``)
- the ``reporter`` at the end is used to keep track of training history
in the hyperparameter optimization
**Note**: The number of epochs and the hyperparameter space are reduced
to make for a shorter experiment
.. code:: python
@ag.args(n_units_1=ag.space.Int(lower=16, upper=128),
n_units_2=ag.space.Int(lower=16, upper=128),
dropout_1=ag.space.Real(lower=0, upper=.75),
dropout_2=ag.space.Real(lower=0, upper=.75),
learning_rate=ag.space.Real(lower=1e-6, upper=1, log=True),
batch_size=ag.space.Int(lower=8, upper=128),
scale_1=ag.space.Real(lower=0.001, upper=10, log=True),
scale_2=ag.space.Real(lower=0.001, upper=10, log=True),
epochs=9)
def run_mlp_openml(args, reporter, **kwargs):
# Time stamp for elapsed_time
ts_start = time.time()
# Unwrap hyperparameters
n_units_1 = args.n_units_1
n_units_2 = args.n_units_2
dropout_1 = args.dropout_1
dropout_2 = args.dropout_2
scale_1 = args.scale_1
scale_2 = args.scale_2
batch_size = args.batch_size
learning_rate = args.learning_rate
ctx = mx.cpu()
net = nn.Sequential()
with net.name_scope():
# Layer 1
net.add(nn.Dense(n_units_1, activation='relu',
weight_initializer=mx.initializer.Uniform(scale=scale_1)))
# Dropout
net.add(gluon.nn.Dropout(dropout_1))
# Layer 2
net.add(nn.Dense(n_units_2, activation='relu',
weight_initializer=mx.initializer.Uniform(scale=scale_2)))
# Dropout
net.add(gluon.nn.Dropout(dropout_2))
# Output
net.add(nn.Dense(n_classes))
net.initialize(ctx=ctx)
trainer = gluon.Trainer(net.collect_params(), 'adam',
{'learning_rate': learning_rate})
for epoch in range(args.epochs):
ts_epoch = time.time()
train_iter = mx.io.NDArrayIter(
data={'data': X_train},
label={'label': y_train},
batch_size=batch_size,
shuffle=True)
valid_iter = mx.io.NDArrayIter(
data={'data': X_valid},
label={'label': y_valid},
batch_size=batch_size,
shuffle=False)
metric = mx.metric.Accuracy()
loss = gluon.loss.SoftmaxCrossEntropyLoss()
for batch in train_iter:
data = batch.data[0].as_in_context(ctx)
label = batch.label[0].as_in_context(ctx)
with autograd.record():
output = net(data)
L = loss(output, label)
L.backward()
trainer.step(data.shape[0])
metric.update([label], [output])
name, train_acc = metric.get()
metric = mx.metric.Accuracy()
for batch in valid_iter:
data = batch.data[0].as_in_context(ctx)
label = batch.label[0].as_in_context(ctx)
output = net(data)
metric.update([label], [output])
name, val_acc = metric.get()
print('Epoch %d ; Time: %f ; Training: %s=%f ; Validation: %s=%f' % (
epoch + 1, time.time() - ts_start, name, train_acc, name, val_acc))
ts_now = time.time()
eval_time = ts_now - ts_epoch
elapsed_time = ts_now - ts_start
# The resource reported back (as 'epoch') is the number of epochs
# done, starting at 1
reporter(
epoch=epoch + 1,
objective=float(val_acc),
eval_time=eval_time,
time_step=ts_now,
elapsed_time=elapsed_time)
**Note**: The annotation ``epochs=9`` specifies the maximum number of
epochs for training. It becomes available as ``args.epochs``.
Importantly, it is also processed by ``HyperbandScheduler`` below in
order to set its ``max_t`` attribute.
**Recommendation**: Whenever writing training code to be passed as
``train_fn`` to a scheduler, if this training code reports a resource
(or time) attribute, the corresponding maximum resource value should be
included in ``train_fn.args``:
- If the resource attribute (``time_attr`` of scheduler) in
``train_fn`` is ``epoch``, make sure to include ``epochs=XYZ`` in the
annotation. This allows the scheduler to read ``max_t`` from
``train_fn.args.epochs``. This case corresponds to our example here.
- If the resource attribute is something else than ``epoch``, you can
also include the annotation ``max_t=XYZ``, which allows the scheduler
to read ``max_t`` from ``train_fn.args.max_t``.
Annotating the training function by the correct value for ``max_t``
simplifies scheduler creation (since ``max_t`` does not have to be
passed), and avoids inconsistencies between ``train_fn`` and the
scheduler.
Running the Hyperparameter Optimization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the following schedulers:
- FIFO (``fifo``)
- Hyperband (either the stopping (``hbs``) or promotion (``hbp``)
variant)
And the following searchers:
- Random search (``random``)
- Gaussian process based Bayesian optimization (``bayesopt``)
- SkOpt Bayesian optimization (``skopt``; only with FIFO scheduler)
Note that the method known as (asynchronous) Hyperband is using random
search. Combining Hyperband scheduling with the ``bayesopt`` searcher
uses a novel method called asynchronous BOHB.
Pick the combination you're interested in (doing the full experiment
takes around 120 seconds, see the ``time_out`` parameter), running
everything with multiple runs can take a fair bit of time. In real life,
you will want to choose a larger ``time_out`` in order to obtain good
performance.
.. code:: python
SCHEDULER = "hbs"
SEARCHER = "bayesopt"
.. code:: python
def compute_error(df):
return 1.0 - df["objective"]
def compute_runtime(df, start_timestamp):
return df["time_step"] - start_timestamp
def process_training_history(task_dicts, start_timestamp,
runtime_fn=compute_runtime,
error_fn=compute_error):
task_dfs = []
for task_id in task_dicts:
task_df = pd.DataFrame(task_dicts[task_id])
task_df = task_df.assign(task_id=task_id,
runtime=runtime_fn(task_df, start_timestamp),
error=error_fn(task_df),
target_epoch=task_df["epoch"].iloc[-1])
task_dfs.append(task_df)
result = pd.concat(task_dfs, axis="index", ignore_index=True, sort=True)
# re-order by runtime
result = result.sort_values(by="runtime")
# calculate incumbent best -- the cumulative minimum of the error.
result = result.assign(best=result["error"].cummin())
return result
resources = dict(num_cpus=NUM_CPUS, num_gpus=0)
.. code:: python
search_options = {
'num_init_random': 2,
'debug_log': True}
if SCHEDULER == 'fifo':
myscheduler = ag.scheduler.FIFOScheduler(
run_mlp_openml,
resource=resources,
searcher=SEARCHER,
search_options=search_options,
time_out=120,
time_attr=RESOURCE_ATTR_NAME,
reward_attr=REWARD_ATTR_NAME)
else:
# This setup uses rung levels at 1, 3, 9 epochs. We just use a single
# bracket, so this is in fact successive halving (Hyperband would use
# more than 1 bracket).
# Also note that since we do not use the max_t argument of
# HyperbandScheduler, this value is obtained from train_fn.args.epochs.
sch_type = 'stopping' if SCHEDULER == 'hbs' else 'promotion'
myscheduler = ag.scheduler.HyperbandScheduler(
run_mlp_openml,
resource=resources,
searcher=SEARCHER,
search_options=search_options,
time_out=120,
time_attr=RESOURCE_ATTR_NAME,
reward_attr=REWARD_ATTR_NAME,
type=sch_type,
grace_period=1,
reduction_factor=3,
brackets=1)
# run tasks
myscheduler.run()
myscheduler.join_jobs()
results_df = process_training_history(
myscheduler.training_history.copy(),
start_timestamp=myscheduler._start_time)
.. parsed-literal::
:class: output
/var/lib/jenkins/workspace/workspace/autogluon-tutorial-course-v3/venv/lib/python3.8/site-packages/distributed/worker.py:3451: UserWarning: Large object of size 1.30 MB detected in task graph:
(0, , { ... sReporter}, [])
Consider scattering large objects ahead of time
with client.scatter to reduce scheduler burden and
keep data on workers
future = client.submit(func, big_data) # bad
big_future = client.scatter(big_data) # good
future = client.submit(func, big_future) # good
warnings.warn(
.. parsed-literal::
:class: output
Epoch 1 ; Time: 0.501428 ; Training: accuracy=0.260079 ; Validation: accuracy=0.531250
Epoch 2 ; Time: 0.927829 ; Training: accuracy=0.496365 ; Validation: accuracy=0.655247
Epoch 3 ; Time: 1.340136 ; Training: accuracy=0.559650 ; Validation: accuracy=0.694686
Epoch 4 ; Time: 1.753211 ; Training: accuracy=0.588896 ; Validation: accuracy=0.711063
Epoch 5 ; Time: 2.168135 ; Training: accuracy=0.609385 ; Validation: accuracy=0.726939
Epoch 6 ; Time: 2.633001 ; Training: accuracy=0.628139 ; Validation: accuracy=0.745321
Epoch 7 ; Time: 3.104744 ; Training: accuracy=0.641193 ; Validation: accuracy=0.750501
Epoch 8 ; Time: 3.582661 ; Training: accuracy=0.653751 ; Validation: accuracy=0.763202
Epoch 9 ; Time: 4.002226 ; Training: accuracy=0.665482 ; Validation: accuracy=0.766043
Epoch 1 ; Time: 0.920221 ; Training: accuracy=0.271154 ; Validation: accuracy=0.443771
Epoch 1 ; Time: 0.354071 ; Training: accuracy=0.045066 ; Validation: accuracy=0.045047
Epoch 1 ; Time: 0.612909 ; Training: accuracy=0.038997 ; Validation: accuracy=0.046671
Epoch 1 ; Time: 1.098973 ; Training: accuracy=0.045658 ; Validation: accuracy=0.035450
Epoch 1 ; Time: 0.378468 ; Training: accuracy=0.040652 ; Validation: accuracy=0.036634
Epoch 1 ; Time: 2.718110 ; Training: accuracy=0.282589 ; Validation: accuracy=0.425758
Epoch 2 ; Time: 5.402659 ; Training: accuracy=0.345902 ; Validation: accuracy=0.548485
Epoch 3 ; Time: 8.251918 ; Training: accuracy=0.355929 ; Validation: accuracy=0.511279
Epoch 1 ; Time: 0.352776 ; Training: accuracy=0.142408 ; Validation: accuracy=0.183016
Epoch 1 ; Time: 0.664635 ; Training: accuracy=0.444048 ; Validation: accuracy=0.599331
Epoch 2 ; Time: 1.269985 ; Training: accuracy=0.567225 ; Validation: accuracy=0.672575
Epoch 3 ; Time: 1.825110 ; Training: accuracy=0.588694 ; Validation: accuracy=0.694147
Epoch 4 ; Time: 2.358906 ; Training: accuracy=0.618700 ; Validation: accuracy=0.707525
Epoch 5 ; Time: 2.880280 ; Training: accuracy=0.624503 ; Validation: accuracy=0.706689
Epoch 6 ; Time: 3.423817 ; Training: accuracy=0.636356 ; Validation: accuracy=0.725920
Epoch 7 ; Time: 3.971068 ; Training: accuracy=0.650365 ; Validation: accuracy=0.734950
Epoch 8 ; Time: 4.567538 ; Training: accuracy=0.665948 ; Validation: accuracy=0.740970
Epoch 9 ; Time: 5.179614 ; Training: accuracy=0.661887 ; Validation: accuracy=0.750836
Epoch 1 ; Time: 1.618978 ; Training: accuracy=0.036318 ; Validation: accuracy=0.038552
Epoch 1 ; Time: 0.631645 ; Training: accuracy=0.422562 ; Validation: accuracy=0.676134
Epoch 2 ; Time: 1.199739 ; Training: accuracy=0.523967 ; Validation: accuracy=0.716807
Epoch 3 ; Time: 1.771595 ; Training: accuracy=0.547521 ; Validation: accuracy=0.709580
Epoch 4 ; Time: 2.350334 ; Training: accuracy=0.559835 ; Validation: accuracy=0.723866
Epoch 5 ; Time: 2.924589 ; Training: accuracy=0.580826 ; Validation: accuracy=0.728739
Epoch 6 ; Time: 3.560243 ; Training: accuracy=0.589008 ; Validation: accuracy=0.757479
Epoch 7 ; Time: 4.141949 ; Training: accuracy=0.585041 ; Validation: accuracy=0.754286
Epoch 8 ; Time: 4.742064 ; Training: accuracy=0.588430 ; Validation: accuracy=0.753109
Epoch 9 ; Time: 5.323142 ; Training: accuracy=0.609339 ; Validation: accuracy=0.752101
Epoch 1 ; Time: 0.348901 ; Training: accuracy=0.083554 ; Validation: accuracy=0.060438
Epoch 1 ; Time: 0.550358 ; Training: accuracy=0.040368 ; Validation: accuracy=0.033478
Epoch 1 ; Time: 0.421942 ; Training: accuracy=0.326778 ; Validation: accuracy=0.625708
Epoch 2 ; Time: 0.779967 ; Training: accuracy=0.442122 ; Validation: accuracy=0.680986
Epoch 3 ; Time: 1.137134 ; Training: accuracy=0.471949 ; Validation: accuracy=0.682651
Epoch 1 ; Time: 0.376085 ; Training: accuracy=0.451456 ; Validation: accuracy=0.705557
Epoch 2 ; Time: 0.693395 ; Training: accuracy=0.575613 ; Validation: accuracy=0.695347
Epoch 3 ; Time: 1.009008 ; Training: accuracy=0.588695 ; Validation: accuracy=0.683964
Epoch 1 ; Time: 0.637191 ; Training: accuracy=0.102950 ; Validation: accuracy=0.183339
Epoch 1 ; Time: 0.330724 ; Training: accuracy=0.255921 ; Validation: accuracy=0.496343
Epoch 2 ; Time: 0.591566 ; Training: accuracy=0.431743 ; Validation: accuracy=0.590426
Epoch 3 ; Time: 0.876340 ; Training: accuracy=0.490461 ; Validation: accuracy=0.632812
Epoch 1 ; Time: 0.418901 ; Training: accuracy=0.411633 ; Validation: accuracy=0.682151
Epoch 2 ; Time: 0.740164 ; Training: accuracy=0.630340 ; Validation: accuracy=0.740593
Epoch 3 ; Time: 1.064412 ; Training: accuracy=0.675370 ; Validation: accuracy=0.768731
Epoch 4 ; Time: 1.385570 ; Training: accuracy=0.696274 ; Validation: accuracy=0.787379
Epoch 5 ; Time: 1.703562 ; Training: accuracy=0.713955 ; Validation: accuracy=0.803530
Epoch 6 ; Time: 2.022915 ; Training: accuracy=0.719078 ; Validation: accuracy=0.814186
Epoch 7 ; Time: 2.342436 ; Training: accuracy=0.731306 ; Validation: accuracy=0.818182
Epoch 8 ; Time: 2.655205 ; Training: accuracy=0.739651 ; Validation: accuracy=0.824675
Epoch 9 ; Time: 2.976654 ; Training: accuracy=0.745105 ; Validation: accuracy=0.821012
Epoch 1 ; Time: 0.568247 ; Training: accuracy=0.284332 ; Validation: accuracy=0.640879
Epoch 2 ; Time: 1.057711 ; Training: accuracy=0.422489 ; Validation: accuracy=0.690888
Epoch 3 ; Time: 1.538753 ; Training: accuracy=0.466970 ; Validation: accuracy=0.714717
Epoch 4 ; Time: 2.017047 ; Training: accuracy=0.477305 ; Validation: accuracy=0.720759
Epoch 5 ; Time: 2.499402 ; Training: accuracy=0.493262 ; Validation: accuracy=0.713207
Epoch 6 ; Time: 2.978205 ; Training: accuracy=0.499215 ; Validation: accuracy=0.723947
Epoch 7 ; Time: 3.475100 ; Training: accuracy=0.514924 ; Validation: accuracy=0.727807
Epoch 8 ; Time: 3.956110 ; Training: accuracy=0.513683 ; Validation: accuracy=0.727303
Epoch 9 ; Time: 4.434170 ; Training: accuracy=0.523687 ; Validation: accuracy=0.739386
Epoch 1 ; Time: 0.300867 ; Training: accuracy=0.145724 ; Validation: accuracy=0.513132
Epoch 1 ; Time: 0.633698 ; Training: accuracy=0.133284 ; Validation: accuracy=0.388135
Epoch 1 ; Time: 0.380906 ; Training: accuracy=0.203834 ; Validation: accuracy=0.487845
Epoch 1 ; Time: 0.304531 ; Training: accuracy=0.106250 ; Validation: accuracy=0.178358
Epoch 1 ; Time: 0.311316 ; Training: accuracy=0.414824 ; Validation: accuracy=0.701003
Epoch 2 ; Time: 0.600304 ; Training: accuracy=0.626584 ; Validation: accuracy=0.752676
Epoch 3 ; Time: 0.855273 ; Training: accuracy=0.670311 ; Validation: accuracy=0.784950
Epoch 4 ; Time: 1.170644 ; Training: accuracy=0.711553 ; Validation: accuracy=0.810033
Epoch 5 ; Time: 1.421779 ; Training: accuracy=0.737226 ; Validation: accuracy=0.830936
Epoch 6 ; Time: 1.670517 ; Training: accuracy=0.757350 ; Validation: accuracy=0.839967
Epoch 7 ; Time: 1.920087 ; Training: accuracy=0.772257 ; Validation: accuracy=0.855686
Epoch 8 ; Time: 2.179702 ; Training: accuracy=0.776646 ; Validation: accuracy=0.866388
Epoch 9 ; Time: 2.447286 ; Training: accuracy=0.792050 ; Validation: accuracy=0.872575
Epoch 1 ; Time: 0.397302 ; Training: accuracy=0.358558 ; Validation: accuracy=0.606426
Epoch 2 ; Time: 0.761423 ; Training: accuracy=0.656296 ; Validation: accuracy=0.707162
Epoch 3 ; Time: 1.108681 ; Training: accuracy=0.733042 ; Validation: accuracy=0.769076
Epoch 4 ; Time: 1.447953 ; Training: accuracy=0.773725 ; Validation: accuracy=0.803715
Epoch 5 ; Time: 1.781177 ; Training: accuracy=0.801205 ; Validation: accuracy=0.822959
Epoch 6 ; Time: 2.155372 ; Training: accuracy=0.826622 ; Validation: accuracy=0.835843
Epoch 7 ; Time: 2.515275 ; Training: accuracy=0.840238 ; Validation: accuracy=0.851908
Epoch 8 ; Time: 2.888833 ; Training: accuracy=0.859383 ; Validation: accuracy=0.867135
Epoch 9 ; Time: 3.239732 ; Training: accuracy=0.868460 ; Validation: accuracy=0.876841
Epoch 1 ; Time: 0.564663 ; Training: accuracy=0.101025 ; Validation: accuracy=0.170699
Epoch 1 ; Time: 0.291451 ; Training: accuracy=0.367434 ; Validation: accuracy=0.627992
Epoch 2 ; Time: 0.523886 ; Training: accuracy=0.537171 ; Validation: accuracy=0.725399
Epoch 3 ; Time: 0.750020 ; Training: accuracy=0.586760 ; Validation: accuracy=0.749003
Epoch 4 ; Time: 0.982082 ; Training: accuracy=0.610773 ; Validation: accuracy=0.767453
Epoch 5 ; Time: 1.211215 ; Training: accuracy=0.642105 ; Validation: accuracy=0.781582
Epoch 6 ; Time: 1.444432 ; Training: accuracy=0.654934 ; Validation: accuracy=0.803025
Epoch 7 ; Time: 1.668773 ; Training: accuracy=0.663405 ; Validation: accuracy=0.786237
Epoch 8 ; Time: 1.895919 ; Training: accuracy=0.681250 ; Validation: accuracy=0.824136
Epoch 9 ; Time: 2.221158 ; Training: accuracy=0.697451 ; Validation: accuracy=0.800864
Epoch 1 ; Time: 0.691166 ; Training: accuracy=0.409061 ; Validation: accuracy=0.644657
Epoch 2 ; Time: 1.289294 ; Training: accuracy=0.623347 ; Validation: accuracy=0.729503
Epoch 3 ; Time: 1.900382 ; Training: accuracy=0.686425 ; Validation: accuracy=0.771673
Epoch 4 ; Time: 2.599052 ; Training: accuracy=0.716766 ; Validation: accuracy=0.786290
Epoch 5 ; Time: 3.277293 ; Training: accuracy=0.742146 ; Validation: accuracy=0.807964
Epoch 6 ; Time: 3.935235 ; Training: accuracy=0.759011 ; Validation: accuracy=0.823421
Epoch 7 ; Time: 4.589851 ; Training: accuracy=0.773892 ; Validation: accuracy=0.835349
Epoch 8 ; Time: 5.233963 ; Training: accuracy=0.786045 ; Validation: accuracy=0.849462
Epoch 9 ; Time: 5.910367 ; Training: accuracy=0.792328 ; Validation: accuracy=0.856351
Epoch 1 ; Time: 0.288102 ; Training: accuracy=0.405139 ; Validation: accuracy=0.701793
Epoch 2 ; Time: 0.520498 ; Training: accuracy=0.622379 ; Validation: accuracy=0.768805
Epoch 3 ; Time: 0.757052 ; Training: accuracy=0.675673 ; Validation: accuracy=0.787234
Epoch 4 ; Time: 0.990964 ; Training: accuracy=0.702942 ; Validation: accuracy=0.807673
Epoch 5 ; Time: 1.214895 ; Training: accuracy=0.716038 ; Validation: accuracy=0.819233
Epoch 6 ; Time: 1.439561 ; Training: accuracy=0.735930 ; Validation: accuracy=0.834143
Epoch 7 ; Time: 1.666994 ; Training: accuracy=0.743722 ; Validation: accuracy=0.846708
Epoch 8 ; Time: 1.908782 ; Training: accuracy=0.752176 ; Validation: accuracy=0.852739
Epoch 9 ; Time: 2.175746 ; Training: accuracy=0.755574 ; Validation: accuracy=0.851734
Epoch 1 ; Time: 0.384220 ; Training: accuracy=0.418733 ; Validation: accuracy=0.717406
Epoch 2 ; Time: 0.689044 ; Training: accuracy=0.598876 ; Validation: accuracy=0.777218
Epoch 3 ; Time: 0.990826 ; Training: accuracy=0.648727 ; Validation: accuracy=0.795027
Epoch 4 ; Time: 1.283572 ; Training: accuracy=0.673280 ; Validation: accuracy=0.820060
Epoch 5 ; Time: 1.578003 ; Training: accuracy=0.701802 ; Validation: accuracy=0.832157
Epoch 6 ; Time: 1.870872 ; Training: accuracy=0.715112 ; Validation: accuracy=0.847110
Epoch 7 ; Time: 2.225747 ; Training: accuracy=0.733383 ; Validation: accuracy=0.857023
Epoch 8 ; Time: 2.548026 ; Training: accuracy=0.745949 ; Validation: accuracy=0.867776
Epoch 9 ; Time: 2.934313 ; Training: accuracy=0.743882 ; Validation: accuracy=0.858535
Epoch 1 ; Time: 0.510480 ; Training: accuracy=0.623262 ; Validation: accuracy=0.791667
Epoch 2 ; Time: 0.878617 ; Training: accuracy=0.746523 ; Validation: accuracy=0.837833
Epoch 3 ; Time: 1.245148 ; Training: accuracy=0.775993 ; Validation: accuracy=0.863833
Epoch 4 ; Time: 1.604610 ; Training: accuracy=0.792964 ; Validation: accuracy=0.878500
Epoch 5 ; Time: 2.042608 ; Training: accuracy=0.814983 ; Validation: accuracy=0.886000
Epoch 6 ; Time: 2.405598 ; Training: accuracy=0.819950 ; Validation: accuracy=0.877667
Epoch 7 ; Time: 2.781806 ; Training: accuracy=0.822599 ; Validation: accuracy=0.880000
Epoch 8 ; Time: 3.150146 ; Training: accuracy=0.832368 ; Validation: accuracy=0.875167
Epoch 9 ; Time: 3.502203 ; Training: accuracy=0.837748 ; Validation: accuracy=0.899000
Epoch 1 ; Time: 0.310339 ; Training: accuracy=0.645217 ; Validation: accuracy=0.791806
Epoch 2 ; Time: 0.567796 ; Training: accuracy=0.814990 ; Validation: accuracy=0.843478
Epoch 3 ; Time: 0.850517 ; Training: accuracy=0.846377 ; Validation: accuracy=0.860368
Epoch 4 ; Time: 1.100746 ; Training: accuracy=0.865921 ; Validation: accuracy=0.879097
Epoch 5 ; Time: 1.365263 ; Training: accuracy=0.877847 ; Validation: accuracy=0.886120
Epoch 6 ; Time: 1.610470 ; Training: accuracy=0.885052 ; Validation: accuracy=0.890635
Epoch 7 ; Time: 1.855182 ; Training: accuracy=0.896480 ; Validation: accuracy=0.895151
Epoch 8 ; Time: 2.103321 ; Training: accuracy=0.899793 ; Validation: accuracy=0.905853
Epoch 9 ; Time: 2.353834 ; Training: accuracy=0.902112 ; Validation: accuracy=0.901171
Epoch 1 ; Time: 0.635832 ; Training: accuracy=0.282077 ; Validation: accuracy=0.614310
Epoch 1 ; Time: 0.288144 ; Training: accuracy=0.273931 ; Validation: accuracy=0.592088
Epoch 1 ; Time: 3.987203 ; Training: accuracy=0.629559 ; Validation: accuracy=0.783647
Epoch 2 ; Time: 8.175726 ; Training: accuracy=0.776442 ; Validation: accuracy=0.844886
Epoch 3 ; Time: 12.323493 ; Training: accuracy=0.821452 ; Validation: accuracy=0.870121
Epoch 4 ; Time: 16.648568 ; Training: accuracy=0.836704 ; Validation: accuracy=0.881561
Epoch 5 ; Time: 20.911560 ; Training: accuracy=0.850464 ; Validation: accuracy=0.902423
Epoch 6 ; Time: 25.113778 ; Training: accuracy=0.858256 ; Validation: accuracy=0.901750
Epoch 7 ; Time: 29.231350 ; Training: accuracy=0.871601 ; Validation: accuracy=0.897880
Epoch 8 ; Time: 33.995565 ; Training: accuracy=0.873591 ; Validation: accuracy=0.908479
Epoch 9 ; Time: 38.424927 ; Training: accuracy=0.880056 ; Validation: accuracy=0.915209
Analysing the results
~~~~~~~~~~~~~~~~~~~~~
The training history is stored in the ``results_df``, the main fields
are the runtime and ``'best'`` (the objective).
**Note**: You will get slightly different curves for different pairs of
scheduler/searcher, the ``time_out`` here is a bit too short to really
see the difference in a significant way (it would be better to set it to
>1000s). Generally speaking though, hyperband stopping / promotion +
model will tend to significantly outperform other combinations given
enough time.
.. code:: python
results_df.head()
.. raw:: html
|
bracket |
elapsed_time |
epoch |
error |
eval_time |
objective |
runtime |
searcher_data_size |
searcher_params_kernel_covariance_scale |
searcher_params_kernel_inv_bw0 |
... |
searcher_params_kernel_inv_bw7 |
searcher_params_kernel_inv_bw8 |
searcher_params_mean_mean_value |
searcher_params_noise_variance |
target_epoch |
task_id |
time_since_start |
time_step |
time_this_iter |
best |
| 0 |
0 |
0.503835 |
1 |
0.468750 |
0.498833 |
0.531250 |
0.794780 |
NaN |
1.0 |
1.0 |
... |
1.0 |
1.0 |
0.0 |
0.001 |
9 |
0 |
0.797088 |
1.614126e+09 |
0.533082 |
0.468750 |
| 1 |
0 |
0.929302 |
2 |
0.344753 |
0.420733 |
0.655247 |
1.220247 |
1.0 |
1.0 |
1.0 |
... |
1.0 |
1.0 |
0.0 |
0.001 |
9 |
0 |
1.221023 |
1.614126e+09 |
0.425449 |
0.344753 |
| 2 |
0 |
1.341724 |
3 |
0.305314 |
0.410199 |
0.694686 |
1.632669 |
1.0 |
1.0 |
1.0 |
... |
1.0 |
1.0 |
0.0 |
0.001 |
9 |
0 |
1.633596 |
1.614126e+09 |
0.412425 |
0.305314 |
| 3 |
0 |
1.754769 |
4 |
0.288937 |
0.410367 |
0.711063 |
2.045714 |
2.0 |
1.0 |
1.0 |
... |
1.0 |
1.0 |
0.0 |
0.001 |
9 |
0 |
2.046513 |
1.614126e+09 |
0.413044 |
0.288937 |
| 4 |
0 |
2.169484 |
5 |
0.273061 |
0.412882 |
0.726939 |
2.460428 |
2.0 |
1.0 |
1.0 |
... |
1.0 |
1.0 |
0.0 |
0.001 |
9 |
0 |
2.461493 |
1.614126e+09 |
0.414714 |
0.273061 |
5 rows × 26 columns
.. code:: python
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 8))
runtime = results_df['runtime'].values
objective = results_df['best'].values
plt.plot(runtime, objective, lw=2)
plt.xticks(fontsize=12)
plt.xlim(0, 120)
plt.ylim(0, 0.5)
plt.yticks(fontsize=12)
plt.xlabel("Runtime [s]", fontsize=14)
plt.ylabel("Objective", fontsize=14)
.. parsed-literal::
:class: output
Text(0, 0.5, 'Objective')
Diving Deeper
-------------
Now, you are ready to try HPO on your own machine learning models (if
you use PyTorch, have a look at :ref:`sec_customstorch`). While
AutoGluon comes with well-chosen defaults, it can pay off to tune it to
your specific needs. Here are some tips which may come useful.
Logging the Search Progress
~~~~~~~~~~~~~~~~~~~~~~~~~~~
First, it is a good idea in general to switch on ``debug_log``, which
outputs useful information about the search progress. This is already
done in the example above.
The outputs show which configurations are chosen, stopped, or promoted.
For BO and BOHB, a range of information is displayed for every
``get_config`` decision. This log output is very useful in order to
figure out what is going on during the search.
Configuring ``HyperbandScheduler``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The most important knobs to turn with ``HyperbandScheduler`` are
``max_t``, ``grace_period``, ``reduction_factor``, ``brackets``, and
``type``. The first three determine the rung levels at which stopping or
promotion decisions are being made.
- The maximum resource level ``max_t`` (usually, resource equates to
epochs, so ``max_t`` is the maximum number of training epochs) is
typically hardcoded in ``train_fn`` passed to the scheduler (this is
``run_mlp_openml`` in the example above). As already noted above, the
value is best fixed in the ``ag.args`` decorator as ``epochs=XYZ``,
it can then be accessed as ``args.epochs`` in the ``train_fn`` code.
If this is done, you do not have to pass ``max_t`` when creating the
scheduler.
- ``grace_period`` and ``reduction_factor`` determine the rung levels,
which are ``grace_period``, ``grace_period * reduction_factor``,
``grace_period * (reduction_factor ** 2)``, etc. All rung levels must
be less or equal than ``max_t``. It is recommended to make ``max_t``
equal to the largest rung level. For example, if
``grace_period = 1``, ``reduction_factor = 3``, it is in general
recommended to use ``max_t = 9``, ``max_t = 27``, or ``max_t = 81``.
Choosing a ``max_t`` value "off the grid" works against the
successive halving principle that the total resources spent in a rung
should be roughly equal between rungs. If in the example above, you
set ``max_t = 10``, about a third of configurations reaching 9 epochs
are allowed to proceed, but only for one more epoch.
- With ``reduction_factor``, you tune the extent to which successive
halving filtering is applied. The larger this integer, the fewer
configurations make it to higher number of epochs. Values 2, 3, 4 are
commonly used.
- Finally, ``grace_period`` should be set to the smallest resource
(number of epochs) for which you expect any meaningful
differentiation between configurations. While ``grace_period = 1``
should always be explored, it may be too low for any meaningful
stopping decisions to be made at the first rung.
- ``brackets`` sets the maximum number of brackets in Hyperband (make
sure to study the Hyperband paper or follow-ups for details). For
``brackets = 1``, you are running successive halving (single
bracket). Higher brackets have larger effective ``grace_period``
values (so runs are not stopped until later), yet are also chosen
with less probability. We recommend to always consider successive
halving (``brackets = 1``) in a comparison.
- Finally, with ``type`` (values ``stopping``, ``promotion``) you are
choosing different ways of extending successive halving scheduling to
the asynchronous case. The method for the default ``stopping`` is
simpler and seems to perform well, but ``promotion`` is more careful
promoting configurations to higher resource levels, which can work
better in some cases.
Asynchronous BOHB
~~~~~~~~~~~~~~~~~
Finally, here are some ideas for tuning asynchronous BOHB, apart from
tuning its ``HyperbandScheduling`` component. You need to pass these
options in ``search_options``.
- We support a range of different surrogate models over the criterion
functions across resource levels. All of them are jointly dependent
Gaussian process models, meaning that data collected at all resource
levels are modelled together. The surrogate model is selected by
``gp_resource_kernel``, values are ``matern52``,
``matern52-res-warp``, ``exp-decay-sum``, ``exp-decay-combined``,
``exp-decay-delta1``. These are variants of either a joint Matern 5/2
kernel over configuration and resource, or the exponential decay
model. Details about the latter can be found
`here `__.
- Fitting a Gaussian process surrogate model to data encurs a cost
which scales cubically with the number of datapoints. When applied to
expensive deep learning workloads, even multi-fidelity asynchronous
BOHB is rarely running up more than 100 observations or so (across
all rung levels and brackets), and the GP computations are
subdominant. However, if you apply it to cheaper ``train_fn`` and
find yourself beyond 2000 total evaluations, the cost of GP fitting
can become painful. In such a situation, you can explore the options
``opt_skip_period`` and ``opt_skip_num_max_resource``. The basic idea
is as follows. By far the most expensive part of a ``get_config``
call (picking the next configuration) is the refitting of the GP
model to past data (this entails re-optimizing hyperparameters of the
surrogate model itself). The options allow you to skip this expensive
step for most ``get_config`` calls, after some initial period. Check
the docstrings for details about these options. If you find yourself
in such a situation and gain experience with these skipping features,
make sure to contact the AutoGluon developers -- we would love to
learn about your use case.