nltk.classify.scikitlearn module

scikit-learn (https://scikit-learn.org) is a machine learning library for Python. It supports many classification algorithms, including SVMs, Naive Bayes, logistic regression (MaxEnt) and decision trees.

This package implements a wrapper around scikit-learn classifiers. To use this wrapper, construct a scikit-learn estimator object, then use that to construct a SklearnClassifier. E.g., to wrap a linear SVM with default settings:

>>> from sklearn.svm import LinearSVC
>>> from nltk.classify.scikitlearn import SklearnClassifier
>>> classif = SklearnClassifier(LinearSVC())

A scikit-learn classifier may include preprocessing steps when it’s wrapped in a Pipeline object. The following constructs and wraps a Naive Bayes text classifier with tf-idf weighting and chi-square feature selection to get the best 1000 features:

>>> from sklearn.feature_extraction.text import TfidfTransformer
>>> from sklearn.feature_selection import SelectKBest, chi2
>>> from sklearn.naive_bayes import MultinomialNB
>>> from sklearn.pipeline import Pipeline
>>> pipeline = Pipeline([('tfidf', TfidfTransformer()),
...                      ('chi2', SelectKBest(chi2, k=1000)),
...                      ('nb', MultinomialNB())])
>>> classif = SklearnClassifier(pipeline)
class nltk.classify.scikitlearn.SklearnClassifier[source]

Bases: ClassifierI

Wrapper for scikit-learn classifiers.

__init__(estimator, dtype=<class 'float'>, sparse=True)[source]
Parameters:
  • estimator – scikit-learn classifier object.

  • dtype – data type used when building feature array. scikit-learn estimators work exclusively on numeric data. The default value should be fine for almost all situations.

  • sparse (boolean.) – Whether to use sparse matrices internally. The estimator must support these; not all scikit-learn classifiers do (see their respective documentation and look for “sparse matrix”). The default value is True, since most NLP problems involve sparse feature sets. Setting this to False may take a great amount of memory.

classify_many(featuresets)[source]

Classify a batch of samples.

Parameters:

featuresets – An iterable over featuresets, each a dict mapping strings to either numbers, booleans or strings.

Returns:

The predicted class label for each input sample.

Return type:

list

labels()[source]

The class labels used by this classifier.

Return type:

list

prob_classify_many(featuresets)[source]

Compute per-class probabilities for a batch of samples.

Parameters:

featuresets – An iterable over featuresets, each a dict mapping strings to either numbers, booleans or strings.

Return type:

list of ProbDistI

train(labeled_featuresets)[source]

Train (fit) the scikit-learn estimator.

Parameters:

labeled_featuresets – A list of (featureset, label) where each featureset is a dict mapping strings to either numbers, booleans or strings.