Hyperparameter Tuning#
[1]:
import ggml_ot
import numpy as np
ggml_ot.settings.random_seed = 42
In this tutorial, we explore how to automatically tune important hyperparameters of ggml-ot:
alpha: Target margin in the OT distance between distributions from the same and different classesreg: regularization strength on \(\mathbf{A}\)reg_type: norm used for the regularization, L11, L22, or nuclear normnuc.n_comps: rank of the latent subspace \(\mathbf{A}\)
First, we setup the Dataset from AnnData as before. To speedup the tutorial, we subsample each patient to n_cells=100 which can be increased (or omitted) on your own data.
[2]:
# Wrapper around load_cellxgene(...) + from_anndata(...) for this example dataset.
# See the dataset-loading tutorial for using your own AnnData object.
dataset = ggml_ot.data.myocardial_infarction(
n_top_genes=1000,
normalize=True,
n_cells=100,
)
[ggml_ot] Neither `path=` nor `ggml_ot.settings.datadir` is set; caching dataset under /home/kuehn/ot_metric_learning/gaussian-ground-metric-learning/code/ggml-ot_privat/docs/source/tutorials/data. Set `ggml_ot.settings.datadir = ...` or pass `path=` to override.
Grid Search over alpha, reg, reg_type and n_comps#
Here, we run the hyperparameter tuning to find the best hyperparameter combination for alpha and reg. This will lead to n_splits train-validation splits being trained and tested for hyperparameter combination.
You can also tune reg_type and n_comps with this function. In general, n_comps=2 is sufficient and preferable for visualization purposes and fast computation, but complex datasets may require more components. The choice of regularization type mostly depends on the downstream task. For example, to identify distinct marker genes L1 is useful, whereas gene enrichment analysis should be trained with L2 to include correlated genes.
Depending on the size of your dataset, the number of splits and hyperparameter combinations, the grid search may take a while!
[3]:
# Grids for alpha (triplet margin) and reg (regularization strength)
alpha_grid = np.logspace(-1, 1, 3) # [10^-1, 10^0, 10^1]
reg_grid = np.logspace(-3, -1, 3) # [10^-4, 10^-3, 10^-2]
As, scores = dataset.tune(
alpha=alpha_grid,
reg=reg_grid,
reg_type="fro",
n_comps=[5, 10, 20],
train_size=0.7,
n_splits=2,
scoring=["ari", "knn"],
)
| metric | knn | ari | epoch_time(s) | ||||||
|---|---|---|---|---|---|---|---|---|---|
| mean±SD | mean | SD | mean | SD | mean | SD | |||
| n_comps | reg_type | alpha | reg | ||||||
| 5 | fro | 0.10 | 0.00 | 0.89 | 0.00 | 0.77 | 0.14 | 2.36 | 0.25 |
| 0.01 | 0.83 | 0.06 | 0.81 | 0.10 | 3.09 | 0.05 | |||
| 0.10 | 0.83 | 0.06 | 0.54 | 0.09 | 2.79 | 0.22 | |||
| 1.00 | 0.00 | 0.89 | 0.00 | 0.83 | 0.08 | 2.12 | 0.06 | ||
| 0.01 | 0.83 | 0.06 | 0.77 | 0.14 | 2.13 | 0.65 | |||
| 0.10 | 0.89 | 0.00 | 0.81 | 0.10 | 1.55 | 0.13 | |||
| 10.00 | 0.00 | 0.83 | 0.06 | 0.87 | 0.04 | 1.45 | 0.17 | ||
| 0.01 | 0.89 | 0.00 | 0.91 | 0.00 | 1.41 | 0.00 | |||
| 0.10 | 0.83 | 0.06 | 0.91 | 0.00 | 1.50 | 0.02 | |||
| 10 | fro | 0.10 | 0.00 | 0.83 | 0.06 | 0.81 | 0.10 | 1.54 | 0.01 |
| 0.01 | 0.89 | 0.00 | 0.77 | 0.14 | 1.55 | 0.02 | |||
| 0.10 | 0.89 | 0.00 | 0.72 | 0.19 | 1.46 | 0.00 | |||
| 1.00 | 0.00 | 0.83 | 0.06 | 0.81 | 0.10 | 1.49 | 0.01 | ||
| 0.01 | 0.83 | 0.06 | 0.81 | 0.10 | 1.36 | 0.02 | |||
| 0.10 | 0.83 | 0.06 | 0.77 | 0.14 | 1.21 | 0.06 | |||
| 10.00 | 0.00 | 0.89 | 0.00 | 0.91 | 0.00 | 1.20 | 0.20 | ||
| 0.01 | 0.83 | 0.06 | 0.77 | 0.14 | 1.29 | 0.15 | |||
| 0.10 | 0.89 | 0.00 | 0.91 | 0.00 | 1.46 | 0.05 | |||
| 20 | fro | 0.10 | 0.00 | 0.83 | 0.06 | 0.81 | 0.10 | 1.55 | 0.17 |
| 0.01 | 0.83 | 0.06 | 0.81 | 0.10 | 1.47 | 0.04 | |||
| 0.10 | 0.89 | 0.00 | 0.77 | 0.14 | 1.28 | 0.16 | |||
| 1.00 | 0.00 | 0.83 | 0.06 | 0.81 | 0.10 | 1.32 | 0.09 | ||
| 0.01 | 0.83 | 0.06 | 0.81 | 0.10 | 1.25 | 0.18 | |||
| 0.10 | 0.89 | 0.00 | 0.81 | 0.10 | 2.05 | 0.52 | |||
| 10.00 | 0.00 | 0.83 | 0.06 | 0.81 | 0.10 | 1.35 | 0.02 | ||
| 0.01 | 0.89 | 0.00 | 0.91 | 0.00 | 1.50 | 0.13 | |||
| 0.10 | 0.89 | 0.00 | 0.81 | 0.10 | 1.44 | 0.03 | |||
Once tuning is complete, the function displays the performance of each hyperparameter combination on the validation set and returns:
As: a dict containing the learned transformations for each parameter combination (with the best performance across splits)scores: a dataframe of the performance of the considered hyperparameter combination, as shown above.
Using the scores dataframe and contour_hyperparams plotting fucntion, you can plot other parameter combinations and evaluation metrics as shown below:
[9]:
# KNN over alpha and reg
ggml_ot.pl.contour_hyperparams(
scores, x="alpha", y="reg", fixed_params={"reg_type": "fro", "n_comps": 5}, value_col=("knn", "mean")
)
[9]:
(<Figure size 640x480 with 2 Axes>, <Axes: xlabel='alpha', ylabel='reg'>)
[10]:
# KNN over n_comps and reg
ggml_ot.pl.contour_hyperparams(
scores,
x="n_comps",
y="reg",
fixed_params={"reg_type": "fro", "alpha": 10.0},
value_col=("knn", "mean"),
log_axis="y",
)
[10]:
(<Figure size 640x480 with 2 Axes>, <Axes: xlabel='n_comps', ylabel='reg'>)
Access best performing hyperparameters#
To get the best performing hyperparameters you can call .idxmax() on the respective column (e.g. mean classification accuracy ("knn","mean")) of the scores dataframe that the hyperparameter tuning returned.
[12]:
best_params = scores[("knn", "mean")].idxmax()
print("as tupple to access As and scores: " + str(best_params))
# Cast numpy scalars (np.int64, np.float64) to Python scalars for cleaner printing and kwargs
best_params_dict = {p: (v.item() if hasattr(v, "item") else v) for p, v in zip(scores.index.names, best_params)}
print("as dict to pass as parameters: " + str(best_params_dict))
as tupple to access As and scores: (np.int64(5), 'fro', np.float64(0.1), np.float64(0.001))
as dict to pass as parameters: {'n_comps': 5, 'reg_type': 'fro', 'alpha': 0.1, 'reg': 0.001}
We can also rerun the training (and testing) with the learned hyperparameters to show that the identified parameters reliable learn a performant ground metric.
[13]:
_ = dataset.train_test(**best_params_dict, plot_split=False)
| metric | knn | ari | epoch_time(s) | |||
|---|---|---|---|---|---|---|
| mean±SD | mean | SD | mean | SD | mean | SD |
| 0 | 0.85 | 0.08 | 0.68 | 0.18 | 1.08 | 0.04 |