
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "examples/examples_hpo/plot_hpo_text_classification.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_examples_examples_hpo_plot_hpo_text_classification.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_examples_examples_hpo_plot_hpo_text_classification.py:


Hyperparameter search for text classification
=============================================

**Author(s)**: Romain Egele, Brett Eiffert.

 
In this tutorial we present how to use hyperparameter optimization on a text classification analysis example from the Pytorch documentation.
 
**Reference**:
This tutorial is based on materials from the Pytorch Documentation: `Text classification with the torchtext library <https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html>`_

.. GENERATED FROM PYTHON SOURCE LINES 15-19

.. code-block:: bash

    %%bash
    pip install deephyper ray numpy==1.26.4 torch torchtext==0.17.2 torchdata==0.7.1 'portalocker>=2.0.0'

.. GENERATED FROM PYTHON SOURCE LINES 22-26

Imports
-------

All imports used in the tutorial are declared at the top of the file.

.. GENERATED FROM PYTHON SOURCE LINES 26-44

.. dropdown:: Code (Imports)

    .. code-block:: Python


        import ray
        import json
        from functools import partial

        import torch

        from torchtext.data.utils import get_tokenizer
        from torchtext.data.functional import to_map_style_dataset
        from torchtext.vocab import build_vocab_from_iterator
        from torchtext.datasets import AG_NEWS

        from torch.utils.data import DataLoader
        from torch.utils.data.dataset import random_split

        from torch import nn








.. GENERATED FROM PYTHON SOURCE LINES 45-48

.. note::
  The following can be used to detect if **CUDA** devices are available on the current host. Therefore, this notebook will automatically adapt the parallel execution based on the ressources available locally. However, it will not be the case if many compute nodes are requested.


.. GENERATED FROM PYTHON SOURCE LINES 50-51

If GPU is available, this code will enabled the tutorial to use the GPU for pytorch operations.

.. GENERATED FROM PYTHON SOURCE LINES 52-57

.. dropdown:: Code (Code to check if using CPU or GPU)

    .. code-block:: Python


        is_gpu_available = torch.cuda.is_available()
        n_gpus = torch.cuda.device_count()








.. GENERATED FROM PYTHON SOURCE LINES 58-63

The dataset
-----------

The torchtext library provides a few raw dataset iterators, which yield the raw text strings. For example, the :code:`AG_NEWS` dataset iterators yield the raw data as a tuple of label and text. It has four labels (1 : World 2 : Sports 3 : Business 4 : Sci/Tec).


.. GENERATED FROM PYTHON SOURCE LINES 63-81

.. dropdown:: Code (Loading the data)

    .. code-block:: Python


        def load_data(train_ratio, fast=False):
            train_iter, test_iter = AG_NEWS()
            train_dataset = to_map_style_dataset(train_iter)
            test_dataset = to_map_style_dataset(test_iter)
            num_train = int(len(train_dataset) * train_ratio)
            split_train, split_valid = \
                random_split(train_dataset, [num_train, len(train_dataset) - num_train])
    
            ## downsample
            if fast:
                split_train, _ = random_split(split_train, [int(len(split_train)*.05), int(len(split_train)*.95)])
                split_valid, _ = random_split(split_valid, [int(len(split_valid)*.05), int(len(split_valid)*.95)])
                test_dataset, _ = random_split(test_dataset, [int(len(test_dataset)*.05), int(len(test_dataset)*.95)])

            return split_train, split_valid, test_dataset








.. GENERATED FROM PYTHON SOURCE LINES 82-90

Preprocessing pipelines and Batch generation
--------------------------------------------

Here is an example for typical NLP data processing with tokenizer and vocabulary. The first step is to build a vocabulary with the raw training dataset. Here we use built in
factory function :code:`build_vocab_from_iterator` which accepts iterator that yield list or iterator of tokens. Users can also pass any special symbols to be added to the
vocabulary.

The vocabulary block converts a list of tokens into integers.

.. GENERATED FROM PYTHON SOURCE LINES 92-96

.. code-block:: python

  vocab(['here', 'is', 'an', 'example'])
  >>> [475, 21, 30, 5286]

.. GENERATED FROM PYTHON SOURCE LINES 98-99

The text pipeline converts a text string into a list of integers based on the lookup table defined in the vocabulary. The label pipeline converts the label into integers. For example,

.. GENERATED FROM PYTHON SOURCE LINES 101-107

