{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Comparing randomized search and grid search for hyperparameter estimation\n\nCompare several strategies to optimize the hyperparameters of a linear SVM\ntrained with stochastic gradient descent. We score the candidates with the\none-vs-rest ROC AUC (``roc_auc_ovr``), which evaluates the ranking quality of the\npredicted class probabilities rather than the raw accuracy of the hard labels.\n\nWe start with an exhaustive grid search\n(:class:`~sklearn.model_selection.GridSearchCV`) that evaluates every combination\nof a discretized parameter grid. Because the grid is fixed, we are forced to fit\nevery configuration and we may even miss a good combination that falls between\ntwo grid points.\n\nWe then run a randomized search\n(:class:`~sklearn.model_selection.RandomizedSearchCV`) that samples the parameter\nspace instead of discretizing it. With a smaller budget it explores the space\nmore efficiently and reaches an equivalent solution with fewer iterations.\n\nFinally, we run a successive halving search\n(:class:`~sklearn.model_selection.HalvingRandomSearchCV`) that samples even more\ncandidates but keeps the cost low by evaluating them on a small number of\ntraining samples first and discarding the unpromising ones early. It combines a\nlarge number of candidates with a reduced fit and predict time in the early\niterations.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Loading the dataset\n\nWe use the digits dataset and restrict ourselves to the first three classes to\nkeep the problem small and the search fast.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.datasets import load_digits\n\nX, y = load_digits(return_X_y=True, n_class=3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Defining the estimator\n\nWe optimize a linear SVM trained with stochastic gradient descent\n(:class:`~sklearn.linear_model.SGDClassifier`). We use the ``\"modified_huber\"``\nloss, a smoothed variant of the hinge loss: it keeps the large-margin behavior\nof a linear SVM while also exposing :term:`predict_proba`. The probability\nestimates are required to score the candidates with the one-vs-rest ROC AUC,\nwhich the plain hinge loss could not provide.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.linear_model import SGDClassifier\n\nlinear_svm = SGDClassifier(\n    loss=\"modified_huber\",\n    penalty=\"elasticnet\",\n    fit_intercept=True,\n    max_iter=5_000,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The ``report`` helper below prints the best parameter settings found by a\ngiven search so that we can compare the different strategies.\n\nSuccessive halving stores in ``cv_results_`` the candidates evaluated at every\niteration, on increasing amounts of resources. The early iterations are scored\non a small subset of the data, where perfect but unreliable scores are common.\nTo keep the comparison fair, when an ``\"iter\"`` column is present we only keep\nthe last iteration, i.e. the surviving candidates trained on the full set of\nresources, and we rank candidates by their mean validation score.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import pandas as pd\n\n\ndef report(results, n_top=3):\n    \"\"\"Report the top parameters for each search strategy.\"\"\"\n    results = pd.DataFrame(results)\n    if \"iter\" in results:\n        results = results[results[\"iter\"] == results[\"iter\"].max()]\n\n    for rank, (_, candidate) in enumerate(\n        results.nlargest(n_top, \"mean_test_score\").iterrows(), start=1\n    ):\n        print(\n            f\"Model with rank: {rank}\\n\"\n            f\"Mean validation score: \"\n            f\"{candidate['mean_test_score']:.3f} \"\n            f\"(std: {candidate['std_test_score']:.3f})\\n\"\n            f\"Parameters: {candidate['params']}\\n\"\n        )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Grid search\n\n:class:`~sklearn.model_selection.GridSearchCV` explores the entire parameter\nspace defined as a grid. Continuous parameters therefore have to be discretized\nbeforehand and every combination of the grid is evaluated. Two limitations\nfollow from this design: we are forced to fit and score each configuration,\neven the unpromising ones, and the best hyperparameters may lie between two grid\npoints and thus be missed entirely.\n\nSome configurations do not let :class:`~sklearn.linear_model.SGDClassifier`\nconverge and raise a :class:`~sklearn.exceptions.ConvergenceWarning`. These\ncorrespond to the poorly performing configurations that the search is meant to\nexplore and discard, so it is fine to silence the warning with a\n:func:`warnings.catch_warnings` context manager to keep the output readable.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import warnings\nfrom time import time\n\nimport numpy as np\n\nfrom sklearn.exceptions import ConvergenceWarning\nfrom sklearn.model_selection import GridSearchCV\n\nparam_grid = {\n    \"average\": [True, False],\n    \"l1_ratio\": np.linspace(0, 1, num=10),\n    \"alpha\": np.power(10, np.arange(-2, 1, dtype=float)),\n}\n\ngrid_search = GridSearchCV(linear_svm, param_grid=param_grid, scoring=\"roc_auc_ovr\")\nstart = time()\nwith warnings.catch_warnings():\n    warnings.simplefilter(\"ignore\", category=ConvergenceWarning)\n    grid_search.fit(X, y)\n\nprint(\n    f\"GridSearchCV took {time() - start:.2f} seconds for \"\n    f\"{len(grid_search.cv_results_['params'])} candidate parameter settings.\"\n)\nreport(grid_search.cv_results_)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Randomized search\n\n:class:`~sklearn.model_selection.RandomizedSearchCV` samples a fixed number of\ncandidates from the parameter distributions instead of evaluating a predefined\ngrid. Sampling lets us explore the continuous distributions directly and spend\nour budget where it matters. Here we use only half as many candidates as the\ngrid above, yet the randomized search reaches results equivalent to the grid\nsearch while fitting far fewer configurations.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import scipy.stats as stats\n\nfrom sklearn.model_selection import RandomizedSearchCV\n\nparam_dist = {\n    \"average\": [True, False],\n    \"l1_ratio\": stats.uniform(0, 1),\n    \"alpha\": stats.loguniform(1e-2, 1e0),\n}\n\nn_iter_search = 30\nrandom_search = RandomizedSearchCV(\n    linear_svm,\n    param_distributions=param_dist,\n    n_iter=n_iter_search,\n    scoring=\"roc_auc_ovr\",\n    random_state=42,\n)\n\nstart = time()\nwith warnings.catch_warnings():\n    warnings.simplefilter(\"ignore\", category=ConvergenceWarning)\n    random_search.fit(X, y)\nprint(\n    f\"RandomizedSearchCV took {time() - start:.2f} seconds for {n_iter_search} \"\n    f\"candidates parameter settings.\"\n)\nreport(random_search.cv_results_)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Successive halving search\n\n:class:`~sklearn.model_selection.HalvingRandomSearchCV` samples candidates like\nthe randomized search, but evaluates them on increasing amounts of resources\n(here the number of training samples). It starts with many candidates trained\non a small subset of the data and, at each iteration, keeps only the most\npromising ones and grants them more samples. We therefore get the best of both\nworlds: a large number of candidates -- which makes it more likely to find a\ngood configuration -- while keeping the fit and predict cost low in the early\niterations where most candidates are discarded.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.experimental import enable_halving_search_cv  # noqa: F401\nfrom sklearn.model_selection import HalvingRandomSearchCV\n\nn_candidates = 60\nhalving_search = HalvingRandomSearchCV(\n    linear_svm,\n    param_distributions=param_dist,\n    n_candidates=n_candidates,\n    scoring=\"roc_auc_ovr\",\n    random_state=42,\n    min_resources=100,\n)\nstart = time()\nwith warnings.catch_warnings():\n    warnings.simplefilter(\"ignore\", category=ConvergenceWarning)\n    halving_search.fit(X, y)\n\nprint(\n    f\"HalvingRandomSearchCV took {time() - start:.2f} seconds for \"\n    f\"{halving_search.n_candidates_[0]} initial candidate parameter settings.\"\n)\nreport(halving_search.cv_results_)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Conclusion\n\nRunning the three searches on the same problem highlights their trade-offs:\n\n- **Grid search** evaluates all 60 combinations of the grid and reaches a best\n  mean validation ROC AUC of essentially 1.0. It is exhaustive, but its cost\n  grows with the resolution of the grid and a finer grid would be needed to\n  refine the continuous parameters, making it the slowest of the three.\n- **Randomized search** reaches an essentially equivalent score while sampling\n  only 30 candidates, i.e. half the budget, and is therefore markedly faster.\n  Drawing the continuous parameters from distributions is usually a better use\n  of a limited budget than refining a grid.\n- **Successive halving** screens the 60 candidates for a run time comparable to\n  the randomized search by spending most of its resources only on the most\n  promising candidates. It explores more candidates than the randomized search\n  without paying the full cost of the grid search.\n\nA word of caution when reading the halving output: the ``cv_results_`` of\n:class:`~sklearn.model_selection.HalvingRandomSearchCV` aggregates every\niteration, including the first ones evaluated on very few samples where perfect\nbut unreliable scores are common. This is why the ``report`` helper above keeps\nonly the last iteration for the halving search, so that the reported scores are\ncomputed on the full set of resources and remain comparable to the grid and\nrandomized searches. More generally, rely on ``best_params_`` -- which the\nhalving search selects among the last-iteration candidates -- and confirm the\nchosen model on a held-out test set.\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}