Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - ARM-software/mango: Parallel Hyperparameter Tuning in Python · GitHub
Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - ARM-software/mango: Parallel Hyperparameter Tuning in Python · GitHub
Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - ARM-software/mango: Parallel Hyperparameter Tuning in Python · GitHub
Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - ARM-software/mango: Parallel Hyperparameter Tuning in Python · GitHub
Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - ARM-software/mango: Parallel Hyperparameter Tuning in Python · GitHub
Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - ARM-software/mango: Parallel Hyperparameter Tuning in Python · GitHub
Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - ARM-software/mango: Parallel Hyperparameter Tuning in Python · GitHub
Skip to content

Repository files navigation

Mango: A parallel hyperparameter tuning library

Mango is a python library to find the optimal hyperparameters for machine learning classifiers. Mango enables parallel optimization over complex search spaces of continuous/discrete/categorical values.

Check out the quick 12 seconds demo of Mango approximating a complex decision boundary of SVM

AirSim Drone Demo Video

Mango has the following salient features:

  • Easily define complex search spaces compatible with the scikit-learn.
  • A novel state-of-the-art gradient-free optimizer for continuous/discrete/categorical values.
  • Modular design to schedule objective function on local, cluster, or cloud infrastructure.
  • Failure detection in the application layer for scalability on commodity hardware.
  • New features are continuously added due to the testing and usage in production settings.

Index

  1. Installation
  2. Getting started
  3. Hyperparameter tuning example
  4. Search space definitions
  5. Scheduler
  6. Optional configurations
  7. Additional features
  8. CASH feature
  9. Platform-aware neural architecture search
  10. Mango introduction slides & Mango production usage slides.
  11. Core Mango research papers to cite and novel applications built over Mango

1. Installation

Using pip:

pip install arm-mango

From source:

$ git clone https://github.com/ARM-software/mango.git
$ cd mango
$ pip3 install .

2. Getting Started

Mango is straightforward to use. Following example minimizes the quadratic function whose input is an integer between -10 and 10.

frommangoimportscheduler, Tuner# Search spaceparam_space=dict(x=range(-10,10))
# Quadratic objective Function@scheduler.serialdefobjective(x):
returnx*x# Initialize and run Tunertuner=Tuner(param_space, objective)
results=tuner.minimize()
print(f'Optimal value of parameters: {results["best_params"]} and objective: {results["best_objective"]}')
# => Optimal value of parameters: {'x': 0} and objective: 0

3. Hyperparameter Tuning Example

fromsklearnimportdatasetsfromsklearn.neighborsimportKNeighborsClassifierfromsklearn.model_selectionimportcross_val_scorefrommangoimportTuner, scheduler# search space for KNN classifier's hyperparameters# n_neighbors can vary between 1 and 50, with different choices of algorithmparam_space=dict(n_neighbors=range(1, 50),
algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
@scheduler.serialdefobjective(**params):
X, y=datasets.load_breast_cancer(return_X_y=True)
clf=KNeighborsClassifier(**params)
score=cross_val_score(clf, X, y, scoring='accuracy').mean()
returnscoretuner=Tuner(param_space, objective)
results=tuner.maximize()
print('best parameters:', results['best_params'])
print('best accuracy:', results['best_objective'])
# => best parameters: {'algorithm': 'ball_tree', 'n_neighbors': 11}# => best accuracy: 0.9332401800962584

