Spec-Zone.ru › scikit-learn

Note

Go to the end to download the full example code or to run this example in your browser via JupyterLite or Binder.

Sample pipeline for text feature extraction and evaluation

The dataset used in this example is The 20 newsgroups text dataset which will be automatically downloaded, cached and reused for the document classification example.

In this example, we tune the hyperparameters of a particular classifier using a RandomizedSearchCV. For a demo on the performance of some other classifiers, see the Classification of text documents using sparse features notebook.

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

Data loading

We load two categories from the training set. You can adjust the number of categories by adding their names to the list or setting categories=None when calling the dataset loader fetch_20newsgroups to get the 20 of them.

from sklearn.datasets import fetch_20newsgroups

categories = [
    "alt.atheism",
    "talk.religion.misc",
]

data_train = fetch_20newsgroups(
    subset="train",
    categories=categories,
    shuffle=True,
    random_state=42,
    remove=("headers", "footers", "quotes"),
)

data_test = fetch_20newsgroups(
    subset="test",
    categories=categories,
    shuffle=True,
    random_state=42,
    remove=("headers", "footers", "quotes"),
)

print(f"Loading 20 newsgroups dataset for {len(data_train.target_names)} categories:")
print(data_train.target_names)
print(f"{len(data_train.data)} documents")
Loading 20 newsgroups dataset for 2 categories:
['alt.atheism', 'talk.religion.misc']
857 documents

Pipeline with hyperparameter tuning

We define a pipeline combining a text feature vectorizer with a simple classifier yet effective for text classification.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import ComplementNB
from sklearn.pipeline import Pipeline

pipeline = Pipeline(
    [
        ("vect", TfidfVectorizer()),
        ("clf", ComplementNB()),
    ]
)
pipeline
Pipeline(steps=[('vect', TfidfVectorizer()), ('clf', ComplementNB())])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
steps steps: list of tuples

List of (name of step, estimator) tuples that are to be chained in
sequential order. To be compatible with the scikit-learn API, all steps
must define `fit`. All non-last steps must also define `transform`. See
:ref:`Combining Estimators <combining_estimators>` for more details.
[('vect', ...), ('clf', ...)]
transform_input transform_input: list of str, default=None

The names of the :term:`metadata` parameters that should be transformed by the
pipeline before passing it to the step consuming it.

This enables transforming some input arguments to ``fit`` (other than ``X``)
to be transformed by the steps of the pipeline up to the step which requires
them. Requirement is defined via :ref:`metadata routing <metadata_routing>`.
For instance, this can be used to pass a validation set through the pipeline.

You can only set this if metadata routing is enabled, which you
can enable using ``sklearn.set_config(enable_metadata_routing=True)``.

.. versionadded:: 1.6
None
memory memory: str or object with the joblib.Memory interface, default=None

Used to cache the fitted transformers of the pipeline. The last step
will never be cached, even if it is a transformer. By default, no
caching is performed. If a string is given, it is the path to the
caching directory. Enabling caching triggers a clone of the transformers
before fitting. Therefore, the transformer instance given to the
pipeline cannot be inspected directly. Use the attribute ``named_steps``
or ``steps`` to inspect estimators within the pipeline. Caching the
transformers is advantageous when fitting is time consuming. See
:ref:`sphx_glr_auto_examples_neighbors_plot_caching_nearest_neighbors.py`
for an example on how to enable caching.
None
verbose verbose: bool, default=False

If True, the time elapsed while fitting each step will be printed as it
is completed.
False
Parameters
input input: {'filename', 'file', 'content'}, default='content'

- If `'filename'`, the sequence passed as an argument to fit is
expected to be a list of filenames that need reading to fetch
the raw content to analyze.

- If `'file'`, the sequence items must have a 'read' method (file-like
object) that is called to fetch the bytes in memory.

- If `'content'`, the input is expected to be a sequence of items that
can be of type string or byte.
'content'
encoding encoding: str, default='utf-8'

If bytes or files are given to analyze, this encoding is used to
decode.
'utf-8'
decode_error decode_error: {'strict', 'ignore', 'replace'}, default='strict'

Instruction on what to do if a byte sequence is given to analyze that
contains characters not of the given `encoding`. By default, it is
'strict', meaning that a UnicodeDecodeError will be raised. Other
values are 'ignore' and 'replace'.
'strict'
strip_accents strip_accents: {'ascii', 'unicode'} or callable, default=None

