{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Sample pipeline for text feature extraction and evaluation\n\nThe dataset used in this example is `20newsgroups_dataset` which will be\nautomatically downloaded, cached and reused for the document classification\nexample.\n\nIn this example, we tune the hyperparameters of a particular classifier using a\n:class:`~sklearn.model_selection.RandomizedSearchCV`. For a demo on the\nperformance of some other classifiers, see the\n`sphx_glr_auto_examples_text_plot_document_classification_20newsgroups.py`\nnotebook.\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": [ "## Data loading\nWe load two categories from the training set. You can adjust the number of\ncategories by adding their names to the list or setting `categories=None` when\ncalling the dataset loader :func:`~sklearn.datasets.fetch_20newsgroups` to get\nthe 20 of them.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.datasets import fetch_20newsgroups\n\ncategories = [\n \"alt.atheism\",\n \"talk.religion.misc\",\n]\n\ndata_train = fetch_20newsgroups(\n subset=\"train\",\n categories=categories,\n shuffle=True,\n random_state=42,\n remove=(\"headers\", \"footers\", \"quotes\"),\n)\n\ndata_test = fetch_20newsgroups(\n subset=\"test\",\n categories=categories,\n shuffle=True,\n random_state=42,\n remove=(\"headers\", \"footers\", \"quotes\"),\n)\n\nprint(f\"Loading 20 newsgroups dataset for {len(data_train.target_names)} categories:\")\nprint(data_train.target_names)\nprint(f\"{len(data_train.data)} documents\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pipeline with hyperparameter tuning\n\nWe define a pipeline combining a text feature vectorizer with a simple\nclassifier yet effective for text classification.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import ComplementNB\nfrom sklearn.pipeline import Pipeline\n\npipeline = Pipeline(\n [\n (\"vect\", TfidfVectorizer()),\n (\"clf\", ComplementNB()),\n ]\n)\npipeline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We define a grid of hyperparameters to be explored by the\n:class:`~sklearn.model_selection.RandomizedSearchCV`. Using a\n:class:`~sklearn.model_selection.GridSearchCV` instead would explore all the\npossible combinations on the grid, which can be costly to compute, whereas the\nparameter `n_iter` of the :class:`~sklearn.model_selection.RandomizedSearchCV`\ncontrols the number of different random combination that are evaluated. Notice\nthat setting `n_iter` larger than the number of possible combinations in a\ngrid would lead to repeating already-explored combinations. We search for the\nbest parameter combination for both the feature extraction (`vect__`) and the\nclassifier (`clf__`).\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n\nparameter_grid = {\n \"vect__max_df\": (0.2, 0.4, 0.6, 0.8, 1.0),\n \"vect__min_df\": (1, 3, 5, 10),\n \"vect__ngram_range\": ((1, 1), (1, 2)), # unigrams or bigrams\n \"vect__norm\": (\"l1\", \"l2\"),\n \"clf__alpha\": np.logspace(-6, 6, 13),\n}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case `n_iter=40` is not an exhaustive search of the hyperparameters'\ngrid. In practice it would be interesting to increase the parameter `n_iter`\nto get a more informative analysis. As a consequence, the computional time\nincreases. We can reduce it by taking advantage of the parallelisation over\nthe parameter combinations evaluation by increasing the number of CPUs used\nvia the parameter `n_jobs`.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from pprint import pprint\n\nfrom sklearn.model_selection import RandomizedSearchCV\n\nrandom_search = RandomizedSearchCV(\n estimator=pipeline,\n param_distributions=parameter_grid,\n n_iter=40,\n random_state=0,\n n_jobs=2,\n verbose=1,\n)\n\nprint(\"Performing grid search...\")\nprint(\"Hyperparameters to be evaluated:\")\npprint(parameter_grid)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from time import time\n\nt0 = time()\nrandom_search.fit(data_train.data, data_train.target)\nprint(f\"Done in {time() - t0:.3f}s\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"Best parameters combination found:\")\nbest_parameters = random_search.best_estimator_.get_params()\nfor param_name in sorted(parameter_grid.keys()):\n print(f\"{param_name}: {best_parameters[param_name]}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "test_accuracy = random_search.score(data_test.data, data_test.target)\nprint(\n \"Accuracy of the best parameters using the inner CV of \"\n f\"the random search: {random_search.best_score_:.3f}\"\n)\nprint(f\"Accuracy on test set: {test_accuracy:.3f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The prefixes `vect` and `clf` are required to avoid possible ambiguities in\nthe pipeline, but are not necessary for visualizing the results. Because of\nthis, we define a function that will rename the tuned hyperparameters and\nimprove the readability.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import pandas as pd\n\n\ndef shorten_param(param_name):\n \"\"\"Remove components' prefixes in param_name.\"\"\"\n if \"__\" in param_name:\n return param_name.rsplit(\"__\", 1)[1]\n return param_name\n\n\ncv_results = pd.DataFrame(random_search.cv_results_)\ncv_results = cv_results.rename(shorten_param, axis=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use a [plotly.express.scatter](https://plotly.com/python-api-reference/generated/plotly.express.scatter.html)\nto visualize the trade-off between scoring time and mean test score (i.e. \"CV\nscore\"). Passing the cursor over a given point displays the corresponding\nparameters. Error bars correspond to one standard deviation as computed in the\ndifferent folds of the cross-validation.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import plotly.express as px\n\nparam_names = [shorten_param(name) for name in parameter_grid.keys()]\nlabels = {\n \"mean_score_time\": \"CV Score time (s)\",\n \"mean_test_score\": \"CV score (accuracy)\",\n}\nfig = px.scatter(\n cv_results,\n x=\"mean_score_time\",\n y=\"mean_test_score\",\n error_x=\"std_score_time\",\n error_y=\"std_test_score\",\n hover_data=param_names,\n labels=labels,\n)\nfig.update_layout(\n title={\n \"text\": \"trade-off between scoring time and mean test score\",\n \"y\": 0.95,\n \"x\": 0.5,\n \"xanchor\": \"center\",\n \"yanchor\": \"top\",\n }\n)\nfig" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the cluster of models in the upper-left corner of the plot have\nthe best trade-off between accuracy and scoring time. In this case, using\nbigrams increases the required scoring time without improving considerably the\naccuracy of the pipeline.\n\n

Note

For more information on how to customize an automated tuning to\n maximize score and minimize scoring time, see the example notebook\n `sphx_glr_auto_examples_model_selection_plot_grid_search_digits.py`.

\n\nWe can also use a [plotly.express.parallel_coordinates](https://plotly.com/python-api-reference/generated/plotly.express.parallel_coordinates.html)\nto further visualize the mean test score as a function of the tuned\nhyperparameters. This helps finding interactions between more than two\nhyperparameters and provide intuition on their relevance for improving the\nperformance of a pipeline.\n\nWe apply a `math.log10` transformation on the `alpha` axis to spread the\nactive range and improve the readability of the plot. A value $x$ on\nsaid axis is to be understood as $10^x$.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import math\n\ncolumn_results = param_names + [\"mean_test_score\", \"mean_score_time\"]\n\ntransform_funcs = dict.fromkeys(column_results, lambda x: x)\n# Using a logarithmic scale for alpha\ntransform_funcs[\"alpha\"] = math.log10\n# L1 norms are mapped to index 1, and L2 norms to index 2\ntransform_funcs[\"norm\"] = lambda x: 2 if x == \"l2\" else 1\n# Unigrams are mapped to index 1 and bigrams to index 2\ntransform_funcs[\"ngram_range\"] = lambda x: x[1]\n\nfig = px.parallel_coordinates(\n cv_results[column_results].apply(transform_funcs),\n color=\"mean_test_score\",\n color_continuous_scale=px.colors.sequential.Viridis_r,\n labels=labels,\n)\nfig.update_layout(\n title={\n \"text\": \"Parallel coordinates plot of text classifier pipeline\",\n \"y\": 0.99,\n \"x\": 0.5,\n \"xanchor\": \"center\",\n \"yanchor\": \"top\",\n }\n)\nfig" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The parallel coordinates plot displays the values of the hyperparameters on\ndifferent columns while the performance metric is color coded. It is possible\nto select a range of results by clicking and holding on any axis of the\nparallel coordinate plot. You can then slide (move) the range selection and\ncross two selections to see the intersections. You can undo a selection by\nclicking once again on the same axis.\n\nIn particular for this hyperparameter search, it is interesting to notice that\nthe top performing models do not seem to depend on the regularization `norm`,\nbut they do depend on a trade-off between `max_df`, `min_df` and the\nregularization strength `alpha`. The reason is that including noisy features\n(i.e. `max_df` close to $1.0$ or `min_df` close to $0$) tend to\noverfit and therefore require a stronger regularization to compensate. Having\nless features require less regularization and less scoring time.\n\nThe best accuracy scores are obtained when `alpha` is between $10^{-6}$\nand $10^0$, regardless of the hyperparameter `norm`.\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.9.21" } }, "nbformat": 4, "nbformat_minor": 0 }