Note that best parameters may be different but accuracy should be ~ 0.93. More examples are available in the examples directory (Facebook's Prophet, XGBoost, SVM).

4. Search Space

The search space defines the range and distribution of input parameters to the objective function. Mango search space is compatible with scikit-learn's parameter space definitions used in RandomizedSearchCV or GridSearchCV. The search space is defined as a dictionary with keys being the parameter names (string) and values being list of discreet choices, range of integers or the distributions.

Note

Mango does not scale or normalize the search space parameters by default. Users should use their judgement on whether input space needs to be normalized.

Example of some common search spaces are:

Integer

Following space defines x as an integer parameters with values in range(-10, 11) (11 is not included):

param_space=dict(x=range(-10, 11)) #=> -10, -9, ..., 10# you can use steps for sparse rangesparam_space=dict(x=range(0, 101, 10)) #=> 0, 10, 20, ..., 100

Integers are uniformly sampled from the given range and are assumed to be ordered and treated as continuous variables.

Categorical

Discreet categories can be defined as lists. For example:

# stringparam_space=dict(color=['red', 'blue', 'green'])
# floatparam_space=dict(v=[0.2, 0.1, 0.3])
# mixedparam_space=dict(max_features=['auto', 0.2, 0.3])

Lists are uniformly sampled and are assumed to be unordered. They are one-hot encoded internally.

Distributions

All the distributions, including multivariate, supported by scipy.stats are supported. In general, distributions must provide a rvs method for sampling.

Uniform distribution

Using uniform(loc, scale) one obtains the uniform distribution on [loc, loc + scale].

fromscipy.statsimportuniform# uniformly distributed between -1 and 1param_space=dict(a=uniform(-1, 2))

Log uniform distribution

We have added loguniform distribution by extending the scipy.stats.distributions constructs. Using loguniform(loc, scale) one obtains the loguniform distribution on [10loc, 10loc + scale].

frommango.domain.distributionimportloguniform# log uniformly distributed between 10^-3 and 10^-1param_space=dict(learning_rate=loguniform(-3, 2))

Hyperparameter search space examples

Example hyperparameter search space for Random Forest Classifier:

param_space=dict(
max_features=['sqrt', 'log2', .1, .3, .5, .7, .9],
n_estimators=range(10, 1000, 50), # 10 to 1000 in steps of 50bootstrap=[True, False],
max_depth=range(1, 20),
min_samples_leaf=range(1, 10)
)

Example search space for XGBoost Classifier:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_space= {
'n_estimators': range(10, 2001, 100), # 10 to 2000 in steps of 100'max_depth': range(1, 15), # 1 to 14'reg_alpha': loguniform(-3, 6), # 10^-3 to 10^3'booster': ['gbtree', 'gblinear'],
'colsample_bylevel': uniform(0.05, 0.95), # 0.05 to 1.0'colsample_bytree': uniform(0.05, 0.95), # 0.05 to 1.0'learning_rate': loguniform(-3, 3), # 0.001 to 1'reg_lambda': loguniform(-3, 6), # 10^-3 to 10^3'min_child_weight': loguniform(0, 2), # 1 to 100'subsample': uniform(0.1, 0.89) # 0.1 to 0.99
}

Example search space for SVM:

fromscipy.statsimportuniformfrommango.domain.distributionimportloguniformparam_dict= {
'kernel': ['rbf', 'sigmoid'],
'gamma': uniform(0.1, 4), # 0.1 to 4.1'C': loguniform(-7, 8) # 10^-7 to 10
}

5. Scheduler

Mango is designed to take advantage of distributed computing. The objective function can be scheduled to run locally or on a cluster with parallel evaluations. Mango is designed to allow the use of any distributed computing framework (like Celery or Kubernetes). The scheduler module comes with some pre-defined schedulers.

Serial scheduler

Serial scheduler runs locally with one objective function evaluation at a time

frommangoimportscheduler@scheduler.serialdefobjective(x):
returnx*x

Parallel scheduler

Parallel scheduler runs locally and uses joblib to evaluate the objective functions in parallel

frommangoimportscheduler@scheduler.parallel(n_jobs=2)defobjective(x):
returnx*x

n_jobs specifies the number of parallel evaluations. n_jobs = -1 uses all the available cpu cores on the machine. See simple_parallel for full working example.

Custom distributed scheduler

Users can define their own distribution strategies using custom scheduler. To do so, users need to define an objective function that takes a list of parameters and returns the list of results:

frommangoimportscheduler@scheduler.custom(n_jobs=4)defobjective(params_batch):
""" Template for custom distributed objective function Args: params_batch (list): Batch of parameter dictionaries to be evaluated in parallel Returns: list: Values of objective function at given parameters """# evaluate the objective on a distributed framework
...
returnresults

For example the following snippet uses Celery:

importceleryfrommangoimportTuner, scheduler# connect to celery backendapp=celery.Celery('simple_celery', backend='rpc://')
# remote celery task@app.taskdefremote_objective(x):
returnx*x@scheduler.custom(n_jobs=4)defobjective(params_batch):
jobs=celery.group(remote_objective.s(params['x']) forparamsinparams_batch)()
returnjobs.get()
param_space=dict(x=range(-10, 10))
tuner=Tuner(param_space, objective)
results=tuner.minimize()

A working example to tune hyperparameters of KNN using Celery is here.

6. Optional configurations

The default configuration parameters used by the Mango as below:

{'param_dict': ...,
'userObjective': ...,
'domain_size': 5000,
'initial_random': 1,
'num_iteration': 20,
'batch_size': 1}

The configuration parameters are:

  • domain_size: The size which is explored in each iteration by the gaussian process. Generally, a larger size is preferred if higher dimensional functions are optimized. More on this will be added with details about the internals of bayesian optimization.

  • initial_random: The number of random samples tried. Note: Mango returns all the random samples together. Users can exploit this to parallelize the random runs without any constraint.

  • num_iteration: The total number of iterations used by Mango to find the optimal value.

  • batch_size: The size of args_list passed to the objective function for parallel evaluation. For larger batch sizes, Mango internally uses intelligent sampling to decide the optimal samples to evaluate.

  • early_stopping: A Callable to specify custom stopping criteria. The callback has the following signature:

    defearly_stopping(results):
    ''' results is the same as dict returned by tuner keys available: params_tries, objective_values, best_objective, best_params '''
    ...
    returnTrue/False

    Early stopping is one of Mango's important features that allow to early terminate the current parallel search based on the custom user-designed criteria, such as the total optimization time spent, current validation accuracy achieved, or improvements in the past few iterations. For usage see early stopping examples notebook.

  • constraint: A callable to specify constraints on parameter space. It has the following signature:

    defconstraint(samples: List[dict]) ->List[bool]:
    ''' Given a list of samples (each sample is a dict with parameter names as keys) Returns a list of True/False elements indicating whether the corresponding sample satisfies the constraints or not '''

    See this notebook for an example.

  • initial_custom: A list of initial evaluation points to warm up the optimizer instead of random sampling. It can be either:

    • A list of dict with parameters. For example, for a search space with two parameters x1 and x2 the input could be: [{'x1': 10, 'x2': -5}, {'x1': 0, 'x2': 10}].
    • A list of tuple with parameters and objective function values. For example, if the objective function is to add x1 and x2 the input could be: [({'x1': 10, 'x2': -5}, 5), ({'x1': 0, 'x2': 10}, 10)].

    This allows the user to customize the initial evaluation points and therefore guide the optimization process. It also enables starting the optimizer from the results of a previous tuner run (see this notebook for a working example). Note that if initial_custom option is given then initial_random is ignored.

  • scale_params: True or False (default: False). Scales the search space parameter space using MinMaxScaler. Can be useful when the range of parameters is not comparable like below:

{
'x': uniform(-1, 2), # -1 to 1'y': uniform(-1000, 2000) # -1000 to 1000
}

However, use this option with caution as it could have unintended consequences.

  • log_progress: True or False (default: True). When True, Mango logs optimization progress with a tqdm-based progress bar and per-iteration best scores. Set this to False to suppress progress logging, which is useful in CI environments or when you want cleaner logs.

The configuration options can be modified, as shown below:

conf_dict=dict(num_iteration=40, domain_size=10000, initial_random=3)
tuner=Tuner(param_dict, objective, conf_dict)

7. Additional Features

Handling runtime failed evaluation

At runtime, failed evaluations are widespread in production deployments. Mango abstractions enable users to make progress even in the presence of failures by only using the correct evaluations. The syntax can return the successful evaluation, and the user can flexibly keep track of failures, for example, using timeouts. Examples showing the usage of Mango in the presence of failures: serial execution and parallel execution

Neural Architecture Search

Mango can also do an efficient neural architecture search. An example on the MNIST dataset to search for optimal filter sizes, the number of filters, etc., is available.

More extensive examples are available in the THIN-Bayes folder doing Neural Architecture Search for a class of neural networks and classical models for different regression and classification tasks.

8. Combiner Classifier Selection and Optimization (CASH)

Mango now provides a novel functionality of combined classifier selection and optimization. It allows developers to directly specify a set of classifiers along with their different hyperparameter spaces. Mango internally finds the best classifier along with the optimal parameters with the least possible number of overall iterations. The examples are available here

The important parts in the skeletion code are as below.

frommangoimportMetaTuner#define search spaces and objective functions as done for tuner.param_space_list= [param_space1, param_space2, param_space3, param_space4, ..]
objective_list= [objective_1, objective_2, objective_3, objective_4, ..]
metatuner=MetaTuner(param_space_list, objective_list)
results=metatuner.run()
print('best_objective:',results['best_objective'])
print('best_params:',results['best_params'])
print('best_objective_fid:',results['best_objective_fid'])

Participate

Core Papers to Cite Mango

More technical details are available in the Mango paper-1 (ICASSP 2020) and Mango paper-2 (CogMI 2021) Please cite them as:

@inproceedings{sandha2020mango,
title={Mango: A Python Library for Parallel Hyperparameter Tuning},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Fedorov, Igor and Srivastava, Mani},
booktitle={ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)},
pages={3987--3991},
year={2020},
organization={IEEE}
}
@inproceedings{sandha2021mango,
title={Enabling Hyperparameter Tuning of Machine Learning Classifiers in Production},
author={Sandha, Sandeep Singh and Aggarwal, Mohit and Saha, Swapnil Sayan and Srivastava, Mani},
booktitle={CogMI 2021, IEEE International Conference on Cognitive Machine Intelligence},
year={2021},
organization={IEEE}
}

Novel Applications built over Mango

@article{saha2022auritus,
title={Auritus: An open-source optimization toolkit for training and development of human movement models and filters using earables},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Pei, Siyou and Jain, Vivek and Wang, Ziqi and Li, Yuchen and Sarker, Ankur and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--34},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022tinyodom,
title={Tinyodom: Hardware-aware efficient neural inertial navigation},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Garcia, Luis Antonio and Srivastava, Mani},
journal={Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies},
volume={6},
number={2},
pages={1--32},
year={2022},
publisher={ACM New York, NY, USA}
}
@article{saha2022thin,
title={THIN-Bayes: Platform-Aware Machine Learning for Low-End IoT Devices},
author={Saha, Swapnil Sayan and Sandha, Sandeep Singh and Aggarwal, Mohit and Srivastava, Mani},
year={2022}
}

Slides

Slides explaining Mango abstractions and design choices are available. Mango Slides-1, Mango Slides-2.

Contribute

Please take a look at open issues if you are looking for areas to contribute to.

Questions

For any questions feel free to reach out by creating an issue here.