{ "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
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`.