.. _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.0b20210223' 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, 43397.22KB/s] 100%|██████████| 2521/2521 [00:00<00:00, 27103.38KB/s] 3KB [00:00, 2775.85KB/s] 8KB [00:00, 9796.91KB/s] 15KB [00:00, 18995.94KB/s] 2998KB [00:00, 44038.31KB/s] 881KB [00:00, 59351.77KB/s] 3KB [00:00, 4375.14KB/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.497917 ; Training: accuracy=0.260079 ; Validation: accuracy=0.531250 Epoch 2 ; Time: 0.932042 ; Training: accuracy=0.496365 ; Validation: accuracy=0.655247 Epoch 3 ; Time: 1.361792 ; Training: accuracy=0.559650 ; Validation: accuracy=0.694686 Epoch 4 ; Time: 1.791742 ; Training: accuracy=0.588896 ; Validation: accuracy=0.711063 Epoch 5 ; Time: 2.224127 ; Training: accuracy=0.609385 ; Validation: accuracy=0.726939 Epoch 6 ; Time: 2.667059 ; Training: accuracy=0.628139 ; Validation: accuracy=0.745321 Epoch 7 ; Time: 3.166794 ; Training: accuracy=0.641193 ; Validation: accuracy=0.750501 Epoch 8 ; Time: 3.603175 ; Training: accuracy=0.653751 ; Validation: accuracy=0.763202 Epoch 9 ; Time: 4.037413 ; Training: accuracy=0.665482 ; Validation: accuracy=0.766043 Epoch 1 ; Time: 0.918722 ; Training: accuracy=0.210844 ; Validation: accuracy=0.449497 Epoch 1 ; Time: 0.284442 ; Training: accuracy=0.051398 ; Validation: accuracy=0.059840 Epoch 1 ; Time: 0.361008 ; Training: accuracy=0.403300 ; Validation: accuracy=0.655647 Epoch 2 ; Time: 0.662917 ; Training: accuracy=0.597030 ; Validation: accuracy=0.730156 Epoch 3 ; Time: 0.957435 ; Training: accuracy=0.639851 ; Validation: accuracy=0.746937 Epoch 4 ; Time: 1.279377 ; Training: accuracy=0.670215 ; Validation: accuracy=0.773620 Epoch 5 ; Time: 1.573360 ; Training: accuracy=0.697525 ; Validation: accuracy=0.799295 Epoch 6 ; Time: 1.935091 ; Training: accuracy=0.708581 ; Validation: accuracy=0.801645 Epoch 7 ; Time: 2.230321 ; Training: accuracy=0.717162 ; Validation: accuracy=0.818426 Epoch 8 ; Time: 2.521688 ; Training: accuracy=0.728218 ; Validation: accuracy=0.830173 Epoch 9 ; Time: 2.812761 ; Training: accuracy=0.743647 ; Validation: accuracy=0.837557 Epoch 1 ; Time: 0.307125 ; Training: accuracy=0.565789 ; Validation: accuracy=0.767620 Epoch 2 ; Time: 0.552073 ; Training: accuracy=0.714474 ; Validation: accuracy=0.811004 Epoch 3 ; Time: 0.779723 ; Training: accuracy=0.743010 ; Validation: accuracy=0.831616 Epoch 4 ; Time: 1.051953 ; Training: accuracy=0.756826 ; Validation: accuracy=0.842919 Epoch 5 ; Time: 1.310629 ; Training: accuracy=0.764227 ; Validation: accuracy=0.851064 Epoch 6 ; Time: 1.541153 ; Training: accuracy=0.774095 ; Validation: accuracy=0.862866 Epoch 7 ; Time: 1.772923 ; Training: accuracy=0.788651 ; Validation: accuracy=0.864694 Epoch 8 ; Time: 2.010529 ; Training: accuracy=0.798026 ; Validation: accuracy=0.884142 Epoch 9 ; Time: 2.250172 ; Training: accuracy=0.797862 ; Validation: accuracy=0.870346 Epoch 1 ; Time: 0.296417 ; Training: accuracy=0.069490 ; Validation: accuracy=0.189162 Epoch 1 ; Time: 0.304443 ; Training: accuracy=0.234951 ; Validation: accuracy=0.434009 Epoch 1 ; Time: 0.399209 ; Training: accuracy=0.038773 ; Validation: accuracy=0.041247 Epoch 1 ; Time: 0.320351 ; Training: accuracy=0.044592 ; Validation: accuracy=0.062657 Epoch 1 ; Time: 0.680845 ; Training: accuracy=0.390212 ; Validation: accuracy=0.679435 Epoch 2 ; Time: 1.332257 ; Training: accuracy=0.543320 ; Validation: accuracy=0.753696 Epoch 3 ; Time: 1.977561 ; Training: accuracy=0.587798 ; Validation: accuracy=0.790659 Epoch 4 ; Time: 2.608873 ; Training: accuracy=0.603340 ; Validation: accuracy=0.798891 Epoch 5 ; Time: 3.237715 ; Training: accuracy=0.621445 ; Validation: accuracy=0.805444 Epoch 6 ; Time: 3.861746 ; Training: accuracy=0.641038 ; Validation: accuracy=0.802419 Epoch 7 ; Time: 4.482365 ; Training: accuracy=0.646743 ; Validation: accuracy=0.818716 Epoch 8 ; Time: 5.102558 ; Training: accuracy=0.652943 ; Validation: accuracy=0.819556 Epoch 9 ; Time: 5.720102 ; Training: accuracy=0.664683 ; Validation: accuracy=0.833669 Epoch 1 ; Time: 0.437460 ; Training: accuracy=0.286954 ; Validation: accuracy=0.639504 Epoch 2 ; Time: 0.802006 ; Training: accuracy=0.383267 ; Validation: accuracy=0.643863 Epoch 3 ; Time: 1.157221 ; Training: accuracy=0.413608 ; Validation: accuracy=0.674044 Epoch 1 ; Time: 0.397943 ; Training: accuracy=0.439891 ; Validation: accuracy=0.673660 Epoch 2 ; Time: 0.800985 ; Training: accuracy=0.589771 ; Validation: accuracy=0.719114 Epoch 3 ; Time: 1.125119 ; Training: accuracy=0.624143 ; Validation: accuracy=0.748085 Epoch 1 ; Time: 0.334943 ; Training: accuracy=0.449707 ; Validation: accuracy=0.693527 Epoch 2 ; Time: 0.619184 ; Training: accuracy=0.627738 ; Validation: accuracy=0.747581 Epoch 3 ; Time: 0.898931 ; Training: accuracy=0.671708 ; Validation: accuracy=0.779446 Epoch 4 ; Time: 1.175023 ; Training: accuracy=0.702372 ; Validation: accuracy=0.804805 Epoch 5 ; Time: 1.454557 ; Training: accuracy=0.718406 ; Validation: accuracy=0.810978 Epoch 6 ; Time: 1.724777 ; Training: accuracy=0.739069 ; Validation: accuracy=0.816817 Epoch 7 ; Time: 2.007390 ; Training: accuracy=0.747665 ; Validation: accuracy=0.833500 Epoch 8 ; Time: 2.383957 ; Training: accuracy=0.759567 ; Validation: accuracy=0.832499 Epoch 9 ; Time: 2.666793 ; Training: accuracy=0.765683 ; Validation: accuracy=0.848182 Epoch 1 ; Time: 0.784725 ; Training: accuracy=0.396197 ; Validation: accuracy=0.671320 Epoch 2 ; Time: 1.513910 ; Training: accuracy=0.483010 ; Validation: accuracy=0.689487 Epoch 3 ; Time: 2.228039 ; Training: accuracy=0.502604 ; Validation: accuracy=0.717410 Epoch 1 ; Time: 1.349526 ; Training: accuracy=0.420621 ; Validation: accuracy=0.674165 Epoch 2 ; Time: 2.756755 ; Training: accuracy=0.599337 ; Validation: accuracy=0.753399 Epoch 3 ; Time: 4.180149 ; Training: accuracy=0.645631 ; Validation: accuracy=0.777069 Epoch 4 ; Time: 5.623622 ; Training: accuracy=0.673375 ; Validation: accuracy=0.812322 Epoch 5 ; Time: 7.002359 ; Training: accuracy=0.695569 ; Validation: accuracy=0.808293 Epoch 6 ; Time: 8.367699 ; Training: accuracy=0.707909 ; Validation: accuracy=0.835991 Epoch 7 ; Time: 9.723337 ; Training: accuracy=0.722484 ; Validation: accuracy=0.840524 Epoch 8 ; Time: 11.077282 ; Training: accuracy=0.736066 ; Validation: accuracy=0.844049 Epoch 9 ; Time: 12.499648 ; Training: accuracy=0.727205 ; Validation: accuracy=0.849924 Epoch 1 ; Time: 0.410830 ; Training: accuracy=0.597944 ; Validation: accuracy=0.792387 Epoch 2 ; Time: 0.680402 ; Training: accuracy=0.733882 ; Validation: accuracy=0.828125 Epoch 3 ; Time: 0.916407 ; Training: accuracy=0.760033 ; Validation: accuracy=0.840924 Epoch 4 ; Time: 1.155002 ; Training: accuracy=0.783388 ; Validation: accuracy=0.854056 Epoch 5 ; Time: 1.389601 ; Training: accuracy=0.782401 ; Validation: accuracy=0.867852 Epoch 6 ; Time: 1.637365 ; Training: accuracy=0.797039 ; Validation: accuracy=0.878491 Epoch 7 ; Time: 1.879865 ; Training: accuracy=0.805181 ; Validation: accuracy=0.877493 Epoch 8 ; Time: 2.142875 ; Training: accuracy=0.808224 ; Validation: accuracy=0.867686 Epoch 9 ; Time: 2.446826 ; Training: accuracy=0.816694 ; Validation: accuracy=0.892453 Epoch 1 ; Time: 0.321680 ; Training: accuracy=0.502220 ; Validation: accuracy=0.711769 Epoch 2 ; Time: 0.583498 ; Training: accuracy=0.722862 ; Validation: accuracy=0.802194 Epoch 3 ; Time: 0.821479 ; Training: accuracy=0.775822 ; Validation: accuracy=0.822640 Epoch 4 ; Time: 1.065256 ; Training: accuracy=0.806743 ; Validation: accuracy=0.856383 Epoch 5 ; Time: 1.337097 ; Training: accuracy=0.832566 ; Validation: accuracy=0.876662 Epoch 6 ; Time: 1.633247 ; Training: accuracy=0.843914 ; Validation: accuracy=0.887965 Epoch 7 ; Time: 1.892295 ; Training: accuracy=0.859539 ; Validation: accuracy=0.897108 Epoch 8 ; Time: 2.145139 ; Training: accuracy=0.868010 ; Validation: accuracy=0.907580 Epoch 9 ; Time: 2.414973 ; Training: accuracy=0.875082 ; Validation: accuracy=0.908743 Epoch 1 ; Time: 0.460085 ; Training: accuracy=0.494636 ; Validation: accuracy=0.700635 Epoch 2 ; Time: 0.865927 ; Training: accuracy=0.750371 ; Validation: accuracy=0.777815 Epoch 3 ; Time: 1.387652 ; Training: accuracy=0.810117 ; Validation: accuracy=0.834280 Epoch 4 ; Time: 1.810829 ; Training: accuracy=0.846179 ; Validation: accuracy=0.846308 Epoch 5 ; Time: 2.224459 ; Training: accuracy=0.873494 ; Validation: accuracy=0.873538 Epoch 6 ; Time: 2.631972 ; Training: accuracy=0.891401 ; Validation: accuracy=0.888239 Epoch 7 ; Time: 3.039830 ; Training: accuracy=0.899076 ; Validation: accuracy=0.893418 Epoch 8 ; Time: 3.458062 ; Training: accuracy=0.919294 ; Validation: accuracy=0.905947 Epoch 9 ; Time: 3.875112 ; Training: accuracy=0.918964 ; Validation: accuracy=0.915971 Epoch 1 ; Time: 0.628635 ; Training: accuracy=0.609582 ; Validation: accuracy=0.774080 Epoch 2 ; Time: 1.183021 ; Training: accuracy=0.777520 ; Validation: accuracy=0.845485 Epoch 3 ; Time: 1.738862 ; Training: accuracy=0.824188 ; Validation: accuracy=0.870736 Epoch 4 ; Time: 2.291882 ; Training: accuracy=0.847646 ; Validation: accuracy=0.889799 Epoch 5 ; Time: 2.830507 ; Training: accuracy=0.860245 ; Validation: accuracy=0.897993 Epoch 6 ; Time: 3.523501 ; Training: accuracy=0.880885 ; Validation: accuracy=0.904849 Epoch 7 ; Time: 4.075918 ; Training: accuracy=0.885444 ; Validation: accuracy=0.908027 Epoch 8 ; Time: 4.626583 ; Training: accuracy=0.893153 ; Validation: accuracy=0.920569 Epoch 9 ; Time: 5.168323 ; Training: accuracy=0.893236 ; Validation: accuracy=0.928094 Epoch 1 ; Time: 0.711923 ; Training: accuracy=0.516118 ; Validation: accuracy=0.734783 Epoch 2 ; Time: 1.332446 ; Training: accuracy=0.671433 ; Validation: accuracy=0.784281 Epoch 3 ; Time: 1.956556 ; Training: accuracy=0.703835 ; Validation: accuracy=0.815217 Epoch 1 ; Time: 0.414955 ; Training: accuracy=0.467968 ; Validation: accuracy=0.689505 Epoch 2 ; Time: 0.767580 ; Training: accuracy=0.681901 ; Validation: accuracy=0.765374 Epoch 3 ; Time: 1.098769 ; Training: accuracy=0.752635 ; Validation: accuracy=0.816511 Epoch 1 ; Time: 0.422718 ; Training: accuracy=0.611424 ; Validation: accuracy=0.742833 Epoch 2 ; Time: 0.800560 ; Training: accuracy=0.773096 ; Validation: accuracy=0.791167 Epoch 3 ; Time: 1.177675 ; Training: accuracy=0.817136 ; Validation: accuracy=0.818833 Epoch 4 ; Time: 1.562771 ; Training: accuracy=0.837169 ; Validation: accuracy=0.818500 Epoch 5 ; Time: 1.926002 ; Training: accuracy=0.858195 ; Validation: accuracy=0.841000 Epoch 6 ; Time: 2.285306 ; Training: accuracy=0.865977 ; Validation: accuracy=0.847333 Epoch 7 ; Time: 2.645601 ; Training: accuracy=0.877566 ; Validation: accuracy=0.844833 Epoch 8 ; Time: 3.022558 ; Training: accuracy=0.891556 ; Validation: accuracy=0.863333 Epoch 9 ; Time: 3.385160 ; Training: accuracy=0.894288 ; Validation: accuracy=0.862167 Epoch 1 ; Time: 1.837415 ; Training: accuracy=0.670424 ; Validation: accuracy=0.806284 Epoch 2 ; Time: 3.712729 ; Training: accuracy=0.801393 ; Validation: accuracy=0.860551 Epoch 3 ; Time: 5.494268 ; Training: accuracy=0.841346 ; Validation: accuracy=0.883065 Epoch 4 ; Time: 7.323959 ; Training: accuracy=0.858090 ; Validation: accuracy=0.899698 Epoch 5 ; Time: 9.208471 ; Training: accuracy=0.873259 ; Validation: accuracy=0.905242 Epoch 6 ; Time: 10.974168 ; Training: accuracy=0.877818 ; Validation: accuracy=0.901378 Epoch 7 ; Time: 12.737943 ; Training: accuracy=0.880802 ; Validation: accuracy=0.912634 Epoch 8 ; Time: 14.542166 ; Training: accuracy=0.888097 ; Validation: accuracy=0.919187 Epoch 9 ; Time: 16.389095 ; Training: accuracy=0.892324 ; Validation: accuracy=0.910282 Epoch 1 ; Time: 0.294135 ; Training: accuracy=0.348280 ; Validation: accuracy=0.618026 Epoch 1 ; Time: 2.035558 ; Training: accuracy=0.440133 ; Validation: accuracy=0.689731 Epoch 1 ; Time: 0.295661 ; Training: accuracy=0.446957 ; Validation: accuracy=0.671210 Epoch 1 ; Time: 3.770654 ; Training: accuracy=0.704327 ; Validation: accuracy=0.817463 Epoch 2 ; Time: 7.518950 ; Training: accuracy=0.851044 ; Validation: accuracy=0.861709 Epoch 3 ; Time: 11.286733 ; Training: accuracy=0.889092 ; Validation: accuracy=0.885935 Epoch 4 ; Time: 15.256937 ; Training: accuracy=0.905918 ; Validation: accuracy=0.902591 Epoch 5 ; Time: 18.993202 ; Training: accuracy=0.922745 ; Validation: accuracy=0.908647 Epoch 6 ; Time: 22.672286 ; Training: accuracy=0.930537 ; Validation: accuracy=0.913694 Epoch 7 ; Time: 26.298830 ; Training: accuracy=0.936754 ; Validation: accuracy=0.925639 Epoch 8 ; Time: 29.974382 ; Training: accuracy=0.942556 ; Validation: accuracy=0.929004 Epoch 9 ; Time: 33.659257 ; Training: accuracy=0.948110 ; Validation: accuracy=0.927490 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.500309 1 0.468750 0.495349 0.531250 1.422407 NaN 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 1.424081 1.614108e+09 0.533353 0.468750
1 0 0.933435 2 0.344753 0.429056 0.655247 1.855533 1.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 1.856385 1.614108e+09 0.433106 0.344753
2 0 1.363380 3 0.305314 0.427676 0.694686 2.285478 1.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 2.286442 1.614108e+09 0.429946 0.305314
3 0 1.793322 4 0.288937 0.427164 0.711063 2.715420 2.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 2.716326 1.614108e+09 0.429943 0.288937
4 0 2.225575 5 0.273061 0.430173 0.726939 3.147673 2.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 3.148450 1.614108e+09 0.432251 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.