.. code-block:: python

  text_pipeline('here is the an example')
  >>> [475, 21, 2, 30, 5286]
  label_pipeline('10')
  >>> 9 

.. GENERATED FROM PYTHON SOURCE LINES 107-138

.. dropdown:: Code (Code to tokenize and build vocabulary for text processing)

    .. code-block:: Python


        train_iter = AG_NEWS(split='train')
        num_class = 4

        tokenizer = get_tokenizer('basic_english')

        def yield_tokens(data_iter):
            for _, text in data_iter:
                yield tokenizer(text)

        vocab = build_vocab_from_iterator(yield_tokens(train_iter), specials=["<unk>"])
        vocab.set_default_index(vocab["<unk>"])
        vocab_size = len(vocab)

        text_pipeline = lambda x: vocab(tokenizer(x))
        label_pipeline = lambda x: int(x) - 1


        def collate_batch(batch, device):
            label_list, text_list, offsets = [], [], [0]
            for (_label, _text) in batch:
                label_list.append(label_pipeline(_label))
                processed_text = torch.tensor(text_pipeline(_text), dtype=torch.int64)
                text_list.append(processed_text)
                offsets.append(processed_text.size(0))
            label_list = torch.tensor(label_list, dtype=torch.int64)
            offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)
            text_list = torch.cat(text_list)
            return label_list.to(device), text_list.to(device), offsets.to(device)








.. GENERATED FROM PYTHON SOURCE LINES 139-141

.. note:: The :code:`collate_fn` function works on a batch of samples generated from :code:`DataLoader`. The input to :code:`collate_fn` is a batch of data with the batch size in :code:`DataLoader`, and :code:`collate_fn` processes them according to the data processing pipelines declared previously.


.. GENERATED FROM PYTHON SOURCE LINES 143-147

Define the model
----------------

The model is composed of the `nn.EmbeddingBag <https://pytorch.org/docs/stable/nn.html?highlight=embeddingbag#torch.nn.EmbeddingBag>`_ layer plus a linear layer for the classification purpose.

.. GENERATED FROM PYTHON SOURCE LINES 147-167

.. dropdown:: Code (Defining the Text Classification model)

    .. code-block:: Python


        class TextClassificationModel(nn.Module):

            def __init__(self, vocab_size, embed_dim, num_class):
                super().__init__()
                self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=False)
                self.fc = nn.Linear(embed_dim, num_class)
                self.init_weights()

            def init_weights(self):
                initrange = 0.5
                self.embedding.weight.data.uniform_(-initrange, initrange)
                self.fc.weight.data.uniform_(-initrange, initrange)
                self.fc.bias.data.zero_()

            def forward(self, text, offsets):
                embedded = self.embedding(text, offsets)
                return self.fc(embedded)








.. GENERATED FROM PYTHON SOURCE LINES 168-170

Define functions to train the model and evaluate results.
---------------------------------------------------------

.. GENERATED FROM PYTHON SOURCE LINES 170-194

.. dropdown:: Code (Define the training and evaluation of the Text Classification model)

    .. code-block:: Python


        def train(model, criterion, optimizer, dataloader):
            model.train()

            for _, (label, text, offsets) in enumerate(dataloader):
                optimizer.zero_grad()
                predicted_label = model(text, offsets)
                loss = criterion(predicted_label, label)
                loss.backward()
                torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1)
                optimizer.step()

        def evaluate(model, dataloader):
            model.eval()
            total_acc, total_count = 0, 0

            with torch.no_grad():
                for _, (label, text, offsets) in enumerate(dataloader):
                    predicted_label = model(text, offsets)
                    total_acc += (predicted_label.argmax(1) == label).sum().item()
                    total_count += label.size(0)
            return total_acc/total_count








.. GENERATED FROM PYTHON SOURCE LINES 195-205

Define the run-function
-----------------------

The run-function defines how the objective that we want to maximize is computed. It takes a :code:`config` dictionary as input and often returns a scalar value that we want to maximize. The :code:`config` contains a sample value of hyperparameters that we want to tune. In this example we will search for:

* :code:`num_epochs` (default value: :code:`10`)
* :code:`batch_size` (default value: :code:`64`)
* :code:`learning_rate` (default value: :code:`5`)

A hyperparameter value can be acessed easily in the dictionary through the corresponding key, for example :code:`config["units"]`.