Remove accents and perform other character normalization
during the preprocessing step.
'ascii' is a fast method that only works on characters that have
a direct ASCII mapping.
'unicode' is a slightly slower method that works on any characters.
None (default) means no character normalization is performed.

Both 'ascii' and 'unicode' use NFKD normalization from
:func:`unicodedata.normalize`.
None
lowercase lowercase: bool, default=True

Convert all characters to lowercase before tokenizing.
True
preprocessor preprocessor: callable, default=None

Override the preprocessing (string transformation) stage while
preserving the tokenizing and n-grams generation steps.
Only applies if ``analyzer`` is not callable.
None
tokenizer tokenizer: callable, default=None

Override the string tokenization step while preserving the
preprocessing and n-grams generation steps.
Only applies if ``analyzer == 'word'``.
None
analyzer analyzer: {'word', 'char', 'char_wb'} or callable, default='word'

Whether the feature should be made of word or character n-grams.
Option 'char_wb' creates character n-grams only from text inside
word boundaries; n-grams at the edges of words are padded with space.

If a callable is passed it is used to extract the sequence of features
out of the raw, unprocessed input.

.. versionchanged:: 0.21
Since v0.21, if ``input`` is ``'filename'`` or ``'file'``, the data
is first read from the file and then passed to the given callable
analyzer.
'word'
stop_words stop_words: {'english'}, list, default=None

If a string, it is passed to _check_stop_list and the appropriate stop
list is returned. 'english' is currently the only supported string
value.
There are several known issues with 'english' and you should
consider an alternative (see :ref:`stop_words`).

If a list, that list is assumed to contain stop words, all of which
will be removed from the resulting tokens.
Only applies if ``analyzer == 'word'``.

If None, no stop words will be used. In this case, setting `max_df`
to a higher value, such as in the range (0.7, 1.0), can automatically detect
and filter stop words based on intra corpus document frequency of terms.
None
token_pattern token_pattern: str, default=r"(?u)\\b\\w\\w+\\b"

Regular expression denoting what constitutes a "token", only used
if ``analyzer == 'word'``. The default regexp selects tokens of 2
or more alphanumeric characters (punctuation is completely ignored
and always treated as a token separator).

If there is a capturing group in token_pattern then the
captured group content, not the entire match, becomes the token.
At most one capturing group is permitted.
'(?u)\\b\\w\\w+\\b'
ngram_range ngram_range: tuple (min_n, max_n), default=(1, 1)

The lower and upper boundary of the range of n-values for different
n-grams to be extracted. All values of n such that min_n <= n <= max_n
will be used. For example an ``ngram_range`` of ``(1, 1)`` means only
unigrams, ``(1, 2)`` means unigrams and bigrams, and ``(2, 2)`` means
only bigrams.
Only applies if ``analyzer`` is not callable.
(1, ...)
max_df max_df: float or int, default=1.0

When building the vocabulary ignore terms that have a document
frequency strictly higher than the given threshold (corpus-specific
stop words).
If float in range [0.0, 1.0], the parameter represents a proportion of
documents, integer absolute counts.
This parameter is ignored if vocabulary is not None.
1.0
min_df min_df: float or int, default=1

When building the vocabulary ignore terms that have a document
frequency strictly lower than the given threshold. This value is also
called cut-off in the literature.
If float in range of [0.0, 1.0], the parameter represents a proportion
of documents, integer absolute counts.
This parameter is ignored if vocabulary is not None.
1
max_features max_features: int, default=None

If not None, build a vocabulary that only consider the top
`max_features` ordered by term frequency across the corpus.
Otherwise, all features are used.

This parameter is ignored if vocabulary is not None.
None
vocabulary vocabulary: Mapping or iterable, default=None

Either a Mapping (e.g., a dict) where keys are terms and values are
indices in the feature matrix, or an iterable over terms. If not
given, a vocabulary is determined from the input documents.
None
binary binary: bool, default=False

If True, all non-zero term counts are set to 1. This does not mean
outputs will have only 0/1 values, only that the tf term in tf-idf
is binary. (Set `binary` to True, `use_idf` to False and
`norm` to None to get 0/1 outputs).
False
dtype dtype: dtype, default=float64

Type of the matrix returned by fit_transform() or transform().
<class 'numpy.float64'>
norm norm: {'l1', 'l2'} or None, default='l2'

Each output row will have unit norm, either:

- 'l2': Sum of squares of vector elements is 1. The cosine
similarity between two vectors is their dot product when l2 norm has
been applied.
- 'l1': Sum of absolute values of vector elements is 1.
See :func:`~sklearn.preprocessing.normalize`.
- None: No normalization.
'l2'
use_idf use_idf: bool, default=True

