How to Tune Multiple Algorithms with Hyperparameter Optimization to Find the Best Model
Tags: ai, sagemaker, machinelearning, optimization
Published: 2024-01-21 22:35:24

<!-- wp:heading {"level":1} -->
<h1 class="wp-block-heading"><strong>Introduction</strong></h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a href="https://towardsdatascience.com/parameters-and-hyperparameters-aa609601a9ac">Hyperparameter</a> tuning is a machine learning concept which is the problem of selecting a set of most optimal Hyperparameters in order to learn an algorithm. It basically performs the role of a control variable which is responsible for controlling the learning process. As far as<a href="https://docs.aws.amazon.com/sagemaker/latest/dg/multiple-algorithm-hpo.html"> Hyperparameter optimization</a> is concerned, it is considered to be a crucial step in the development of a machine learning model.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Amazon SageMaker jumps into the picture to create ease for the users by allowing them to<a href="https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-ex.html"> tune more than one algorithm concurrently</a>. You will find information regarding the following topics in this guide.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>&nbsp;How to set up a Hyperparameter tuning job</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>&nbsp;How to cover tuning job settings</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>How to train job definitions</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>How to tune job configuration</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>There are two approaches which can be followed for managing Hyperparameter tuning jobs; console-based and API. We will further dive into the details in the later section of this guide.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 class="wp-block-heading"><strong>Components of a Tuning Job&nbsp;</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>It is important to know that in Amazon SageMaker, a Hyperparameter tuning job consists of three important components:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>Tuning Job Settings</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Training Job Definitions</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>&nbsp;Tuning Job Configuration</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>The setting of the setup depends on the number of algorithms you are trying to tune. Whenever you select a particular tuning job setting then it will be applied to all the algorithms present in the job. Some of the tuning job settings are warm start, tuning strategy and early stopping.<a href="https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-warm-start.html"> Warm start</a> and early stop have their own advantages like when you decide to use warm start then you will get an upper hand of leveraging results from the previous tuning jobs. In case of<a href="https://sagemaker-examples.readthedocs.io/en/latest/hyperparameter_tuning/image_classification_early_stopping/hpo_image_classification_early_stopping.html"> early stopping</a>, the compute time will be reduced significantly. Warm start and early stopping are meant to be used for single-algorithm tuning jobs only.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now comes the tuning strategy options which are random, Bayesian and Hyperband. When we discuss training job definitions then there are three things associated with it which the user has to provide as well; name, source of the algorithm and the ranges of Hyperparameter for every algorithm.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://lh7-us.googleusercontent.com/pCUMjukCUaMM0ebYQsJ6sCOPh75Ddk-RpVz1PNzqQpokaS36-D6byoDt1RMXopVAfWn1hiFGQhluxIeZ9yJNfh2QScmBzHDsVOvOdD3Smfd-27LVlYdsoBHBmaTxDRARSq_SchvTnEN4L1ZYE4K5eaM" alt=""/><figcaption class="wp-element-caption">Source : SUDO Consultants</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 class="wp-block-heading"><strong>Getting Started</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As told before, there are two options for the user to initiate a Hyperparameter tuning job. Both approaches have their own pros. Like if you decide to opt for the console-based option then you will have a user-friendly interface using which you can clone, create or even tag the jobs. In the case of API, you will have to go through in-depth details and instructions.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Creating Training Job Definitions&nbsp;</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Before jumping on to the configuration part, it is essential to start by defining training job definitions for every algorithm to be tuned. For this you need to initialize estimators for every algorithm, specify input data locations and set Hyperparameters.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let’s take an example where we want to initialize the estimators for XGBoost along with Linear Learner. For this, we need to set the static Hyperparameters and also define input data locations in Amazon S3. All these training job definitions are critical because they serve as the base for the succeeding Hyperparameter tuning.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Define Resources and Settings for Your Tuning Job&nbsp;</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Once you are done with the first step, the next one involves the following:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>Initializing a tuner</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Specifying Hyperparameter Ranges</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Setting Up Objective Metric</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>In this section, you will get to know about the code examples related to the tuning process of a single algorithm as well as multiple algorithms. There is an ease for the users to customize the tuning strategy such as using the<a href="https://www.run.ai/guides/hyperparameter-tuning/bayesian-hyperparameter-optimization"> Bayesian optimization</a> and setting the resource constraints like the max number of regular as well as parallel jobs. Metric definitions are used for accurate tracking.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Running Your HPO Tuning Job&nbsp;</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In order to run the Hyperparameter tuning job you will be needing an initialized tuner and a set of defined training inputs. The code examples will give you an overall view regarding the execution of tuning jobs. They will emphasize on utilizing the flexibility of SageMaker’s HyperparameterTuner class. The process for both the situations, either running the job with one algorithm or with multiple algorithms, remain streamlined. This way the users will have an upper hand in fine-tuning and optimizing the machine learning models effectively.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Managing Hyperparameter Tuning and Training Jobs&nbsp;</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As the number of training jobs within a tuning job starts increasing their management becomes difficult too. By using Amazon SageMaker you can use a console which will help you to access and monitor the Hyperparameter tuning jobs. Users will have the authority to get insights regarding the training jobs, training jobs definitions and identifying which model is the best performing one. For the sake of time convenience, you can use the cloning feature which will allow you to replicate the job settings.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 class="wp-block-heading"><strong>Prerequisites</strong></h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You must have the following prerequisites installed before diving into the implementation part.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>A working AWS account</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Access of an Administrator User</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>An up and running SageMaker notebook instance</li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Creating a Notebook Instance</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><!-- wp:list-item -->
<li>Go to the website<a href="https://console.aws.amazon.com/sagemaker/"> https://console.aws.amazon.com/sagemaker/</a></li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>Open the SageMaker console</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>&nbsp;From the running notebook instances, open a single instance by clicking on <strong><em>“Open”</em></strong> option</li>
<!-- /wp:list-item -->