.. GENERATED FROM PYTHON SOURCE LINES 205-232

.. dropdown:: Code (Run the Text Classification model)

    .. code-block:: Python


        def get_run(train_ratio=0.95):
          def run(config: dict):
            device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

            embed_dim = 64
    
            collate_fn = partial(collate_batch, device=device)
            split_train, split_valid, _ = load_data(train_ratio, fast=True) # set fast=false for longer running, more accurate example
            train_dataloader = DataLoader(split_train, batch_size=int(config["batch_size"]),
                                        shuffle=True, collate_fn=collate_fn)
            valid_dataloader = DataLoader(split_valid, batch_size=int(config["batch_size"]),
                                        shuffle=True, collate_fn=collate_fn)

            model = TextClassificationModel(vocab_size, int(embed_dim), num_class).to(device)
      
            criterion = torch.nn.CrossEntropyLoss()
            optimizer = torch.optim.SGD(model.parameters(), lr=config["learning_rate"])

            for _ in range(1, int(config["num_epochs"]) + 1):
                train(model, criterion, optimizer, train_dataloader)
    
            accu_test = evaluate(model, valid_dataloader)
            return accu_test
          return run








.. GENERATED FROM PYTHON SOURCE LINES 233-234

We create two versions of :code:`run`, one quicker to evaluate for the search, with a small training dataset, and another one, for performance evaluation, which uses a normal training/validation ratio.

.. GENERATED FROM PYTHON SOURCE LINES 236-239

.. code-block:: Python

    quick_run = get_run(train_ratio=0.3)
    perf_run = get_run(train_ratio=0.95)








.. GENERATED FROM PYTHON SOURCE LINES 240-243

.. note:: The objective maximised by DeepHyper is the scalar value returned by the :code:`run`-function.

In this tutorial it corresponds to the validation accuracy of the model after training.

.. GENERATED FROM PYTHON SOURCE LINES 245-255

Define the Hyperparameter optimization problem
---------------------------------------------- 

Hyperparameter ranges are defined using the following syntax:

* Discrete integer ranges are generated from a tuple :code:`(lower: int, upper: int)`
* Continuous prarameters are generated from a tuple :code:`(lower: float, upper: float)`
* Categorical or nonordinal hyperparameter ranges can be given as a list of possible values :code:`[val1, val2, ...]`

We provide the default configuration of hyperparameters as a starting point of the problem.

.. GENERATED FROM PYTHON SOURCE LINES 257-270

.. code-block:: Python

    from deephyper.hpo import HpProblem

    problem = HpProblem()

    # Discrete hyperparameter (sampled with uniform prior)
    problem.add_hyperparameter((5, 20), "num_epochs", default_value=10)

    # Discrete and Real hyperparameters (sampled with log-uniform)
    problem.add_hyperparameter((8, 512, "log-uniform"), "batch_size", default_value=64)
    problem.add_hyperparameter((0.1, 10, "log-uniform"), "learning_rate", default_value=5)

    problem





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    Configuration space object:
      Hyperparameters:
        batch_size, Type: UniformInteger, Range: [8, 512], Default: 64, on log-scale
        learning_rate, Type: UniformFloat, Range: [0.1, 10.0], Default: 5.0, on log-scale
        num_epochs, Type: UniformInteger, Range: [5, 20], Default: 10




.. GENERATED FROM PYTHON SOURCE LINES 271-275

Evaluate a default configuration
--------------------------------

We evaluate the performance of the default set of hyperparameters provided in the Pytorch tutorial.

.. GENERATED FROM PYTHON SOURCE LINES 275-292

.. code-block:: Python


    #We launch the Ray run-time and execute the `run` function
    #with the default configuration
    if is_gpu_available:
        if not(ray.is_initialized()):
            ray.init(num_cpus=n_gpus, num_gpus=n_gpus, log_to_driver=False)
    
        run_default = ray.remote(num_cpus=1, num_gpus=1)(perf_run)
        objective_default = ray.get(run_default.remote(problem.default_configuration))
    else:
        if not(ray.is_initialized()):
            ray.init(num_cpus=1, log_to_driver=False)
        run_default = perf_run
        objective_default = run_default(problem.default_configuration)

    print(f"Accuracy Default Configuration:  {objective_default:.3f}")





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    2025-08-18 14:44:20,921 INFO worker.py:1843 -- Started a local Ray instance. View the dashboard at http://127.0.0.1:8265 
    Accuracy Default Configuration:  0.863