Enable inverse-document-frequency reweighting. If False, idf(t) = 1.
True
smooth_idf smooth_idf: bool, default=True

Smooth idf weights by adding one to document frequencies, as if an
extra document was seen containing every term in the collection
exactly once. Prevents zero divisions.
True
sublinear_tf sublinear_tf: bool, default=False

Apply sublinear tf scaling, i.e. replace tf with 1 + log(tf).
False
Parameters
alpha alpha: float or array-like of shape (n_features,), default=1.0

Additive (Laplace/Lidstone) smoothing parameter
(set alpha=0 and force_alpha=True, for no smoothing).
1.0
force_alpha force_alpha: bool, default=True

If False and alpha is less than 1e-10, it will set alpha to
1e-10. If True, alpha will remain unchanged. This may cause
numerical errors if alpha is too close to 0.

.. versionadded:: 1.2
.. versionchanged:: 1.4
The default value of `force_alpha` changed to `True`.
True
fit_prior fit_prior: bool, default=True

Only used in edge case with a single class in the training set.
True
class_prior class_prior: array-like of shape (n_classes,), default=None

Prior probabilities of the classes. Not used.
None
norm norm: bool, default=False

Whether or not a second normalization of the weights is performed. The
default behavior mirrors the implementations found in Mahout and Weka,
which do not follow the full algorithm described in Table 9 of the
paper.
False


We define a grid of hyperparameters to be explored by the RandomizedSearchCV. Using a GridSearchCV instead would explore all the possible combinations on the grid, which can be costly to compute, whereas the parameter n_iter of the RandomizedSearchCV controls the number of different random combination that are evaluated. Notice that setting n_iter larger than the number of possible combinations in a grid would lead to repeating already-explored combinations. We search for the best parameter combination for both the feature extraction (vect__) and the classifier (clf__).

import numpy as np

parameter_grid = {
    "vect__max_df": (0.2, 0.4, 0.6, 0.8, 1.0),
    "vect__min_df": (1, 3, 5, 10),
    "vect__ngram_range": ((1, 1), (1, 2)),  # unigrams or bigrams
    "vect__norm": ("l1", "l2"),
    "clf__alpha": np.logspace(-6, 6, 13),
}

In this case n_iter=40 is not an exhaustive search of the hyperparameters’ grid. In practice it would be interesting to increase the parameter n_iter to get a more informative analysis. As a consequence, the computional time increases. We can reduce it by taking advantage of the parallelisation over the parameter combinations evaluation by increasing the number of CPUs used via the parameter n_jobs.

from pprint import pprint

from sklearn.model_selection import RandomizedSearchCV

random_search = RandomizedSearchCV(
    estimator=pipeline,
    param_distributions=parameter_grid,
    n_iter=40,
    random_state=0,
    n_jobs=2,
    verbose=1,
)

print("Performing grid search...")
print("Hyperparameters to be evaluated:")
pprint(parameter_grid)
Performing grid search...
Hyperparameters to be evaluated:
{'clf__alpha': array([1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01,
       1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06]),
 'vect__max_df': (0.2, 0.4, 0.6, 0.8, 1.0),
 'vect__min_df': (1, 3, 5, 10),
 'vect__ngram_range': ((1, 1), (1, 2)),
 'vect__norm': ('l1', 'l2')}
from time import time

t0 = time()
random_search.fit(data_train.data, data_train.target)
print(f"Done in {time() - t0:.3f}s")
Fitting 5 folds for each of 40 candidates, totalling 200 fits
Done in 33.493s
print("Best parameters combination found:")
best_parameters = random_search.best_estimator_.get_params()
for param_name in sorted(parameter_grid.keys()):
    print(f"{param_name}: {best_parameters[param_name]}")
Best parameters combination found:
clf__alpha: 0.01
vect__max_df: 0.2
vect__min_df: 1
vect__ngram_range: (1, 1)
vect__norm: l1
test_accuracy = random_search.score(data_test.data, data_test.target)
print(
    "Accuracy of the best parameters using the inner CV of "
    f"the random search: {random_search.best_score_:.3f}"
)
print(f"Accuracy on test set: {test_accuracy:.3f}")
Accuracy of the best parameters using the inner CV of the random search: 0.816
Accuracy on test set: 0.709