<!-- wp:list-item -->
<li>In order to create a new notebook, go to <strong><em>Files</em></strong> option, select <strong><em>New</em></strong> and then choose <strong><em>conda_python3</em></strong></li>
<!-- /wp:list-item --></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Get the Amazon SageMaker Boto3 Client</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Open Jupyter notebook and import the necessary libraries. Along with this, create a Boto3 client for the SageMaker.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import sagemaker

import boto3

import numpy as np

import pandas as pd

from time import gmtime, strftime

import os

region = boto3.Session().region_name

smclient = boto3.Session().client('sagemaker')</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Get the SageMaker Execution Role</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The ARN (Amazon Resource Name) of the IAM execution role will be attached to the notebook instance, retrieve it</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>from sagemaker import get_execution_role

role = get_execution_role()

print(role)</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Use an Amazon S3 Bucket for Input and Output</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In order to upload your training datasets and save the output data, you will need to set an S3 bucket. There are two types of buckets available; default and custom. You can use either one of these.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>sess = sagemaker.Session()

bucket = sess.default_bucket() # Use default S3 bucket

prefix = 'DEMO-automatic-model-tuning-xgboost-dm'</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Download, Prepare, and Upload Training Data</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now it’s time to download and prepare the training dataset. In this particular example, we have used a dataset of bank customer information for the purpose of predicting term deposit enrollment.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>!wget -N https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip

!unzip -o bank-additional.zip

data = pd.read_csv('./bank-additional/bank-additional-full.csv', sep=';')

# Perform data preparation steps

# ...

# Upload data to S3 bucket

boto3.Session().resource('s3').Bucket(bucket).Object(os.path.join(prefix, 'train/train.csv')).upload_file('train.csv')</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Configure and Launch a Hyperparameter Tuning Job</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We will now begin configuring the Hyperparameter tuning job with the help of low-level SDK for Python. Define the related components of a Hyperparameter tuning job configuration such as parameter ranges, resource limits and last but not the least objective metric.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>tuning_job_config = {

&nbsp;"ParameterRanges": {

&nbsp;"CategoricalParameterRanges": &#91;],

&nbsp;"ContinuousParameterRanges": &#91;

&nbsp;{"MaxValue": "1", "MinValue": "0", "Name": "eta"},

&nbsp;{"MaxValue": "2", "MinValue": "0", "Name": "alpha"},

&nbsp;{"MaxValue": "10", "MinValue": "1", "Name": "min_child_weight"}

&nbsp;],

&nbsp;"IntegerParameterRanges": &#91;

&nbsp;{"MaxValue": "10", "MinValue": "1", "Name": "max_depth"}

&nbsp;]