.. GENERATED FROM PYTHON SOURCE LINES 293-299

Define the evaluator object
---------------------------

The :code:`Evaluator` object allows to change the parallelization backend used by DeepHyper.  
It is a standalone object which schedules the execution of remote tasks. All evaluators needs a :code:`run_function` to be instantiated.  
Then a keyword :code:`method` defines the backend (e.g., :code:`"ray"`) and the :code:`method_kwargs` corresponds to keyword arguments of this chosen :code:`method`.

.. GENERATED FROM PYTHON SOURCE LINES 301-304

.. code-block:: python

  evaluator = Evaluator.create(run_function, method, method_kwargs)

.. GENERATED FROM PYTHON SOURCE LINES 306-309

Once created the :code:`evaluator.num_workers` gives access to the number of available parallel workers.

Finally, to submit and collect tasks to the evaluator one just needs to use the following interface:

.. GENERATED FROM PYTHON SOURCE LINES 311-318

.. code-block:: python

 	configs = [...]
 	evaluator.submit(configs)
	...
	tasks_done = evaluator.get("BATCH", size=1) # For asynchronous
	tasks_done = evaluator.get("ALL") # For batch synchronous

.. GENERATED FROM PYTHON SOURCE LINES 320-321

.. warning:: Each `Evaluator` saves its own state, therefore it is crucial to create a new evaluator when launching a fresh search.

.. GENERATED FROM PYTHON SOURCE LINES 323-353

.. code-block:: Python

    from deephyper.evaluator import Evaluator
    from deephyper.evaluator.callback import TqdmCallback

    def get_evaluator(run_function):
        # Default arguments for Ray: 1 worker and 1 worker per evaluation
        method_kwargs = {
            "num_cpus": 1, 
            "num_cpus_per_task": 1,
            "callbacks": [TqdmCallback()]
        }

        # If GPU devices are detected then it will create 'n_gpus' workers
        # and use 1 worker for each evaluation
        if is_gpu_available:
            method_kwargs["num_cpus"] = n_gpus
            method_kwargs["num_gpus"] = n_gpus
            method_kwargs["num_cpus_per_task"] = 1
            method_kwargs["num_gpus_per_task"] = 1

        evaluator = Evaluator.create(
            run_function, 
            method="ray", 
            method_kwargs=method_kwargs
        )
        print(f"Created new evaluator with {evaluator.num_workers} worker{'s' if evaluator.num_workers > 1 else ''} and config: {method_kwargs}", )
    
        return evaluator

    evaluator = get_evaluator(quick_run)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Created new evaluator with 1 worker and config: {'num_cpus': 1, 'num_cpus_per_task': 1, 'callbacks': [<deephyper.evaluator.callback.TqdmCallback object at 0x3a52a0b00>]}




.. GENERATED FROM PYTHON SOURCE LINES 354-358

Define and run the Centralized Bayesian Optimization search (CBO)
-----------------------------------------------------------------

We create the CBO using the :code:`problem` and :code:`evaluator` defined above.

.. GENERATED FROM PYTHON SOURCE LINES 360-362

.. code-block:: Python

    from deephyper.hpo import CBO








.. GENERATED FROM PYTHON SOURCE LINES 363-364

Instanciate the search with the problem and a specific evaluator

.. GENERATED FROM PYTHON SOURCE LINES 364-366

.. code-block:: Python

    search = CBO(problem)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Results file already exists, it will be renamed to /Users/rp5/Documents/DeepHyper/deephyper/examples/examples_hpo/results_20250818-144426.csv




.. GENERATED FROM PYTHON SOURCE LINES 367-372

.. note:: 
  All DeepHyper's search algorithm have two stopping criteria:
      * :code:`max_evals (int)`: Defines the maximum number of evaluations that we want to perform. Default to :code:`-1` for an infinite number.
      * :code:`timeout (int)`: Defines a time budget (in seconds) before stopping the search. Default to :code:`None` for an infinite time budget.


.. GENERATED FROM PYTHON SOURCE LINES 374-376

