.. _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.1b20210310' 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, 14407.30KB/s] 100%|██████████| 2521/2521 [00:00<00:00, 36939.83KB/s] 3KB [00:00, 4088.02KB/s] 8KB [00:00, 7305.56KB/s] 15KB [00:00, 17985.87KB/s] 2998KB [00:00, 45037.05KB/s] 881KB [00:00, 35039.04KB/s] 3KB [00:00, 2921.50KB/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.7/site-packages/distributed/worker.py:3460: 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 % (format_bytes(len(b)), s) .. parsed-literal:: :class: output Epoch 1 ; Time: 0.499187 ; Training: accuracy=0.260079 ; Validation: accuracy=0.531250 Epoch 2 ; Time: 0.931287 ; Training: accuracy=0.496365 ; Validation: accuracy=0.655247 Epoch 3 ; Time: 1.368944 ; Training: accuracy=0.559650 ; Validation: accuracy=0.694686 Epoch 4 ; Time: 1.796348 ; Training: accuracy=0.588896 ; Validation: accuracy=0.711063 Epoch 5 ; Time: 2.223053 ; Training: accuracy=0.609385 ; Validation: accuracy=0.726939 Epoch 6 ; Time: 2.642448 ; Training: accuracy=0.628139 ; Validation: accuracy=0.745321 Epoch 7 ; Time: 3.068481 ; Training: accuracy=0.641193 ; Validation: accuracy=0.750501 Epoch 8 ; Time: 3.493457 ; Training: accuracy=0.653751 ; Validation: accuracy=0.763202 Epoch 9 ; Time: 3.919381 ; Training: accuracy=0.665482 ; Validation: accuracy=0.766043 Epoch 1 ; Time: 0.397470 ; Training: accuracy=0.035655 ; Validation: accuracy=0.048829 Epoch 1 ; Time: 1.427605 ; Training: accuracy=0.041408 ; Validation: accuracy=0.032643 Epoch 1 ; Time: 1.321110 ; Training: accuracy=0.043313 ; Validation: accuracy=0.039785 Epoch 1 ; Time: 0.437642 ; Training: accuracy=0.169652 ; Validation: accuracy=0.465152 Epoch 2 ; Time: 0.813720 ; Training: accuracy=0.238723 ; Validation: accuracy=0.532155 Epoch 3 ; Time: 1.138647 ; Training: accuracy=0.261609 ; Validation: accuracy=0.542256 Epoch 1 ; Time: 1.420248 ; Training: accuracy=0.036687 ; Validation: accuracy=0.038533 Epoch 1 ; Time: 0.505312 ; Training: accuracy=0.098302 ; Validation: accuracy=0.353157 Epoch 2 ; Time: 0.929666 ; Training: accuracy=0.187826 ; Validation: accuracy=0.533400 Epoch 3 ; Time: 1.346565 ; Training: accuracy=0.231718 ; Validation: accuracy=0.570881 Epoch 1 ; Time: 0.492936 ; Training: accuracy=0.038889 ; Validation: accuracy=0.040080 Epoch 1 ; Time: 0.544571 ; Training: accuracy=0.218859 ; Validation: accuracy=0.450669 Epoch 2 ; Time: 1.031773 ; Training: accuracy=0.458065 ; Validation: accuracy=0.584281 Epoch 3 ; Time: 1.460059 ; Training: accuracy=0.520265 ; Validation: accuracy=0.631773 Epoch 4 ; Time: 1.911848 ; Training: accuracy=0.562614 ; Validation: accuracy=0.674582 Epoch 5 ; Time: 2.419292 ; Training: accuracy=0.593218 ; Validation: accuracy=0.695987 Epoch 6 ; Time: 2.863793 ; Training: accuracy=0.618528 ; Validation: accuracy=0.706522 Epoch 7 ; Time: 3.399869 ; Training: accuracy=0.629115 ; Validation: accuracy=0.733278 Epoch 8 ; Time: 3.842475 ; Training: accuracy=0.646319 ; Validation: accuracy=0.737793 Epoch 9 ; Time: 4.275826 ; Training: accuracy=0.661787 ; Validation: accuracy=0.755686 Epoch 1 ; Time: 0.795109 ; Training: accuracy=0.100877 ; Validation: accuracy=0.188736 Epoch 1 ; Time: 0.444969 ; Training: accuracy=0.098302 ; Validation: accuracy=0.170333 Epoch 1 ; Time: 0.457013 ; Training: accuracy=0.098511 ; Validation: accuracy=0.412587 Epoch 2 ; Time: 0.837183 ; Training: accuracy=0.160546 ; Validation: accuracy=0.415418 Epoch 3 ; Time: 1.208207 ; Training: accuracy=0.186518 ; Validation: accuracy=0.469530 Epoch 1 ; Time: 0.511076 ; Training: accuracy=0.284898 ; Validation: accuracy=0.657071 Epoch 2 ; Time: 0.947124 ; Training: accuracy=0.449909 ; Validation: accuracy=0.695623 Epoch 3 ; Time: 1.379096 ; Training: accuracy=0.499172 ; Validation: accuracy=0.740236 Epoch 4 ; Time: 1.818933 ; Training: accuracy=0.526412 ; Validation: accuracy=0.747138 Epoch 5 ; Time: 2.250991 ; Training: accuracy=0.535022 ; Validation: accuracy=0.757407 Epoch 6 ; Time: 2.700488 ; Training: accuracy=0.553734 ; Validation: accuracy=0.763131 Epoch 7 ; Time: 3.130704 ; Training: accuracy=0.567230 ; Validation: accuracy=0.766667 Epoch 8 ; Time: 3.587915 ; Training: accuracy=0.578076 ; Validation: accuracy=0.772896 Epoch 9 ; Time: 4.025302 ; Training: accuracy=0.580891 ; Validation: accuracy=0.779461 Epoch 1 ; Time: 0.531032 ; Training: accuracy=0.262235 ; Validation: accuracy=0.582122 Epoch 2 ; Time: 1.006891 ; Training: accuracy=0.423776 ; Validation: accuracy=0.658480 Epoch 3 ; Time: 1.472682 ; Training: accuracy=0.463624 ; Validation: accuracy=0.692231 Epoch 4 ; Time: 1.953783 ; Training: accuracy=0.488426 ; Validation: accuracy=0.723475 Epoch 5 ; Time: 2.415783 ; Training: accuracy=0.509177 ; Validation: accuracy=0.729657 Epoch 6 ; Time: 2.907128 ; Training: accuracy=0.517774 ; Validation: accuracy=0.739850 Epoch 7 ; Time: 3.387241 ; Training: accuracy=0.531085 ; Validation: accuracy=0.757561 Epoch 8 ; Time: 3.848858 ; Training: accuracy=0.541253 ; Validation: accuracy=0.765581 Epoch 9 ; Time: 4.319560 ; Training: accuracy=0.550513 ; Validation: accuracy=0.775439 Epoch 1 ; Time: 0.334212 ; Training: accuracy=0.039172 ; Validation: accuracy=0.036288 Epoch 1 ; Time: 0.337313 ; Training: accuracy=0.223324 ; Validation: accuracy=0.492826 Epoch 2 ; Time: 0.609893 ; Training: accuracy=0.476568 ; Validation: accuracy=0.608775 Epoch 3 ; Time: 0.891665 ; Training: accuracy=0.549632 ; Validation: accuracy=0.681515 Epoch 1 ; Time: 0.578093 ; Training: accuracy=0.101273 ; Validation: accuracy=0.116835 Epoch 1 ; Time: 1.019357 ; Training: accuracy=0.441211 ; Validation: accuracy=0.677104 Epoch 2 ; Time: 1.985586 ; Training: accuracy=0.636318 ; Validation: accuracy=0.746465 Epoch 3 ; Time: 2.957242 ; Training: accuracy=0.686153 ; Validation: accuracy=0.781481 Epoch 4 ; Time: 3.925401 ; Training: accuracy=0.719237 ; Validation: accuracy=0.801515 Epoch 5 ; Time: 4.977983 ; Training: accuracy=0.735240 ; Validation: accuracy=0.808923 Epoch 6 ; Time: 5.936820 ; Training: accuracy=0.749834 ; Validation: accuracy=0.830976 Epoch 7 ; Time: 6.893489 ; Training: accuracy=0.761443 ; Validation: accuracy=0.843098 Epoch 8 ; Time: 7.858332 ; Training: accuracy=0.771393 ; Validation: accuracy=0.845960 Epoch 9 ; Time: 8.846323 ; Training: accuracy=0.782836 ; Validation: accuracy=0.858923 Epoch 1 ; Time: 0.297672 ; Training: accuracy=0.127587 ; Validation: accuracy=0.533958 Epoch 2 ; Time: 0.544459 ; Training: accuracy=0.309654 ; Validation: accuracy=0.642690 Epoch 3 ; Time: 0.790447 ; Training: accuracy=0.412568 ; Validation: accuracy=0.669455 Epoch 1 ; Time: 3.212780 ; Training: accuracy=0.326617 ; Validation: accuracy=0.571380 Epoch 2 ; Time: 6.386173 ; Training: accuracy=0.521061 ; Validation: accuracy=0.647138 Epoch 3 ; Time: 9.528424 ; Training: accuracy=0.581343 ; Validation: accuracy=0.712626 Epoch 4 ; Time: 12.612814 ; Training: accuracy=0.620978 ; Validation: accuracy=0.743939 Epoch 5 ; Time: 15.867750 ; Training: accuracy=0.646600 ; Validation: accuracy=0.765657 Epoch 6 ; Time: 18.937279 ; Training: accuracy=0.673134 ; Validation: accuracy=0.773906 Epoch 7 ; Time: 22.059052 ; Training: accuracy=0.686982 ; Validation: accuracy=0.800168 Epoch 8 ; Time: 25.081442 ; Training: accuracy=0.698176 ; Validation: accuracy=0.811279 Epoch 9 ; Time: 28.096571 ; Training: accuracy=0.709287 ; Validation: accuracy=0.814646 Epoch 1 ; Time: 0.726542 ; Training: accuracy=0.152413 ; Validation: accuracy=0.459541 Epoch 1 ; Time: 1.664907 ; Training: accuracy=0.237148 ; Validation: accuracy=0.538384 Epoch 2 ; Time: 3.268260 ; Training: accuracy=0.306882 ; Validation: accuracy=0.597643 Epoch 3 ; Time: 4.863143 ; Training: accuracy=0.330182 ; Validation: accuracy=0.604545 Epoch 1 ; Time: 0.303884 ; Training: accuracy=0.216941 ; Validation: accuracy=0.468418 Epoch 1 ; Time: 0.646231 ; Training: accuracy=0.456482 ; Validation: accuracy=0.682609 Epoch 2 ; Time: 1.266967 ; Training: accuracy=0.639672 ; Validation: accuracy=0.728930 Epoch 3 ; Time: 1.832391 ; Training: accuracy=0.679957 ; Validation: accuracy=0.761538 Epoch 4 ; Time: 2.395957 ; Training: accuracy=0.706482 ; Validation: accuracy=0.780769 Epoch 5 ; Time: 2.964152 ; Training: accuracy=0.726293 ; Validation: accuracy=0.808361 Epoch 6 ; Time: 3.537363 ; Training: accuracy=0.738395 ; Validation: accuracy=0.824916 Epoch 7 ; Time: 4.086656 ; Training: accuracy=0.756217 ; Validation: accuracy=0.827090 Epoch 8 ; Time: 4.633717 ; Training: accuracy=0.768070 ; Validation: accuracy=0.852341 Epoch 9 ; Time: 5.187097 ; Training: accuracy=0.777686 ; Validation: accuracy=0.858696 Epoch 1 ; Time: 0.785594 ; Training: accuracy=0.162106 ; Validation: accuracy=0.490909 Epoch 1 ; Time: 3.619108 ; Training: accuracy=0.281747 ; Validation: accuracy=0.633244 Epoch 2 ; Time: 7.172428 ; Training: accuracy=0.432527 ; Validation: accuracy=0.702052 Epoch 3 ; Time: 10.780054 ; Training: accuracy=0.491628 ; Validation: accuracy=0.728466 Epoch 4 ; Time: 14.530495 ; Training: accuracy=0.542606 ; Validation: accuracy=0.759590 Epoch 5 ; Time: 18.309598 ; Training: accuracy=0.561837 ; Validation: accuracy=0.776245 Epoch 6 ; Time: 21.964199 ; Training: accuracy=0.589854 ; Validation: accuracy=0.780114 Epoch 7 ; Time: 25.531408 ; Training: accuracy=0.605023 ; Validation: accuracy=0.793237 Epoch 8 ; Time: 29.101756 ; Training: accuracy=0.620192 ; Validation: accuracy=0.814098 Epoch 9 ; Time: 32.804132 ; Training: accuracy=0.637019 ; Validation: accuracy=0.820659 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.501811 1 0.468750 0.497021 0.531250 0.793618 NaN 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 0.795673 1.615351e+09 0.532143 0.468750
1 0 0.932910 2 0.344753 0.426423 0.655247 1.224717 1.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 1.225527 1.615351e+09 0.431076 0.344753
2 0 1.370678 3 0.305314 0.435934 0.694686 1.662485 1.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 1.663301 1.615351e+09 0.437768 0.305314
3 0 1.798113 4 0.288937 0.424839 0.711063 2.089920 2.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 2.090684 1.615351e+09 0.427435 0.288937
4 0 2.224725 5 0.273061 0.424415 0.726939 2.516532 2.0 1.0 1.0 ... 1.0 1.0 0.0 0.001 9 0 2.517470 1.615351e+09 0.426612 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.