The prefixes vect and clf are required to avoid possible ambiguities in the pipeline, but are not necessary for visualizing the results. Because of this, we define a function that will rename the tuned hyperparameters and improve the readability.

import pandas as pd


def shorten_param(param_name):
    """Remove components' prefixes in param_name."""
    if "__" in param_name:
        return param_name.rsplit("__", 1)[1]
    return param_name


cv_results = pd.DataFrame(random_search.cv_results_)
cv_results = cv_results.rename(shorten_param, axis=1)

We can use a plotly.express.scatter to visualize the trade-off between scoring time and mean test score (i.e. “CV score”). Passing the cursor over a given point displays the corresponding parameters. Error bars correspond to one standard deviation as computed in the different folds of the cross-validation.

import plotly.express as px

param_names = [shorten_param(name) for name in parameter_grid.keys()]
labels = {
    "mean_score_time": "CV Score time (s)",
    "mean_test_score": "CV score (accuracy)",
}
fig = px.scatter(
    cv_results,
    x="mean_score_time",
    y="mean_test_score",
    error_x="std_score_time",
    error_y="std_test_score",
    hover_data=param_names,
    labels=labels,
)
fig.update_layout(
    title={
        "text": "trade-off between scoring time and mean test score",
        "y": 0.95,
        "x": 0.5,
        "xanchor": "center",
        "yanchor": "top",
    }
)
fig


Notice that the cluster of models in the upper-left corner of the plot have the best trade-off between accuracy and scoring time. In this case, using bigrams increases the required scoring time without improving considerably the accuracy of the pipeline.

Note

For more information on how to customize an automated tuning to maximize score and minimize scoring time, see the example notebook Custom refit strategy of a grid search with cross-validation.

We can also use a plotly.express.parallel_coordinates to further visualize the mean test score as a function of the tuned hyperparameters. This helps finding interactions between more than two hyperparameters and provide intuition on their relevance for improving the performance of a pipeline.

We apply a math.log10 transformation on the alpha axis to spread the active range and improve the readability of the plot. A value \(x\) on said axis is to be understood as \(10^x\).

import math

column_results = param_names + ["mean_test_score", "mean_score_time"]

transform_funcs = dict.fromkeys(column_results, lambda x: x)
# Using a logarithmic scale for alpha
transform_funcs["alpha"] = math.log10
# L1 norms are mapped to index 1, and L2 norms to index 2
transform_funcs["norm"] = lambda x: 2 if x == "l2" else 1
# Unigrams are mapped to index 1 and bigrams to index 2
transform_funcs["ngram_range"] = lambda x: x[1]

fig = px.parallel_coordinates(
    cv_results[column_results].apply(transform_funcs),
    color="mean_test_score",
    color_continuous_scale=px.colors.sequential.Viridis_r,
    labels=labels,
)
fig.update_layout(
    title={
        "text": "Parallel coordinates plot of text classifier pipeline",
        "y": 0.99,
        "x": 0.5,
        "xanchor": "center",
        "yanchor": "top",
    }
)
fig


The parallel coordinates plot displays the values of the hyperparameters on different columns while the performance metric is color coded. It is possible to select a range of results by clicking and holding on any axis of the parallel coordinate plot. You can then slide (move) the range selection and cross two selections to see the intersections. You can undo a selection by clicking once again on the same axis.

In particular for this hyperparameter search, it is interesting to notice that the top performing models do not seem to depend on the regularization norm, but they do depend on a trade-off between max_df, min_df and the regularization strength alpha. The reason is that including noisy features (i.e. max_df close to \(1.0\) or min_df close to \(0\)) tend to overfit and therefore require a stronger regularization to compensate. Having less features require less regularization and less scoring time.

The best accuracy scores are obtained when alpha is between \(10^{-6}\) and \(10^0\), regardless of the hyperparameter norm.

Total running time of the script: (0 minutes 36.426 seconds)

Launch binder
Launch JupyterLite

Download Jupyter notebook: plot_grid_search_text_feature_extraction.ipynb

Download Python source code: plot_grid_search_text_feature_extraction.py

Download zipped: plot_grid_search_text_feature_extraction.zip

Related examples

Classification of text documents using sparse features

Comparing Random Forests and Histogram Gradient Boosting models

Analysis of the convergence of penalized logistic regression models

Column Transformer with Mixed Types

© 2007–2026 The scikit-learn developers
Licensed under the 3-clause BSD License.
https://scikit-learn.org/1.9/auto_examples/model_selection/plot_grid_search_text_feature_extraction.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API