.. code-block:: Python

    results = search.search(evaluator, max_evals=30)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

      0%|          | 0/30 [00:00<?, ?it/s]      3%|▎         | 1/30 [00:00<00:00, 5398.07it/s, failures=0, objective=0.385]      7%|▋         | 2/30 [00:02<00:32,  1.16s/it, failures=0, objective=0.385]        7%|▋         | 2/30 [00:02<00:32,  1.16s/it, failures=0, objective=0.602]     10%|█         | 3/30 [00:06<01:07,  2.49s/it, failures=0, objective=0.602]     10%|█         | 3/30 [00:06<01:07,  2.49s/it, failures=0, objective=0.602]     13%|█▎        | 4/30 [00:08<00:57,  2.21s/it, failures=0, objective=0.602]     13%|█▎        | 4/30 [00:08<00:57,  2.21s/it, failures=0, objective=0.69]      17%|█▋        | 5/30 [00:09<00:48,  1.93s/it, failures=0, objective=0.69]     17%|█▋        | 5/30 [00:09<00:48,  1.93s/it, failures=0, objective=0.69]     20%|██        | 6/30 [00:12<00:51,  2.15s/it, failures=0, objective=0.69]     20%|██        | 6/30 [00:12<00:51,  2.15s/it, failures=0, objective=0.74]     23%|██▎       | 7/30 [00:14<00:51,  2.25s/it, failures=0, objective=0.74]     23%|██▎       | 7/30 [00:14<00:51,  2.25s/it, failures=0, objective=0.74]     27%|██▋       | 8/30 [00:16<00:45,  2.08s/it, failures=0, objective=0.74]     27%|██▋       | 8/30 [00:16<00:45,  2.08s/it, failures=0, objective=0.74]     30%|███       | 9/30 [00:22<01:11,  3.38s/it, failures=0, objective=0.74]     30%|███       | 9/30 [00:22<01:11,  3.38s/it, failures=0, objective=0.816]     33%|███▎      | 10/30 [00:31<01:41,  5.09s/it, failures=0, objective=0.816]     33%|███▎      | 10/30 [00:31<01:41,  5.09s/it, failures=0, objective=0.816]     37%|███▋      | 11/30 [00:42<02:07,  6.73s/it, failures=0, objective=0.816]     37%|███▋      | 11/30 [00:42<02:07,  6.73s/it, failures=0, objective=0.82]      40%|████      | 12/30 [00:48<02:00,  6.69s/it, failures=0, objective=0.82]     40%|████      | 12/30 [00:48<02:00,  6.69s/it, failures=0, objective=0.82]     43%|████▎     | 13/30 [00:59<02:14,  7.90s/it, failures=0, objective=0.82]     43%|████▎     | 13/30 [00:59<02:14,  7.90s/it, failures=0, objective=0.82]     47%|████▋     | 14/30 [01:08<02:11,  8.20s/it, failures=0, objective=0.82]     47%|████▋     | 14/30 [01:08<02:11,  8.20s/it, failures=0, objective=0.82]     50%|█████     | 15/30 [01:15<01:56,  7.76s/it, failures=0, objective=0.82]     50%|█████     | 15/30 [01:15<01:56,  7.76s/it, failures=0, objective=0.82]     53%|█████▎    | 16/30 [01:22<01:45,  7.53s/it, failures=0, objective=0.82]     53%|█████▎    | 16/30 [01:22<01:45,  7.53s/it, failures=0, objective=0.82]     57%|█████▋    | 17/30 [01:32<01:49,  8.41s/it, failures=0, objective=0.82]     57%|█████▋    | 17/30 [01:32<01:49,  8.41s/it, failures=0, objective=0.82]     60%|██████    | 18/30 [01:41<01:42,  8.56s/it, failures=0, objective=0.82]     60%|██████    | 18/30 [01:41<01:42,  8.56s/it, failures=0, objective=0.82]     63%|██████▎   | 19/30 [01:45<01:18,  7.11s/it, failures=0, objective=0.82]     63%|██████▎   | 19/30 [01:45<01:18,  7.11s/it, failures=0, objective=0.82]     67%|██████▋   | 20/30 [01:54<01:18,  7.86s/it, failures=0, objective=0.82]     67%|██████▋   | 20/30 [01:54<01:18,  7.86s/it, failures=0, objective=0.82]     70%|███████   | 21/30 [02:00<01:03,  7.08s/it, failures=0, objective=0.82]     70%|███████   | 21/30 [02:00<01:03,  7.08s/it, failures=0, objective=0.82]     73%|███████▎  | 22/30 [02:05<00:52,  6.62s/it, failures=0, objective=0.82]     73%|███████▎  | 22/30 [02:05<00:52,  6.62s/it, failures=0, objective=0.82]     77%|███████▋  | 23/30 [02:11<00:44,  6.39s/it, failures=0, objective=0.82]     77%|███████▋  | 23/30 [02:11<00:44,  6.39s/it, failures=0, objective=0.82]     80%|████████  | 24/30 [02:17<00:38,  6.35s/it, failures=0, objective=0.82]     80%|████████  | 24/30 [02:17<00:38,  6.35s/it, failures=0, objective=0.82]     83%|████████▎ | 25/30 [02:25<00:33,  6.65s/it, failures=0, objective=0.82]     83%|████████▎ | 25/30 [02:25<00:33,  6.65s/it, failures=0, objective=0.82]     87%|████████▋ | 26/30 [02:35<00:31,  7.81s/it, failures=0, objective=0.82]     87%|████████▋ | 26/30 [02:35<00:31,  7.81s/it, failures=0, objective=0.82]     90%|█████████ | 27/30 [02:41<00:21,  7.21s/it, failures=0, objective=0.82]     90%|█████████ | 27/30 [02:41<00:21,  7.21s/it, failures=0, objective=0.82]     93%|█████████▎| 28/30 [02:46<00:13,  6.69s/it, failures=0, objective=0.82]     93%|█████████▎| 28/30 [02:46<00:13,  6.69s/it, failures=0, objective=0.82]     97%|█████████▋| 29/30 [02:52<00:06,  6.25s/it, failures=0, objective=0.82]     97%|█████████▋| 29/30 [02:52<00:06,  6.25s/it, failures=0, objective=0.82]    100%|██████████| 30/30 [02:56<00:00,  5.62s/it, failures=0, objective=0.82]    100%|██████████| 30/30 [02:56<00:00,  5.62s/it, failures=0, objective=0.82]    100%|██████████| 30/30 [02:56<00:00,  5.88s/it, failures=0, objective=0.82]