&nbsp;},

&nbsp;"ResourceLimits": {

&nbsp;"MaxNumberOfTrainingJobs": 20,

&nbsp;"MaxParallelTrainingJobs": 3

&nbsp;},

&nbsp;"Strategy": "Bayesian",

&nbsp;"HyperParameterTuningJobObjective": {

&nbsp;"MetricName": "validation:auc",

&nbsp;"Type": "Maximize"

&nbsp;},

&nbsp;"RandomSeed": 123

}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now it is time to define the training job specifications such as algorithm, output data, input data, resource configuration, role ARN, and stopping conditions:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code># Define training job specifications

training_image = sagemaker.amazon.amazon_estimator.get_image_uri(region, 'xgboost', repo_version='1.0-1')

s3_input_train = 's3://{}/{}/train'.format(bucket, prefix)

s3_input_validation = 's3://{}/{}/validation/'.format(bucket, prefix)

training_job_definition = {

&nbsp;"AlgorithmSpecification": {

&nbsp;"TrainingImage": training_image,

&nbsp;"TrainingInputMode": "File"

&nbsp;},

&nbsp;"InputDataConfig": &#91;

&nbsp;{"ChannelName": "train", "CompressionType": "None", "ContentType": "csv", "DataSource": {...}},

&nbsp;{"ChannelName": "validation", "CompressionType": "None", "ContentType": "csv", "DataSource": {...}}

&nbsp;],

&nbsp;"OutputDataConfig": {"S3OutputPath": "s3://{}/{}/output".format(bucket, prefix)},

&nbsp;"ResourceConfig": {"InstanceCount": 2, "InstanceType": "ml.c4.2xlarge", "VolumeSizeInGB": 10},

&nbsp;"RoleArn": role,

&nbsp;"StaticHyperParameters": {...},

&nbsp;"StoppingCondition": {"MaxRuntimeInSeconds": 43200}

}

Save to grepper

Name and launch the hyperparameter tuning job:

python

Copy code

tuning_job_name = "MyTuningJob"

smclient.create_hyper_parameter_tuning_job(

&nbsp;HyperParameterTuningJobName=tuning_job_name,

&nbsp;HyperParameterTuningJobConfig=tuning_job_config,

&nbsp;TrainingJobDefinition=training_job_definition

)</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Monitoring the Progress of a Hyperparameter Tuning Job</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You can easily track the training jobs status in the SageMaker console which is launched by the Hyperparameter tuning job.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>View the Best Training Job</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As soon as the Hyperparameter tuning job part is done, it is time to identify the best training job among the others on the basis of objective metric. The best model should be deployed as a SageMaker endpoint for inference.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Clean Up</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>All the resources which were created for the demonstration of this example should be deleted immediately to avoid unnecessary charges. For this purpose, use the AWS Management Console and delete the resources including S3 bucket, notebook instance and IAM role.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For detailed roadmap you can also watch this video tutorial to make stuff easier:</p>
<!-- /wp:paragraph -->

<!-- wp:embed {"url":"https://www.youtube.com/watch?v=8cA9RifwWZ4","type":"video","providerNameSlug":"youtube","responsive":true,"className":"wp-embed-aspect-16-9 wp-has-aspect-ratio"} -->
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
https://www.youtube.com/watch?v=8cA9RifwWZ4
</div></figure>
<!-- /wp:embed -->

<!-- wp:heading {"level":3} -->
<h3 class="wp-block-heading"><strong>Conclusion</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>To become an expert in Hyperparameter optimization using Amazon SageMaker, you need to have comprehensive details regarding tuning job settings, training job definitions, job configuration etc. The sample example shown above consisted of every step from the creation of resources to deleting them. For your better understanding, you can experiment with other algorithms as well by using SageMaker’s powerful capabilities.</p>
<!-- /wp:paragraph -->