.. GENERATED FROM PYTHON SOURCE LINES 377-383

The returned :code:`results` is a Pandas Dataframe where columns are hyperparameters and information stored by the evaluator:

* :code:`job_id` is a unique identifier corresponding to the order of creation of tasks
* :code:`objective` is the value returned by the run-function
* :code:`timestamp_submit` is the time (in seconds) when the hyperparameter configuration was submitted by the :code:`Evaluator` relative to the creation of the evaluator.
* :code:`timestamp_gather` is the time (in seconds) when the hyperparameter configuration was collected by the :code:`Evaluator` relative to the creation of the evaluator.

.. GENERATED FROM PYTHON SOURCE LINES 385-387

.. code-block:: Python

    results






.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <div>
    <style scoped>
        .dataframe tbody tr th:only-of-type {
            vertical-align: middle;
        }

        .dataframe tbody tr th {
            vertical-align: top;
        }

        .dataframe thead th {
            text-align: right;
        }
    </style>
    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>p:batch_size</th>
          <th>p:learning_rate</th>
          <th>p:num_epochs</th>
          <th>objective</th>
          <th>job_id</th>
          <th>job_status</th>
          <th>m:timestamp_submit</th>
          <th>m:timestamp_gather</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>0</th>
          <td>245</td>
          <td>1.631048</td>
          <td>9</td>
          <td>0.385000</td>
          <td>0</td>
          <td>DONE</td>
          <td>0.806100</td>
          <td>3.504088</td>
        </tr>
        <tr>
          <th>1</th>
          <td>56</td>
          <td>1.112981</td>
          <td>16</td>
          <td>0.601667</td>
          <td>1</td>
          <td>DONE</td>
          <td>3.526653</td>
          <td>5.828167</td>
        </tr>
        <tr>
          <th>2</th>
          <td>23</td>
          <td>0.143010</td>
          <td>16</td>
          <td>0.394524</td>
          <td>2</td>
          <td>DONE</td>
          <td>5.839790</td>
          <td>10.173068</td>
        </tr>
        <tr>
          <th>3</th>
          <td>264</td>
          <td>5.976338</td>
          <td>17</td>
          <td>0.690000</td>
          <td>3</td>
          <td>DONE</td>
          <td>10.184379</td>
          <td>11.913512</td>
        </tr>
        <tr>
          <th>4</th>
          <td>136</td>
          <td>1.760105</td>
          <td>8</td>
          <td>0.425714</td>
          <td>4</td>
          <td>DONE</td>
          <td>11.925383</td>
          <td>13.314167</td>
        </tr>
        <tr>
          <th>5</th>
          <td>82</td>
          <td>2.249590</td>
          <td>20</td>
          <td>0.739524</td>
          <td>5</td>
          <td>DONE</td>
          <td>13.325365</td>
          <td>15.923063</td>
        </tr>
        <tr>
          <th>6</th>
          <td>53</td>
          <td>0.913211</td>
          <td>14</td>
          <td>0.563095</td>
          <td>6</td>
          <td>DONE</td>
          <td>15.934397</td>
          <td>18.385043</td>
        </tr>
        <tr>
          <th>7</th>
          <td>283</td>
          <td>3.305364</td>
          <td>19</td>
          <td>0.590714</td>
          <td>7</td>
          <td>DONE</td>
          <td>18.615469</td>
          <td>20.076355</td>
        </tr>
        <tr>
          <th>8</th>
          <td>17</td>
          <td>2.536505</td>
          <td>20</td>
          <td>0.816429</td>
          <td>8</td>
          <td>DONE</td>
          <td>20.309002</td>
          <td>26.365440</td>
        </tr>
        <tr>
          <th>9</th>
          <td>11</td>
          <td>2.086957</td>
          <td>20</td>
          <td>0.815714</td>
          <td>9</td>
          <td>DONE</td>
          <td>26.609885</td>
          <td>35.309791</td>
        </tr>
        <tr>
          <th>10</th>
          <td>9</td>
          <td>8.421344</td>
          <td>20</td>
          <td>0.820238</td>
          <td>10</td>
          <td>DONE</td>
          <td>35.544787</td>
          <td>45.785644</td>
        </tr>
        <tr>
          <th>11</th>
          <td>16</td>
          <td>0.911853</td>
          <td>20</td>
          <td>0.746905</td>
          <td>11</td>
          <td>DONE</td>
          <td>46.023974</td>
          <td>52.367163</td>
        </tr>
        <tr>
          <th>12</th>
          <td>9</td>
          <td>4.070022</td>
          <td>20</td>
          <td>0.803571</td>
          <td>12</td>
          <td>DONE</td>
          <td>52.705372</td>
          <td>63.077662</td>
        </tr>
        <tr>
          <th>13</th>
          <td>11</td>
          <td>2.122347</td>
          <td>20</td>
          <td>0.809286</td>
          <td>13</td>
          <td>DONE</td>
          <td>63.321248</td>
          <td>71.979538</td>
        </tr>
        <tr>
          <th>14</th>
          <td>16</td>
          <td>6.979859</td>
          <td>20</td>
          <td>0.807143</td>
          <td>14</td>
          <td>DONE</td>
          <td>72.221648</td>
          <td>78.707475</td>
        </tr>
        <tr>
          <th>15</th>
          <td>15</td>
          <td>1.276222</td>
          <td>20</td>
          <td>0.770476</td>
          <td>15</td>
          <td>DONE</td>
          <td>78.946452</td>
          <td>85.686414</td>
        </tr>
        <tr>
          <th>16</th>
          <td>9</td>
          <td>1.361241</td>
          <td>20</td>
          <td>0.800476</td>
          <td>16</td>
          <td>DONE</td>
          <td>85.925403</td>
          <td>96.158468</td>
        </tr>
        <tr>
          <th>17</th>
          <td>11</td>
          <td>2.886584</td>
          <td>20</td>
          <td>0.807619</td>
          <td>17</td>
          <td>DONE</td>
          <td>96.397284</td>
          <td>105.057524</td>
        </tr>
        <tr>
          <th>18</th>
          <td>36</td>
          <td>0.523676</td>
          <td>20</td>
          <td>0.582857</td>
          <td>18</td>
          <td>DONE</td>
          <td>105.291716</td>
          <td>108.786150</td>
        </tr>
        <tr>
          <th>19</th>
          <td>10</td>
          <td>0.765039</td>
          <td>20</td>
          <td>0.746905</td>
          <td>19</td>
          <td>DONE</td>
          <td>109.025325</td>
          <td>118.416570</td>
        </tr>
        <tr>
          <th>20</th>
          <td>22</td>
          <td>7.267154</td>
          <td>20</td>
          <td>0.818095</td>
          <td>20</td>
          <td>DONE</td>
          <td>118.738970</td>
          <td>123.678590</td>
        </tr>
        <tr>
          <th>21</th>
          <td>20</td>
          <td>9.786512</td>
          <td>20</td>
          <td>0.806190</td>
          <td>21</td>
          <td>DONE</td>
          <td>123.911904</td>
          <td>129.223925</td>
        </tr>
        <tr>
          <th>22</th>
          <td>19</td>
          <td>8.426698</td>
          <td>20</td>
          <td>0.805714</td>
          <td>22</td>
          <td>DONE</td>
          <td>129.460490</td>
          <td>135.063884</td>
        </tr>
        <tr>
          <th>23</th>
          <td>17</td>
          <td>6.601954</td>
          <td>20</td>
          <td>0.816190</td>
          <td>23</td>
          <td>DONE</td>
          <td>135.300321</td>
          <td>141.337653</td>
        </tr>
        <tr>
          <th>24</th>
          <td>14</td>
          <td>8.959608</td>
          <td>20</td>
          <td>0.798571</td>
          <td>24</td>
          <td>DONE</td>
          <td>141.570983</td>
          <td>148.691888</td>
        </tr>
        <tr>
          <th>25</th>
          <td>9</td>
          <td>8.727873</td>
          <td>20</td>
          <td>0.815952</td>
          <td>25</td>
          <td>DONE</td>
          <td>148.930730</td>
          <td>159.216285</td>
        </tr>
        <tr>
          <th>26</th>
          <td>19</td>
          <td>6.263893</td>
          <td>20</td>
          <td>0.799762</td>
          <td>26</td>
          <td>DONE</td>
          <td>159.453678</td>
          <td>165.011176</td>
        </tr>
        <tr>
          <th>27</th>
          <td>21</td>
          <td>8.539551</td>
          <td>20</td>
          <td>0.814524</td>
          <td>27</td>
          <td>DONE</td>
          <td>165.337578</td>
          <td>170.484569</td>
        </tr>
        <tr>
          <th>28</th>
          <td>22</td>
          <td>1.172272</td>
          <td>20</td>
          <td>0.751429</td>
          <td>28</td>
          <td>DONE</td>
          <td>170.722989</td>
          <td>175.696918</td>
        </tr>
        <tr>
          <th>29</th>
          <td>30</td>
          <td>5.805169</td>
          <td>20</td>
          <td>0.796190</td>
          <td>29</td>
          <td>DONE</td>
          <td>175.931295</td>
          <td>179.869023</td>
        </tr>
      </tbody>
    </table>
    </div>
    </div>
    <br />
    <br />

.. GENERATED FROM PYTHON SOURCE LINES 388-392

Evaluate the best configuration
-------------------------------

Now that the search is over, let us print the best configuration found during this run and evaluate it on the full training dataset.

.. GENERATED FROM PYTHON SOURCE LINES 394-404

.. code-block:: Python

    i_max = results.objective.argmax()
    best_config = results.iloc[i_max][:-3].to_dict()
    best_config = {k[2:]: v for k, v in best_config.items() if k.startswith("p:")}

    print(f"The default configuration has an accuracy of {objective_default:.3f}. \n" 
          f"The best configuration found by DeepHyper has an accuracy {results['objective'].iloc[i_max]:.3f}, \n" 
          f"finished after {results['m:timestamp_gather'].iloc[i_max]:.2f} secondes of search.\n")

    print(json.dumps(best_config, indent=4))





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    The default configuration has an accuracy of 0.863. 
    The best configuration found by DeepHyper has an accuracy 0.820, 
    finished after 45.79 secondes of search.

    {
        "batch_size": 9,
        "learning_rate": 8.421343891942513,
        "num_epochs": 20
    }




.. GENERATED FROM PYTHON SOURCE LINES 405-407

.. code-block:: Python

    objective_best = perf_run(best_config)
    print(f"Accuracy Best Configuration:  {objective_best:.3f}")




.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Accuracy Best Configuration:  0.807





.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (3 minutes 47.673 seconds)


.. _sphx_glr_download_examples_examples_hpo_plot_hpo_text_classification.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_hpo_text_classification.ipynb <plot_hpo_text_classification.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_hpo_text_classification.py <plot_hpo_text_classification.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: plot_hpo_text_classification.zip <plot_hpo_text_classification.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
