Skip to content

NLP with scikit-learn

Classic NLP (natural language processing) turns text into numeric vectors and then uses ordinary models on them. This page covers cleaning, the scikit-learn vectorizers and their settings, n-grams, classification pipelines, topic models, LSA (latent semantic analysis) and similarity search. The same tools work for log lines, support tickets, product titles and search boxes. The examples use data/reviews.csv. The blocks share one session:

import html
import re
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.pipeline import make_pipeline
pd.set_option("display.width", 100)
np.set_printoptions(precision=3, suppress=True)
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False) # "" stays a string
print(reviews.shape, reviews["sentiment"].value_counts().to_dict())
Output
(3000, 9) {'positive': 2066, 'negative': 596, 'neutral': 338}
I want to… Use… Notes
decode &, ' html.unescape(text) before tokenizing
collapse whitespace re.sub(r"\s+", " ", text).strip()
split into word tokens re.findall(r"[a-z0-9']+", text.lower()) keeps don't
see the tokens a vectorizer makes vec.build_analyzer()(text) debug settings fast
word counts per document CountVectorizer() sparse matrix
counts weighted by rarity TfidfVectorizer() unit-length rows by default
1/0 presence instead of counts CountVectorizer(binary=True)
add two-word phrases ngram_range=(1, 2) not worth becomes a feature
drop rare terms and typos min_df=2 (documents) or min_df=0.01 (share)
drop terms in most documents max_df=0.5 corpus-specific stop words
cap the vocabulary max_features=20_000 most frequent terms
remove stop words stop_words="english" or a list not for sentiment
keep 1-letter tokens and digits token_pattern=r"(?u)\b\w+\b" default drops them
be robust to typos analyzer="char_wb", ngram_range=(3, 5)
use my own tokenizer tokenizer=f, token_pattern=None
dampen repeated words TfidfVectorizer(sublinear_tf=True) tf → 1 + ln(tf)
vectorize new text vec.transform(new_texts) never fit_transform
list the columns vec.get_feature_names_out()
classify text make_pipeline(TfidfVectorizer(), LogisticRegression(C=10)) input: a list of strings
a very fast baseline make_pipeline(CountVectorizer(), MultinomialNB())
tune vectorizer and model together GridSearchCV(pipe, {"tfidfvectorizer__min_df": [1, 2, 5]}) step__param
text + numeric columns ColumnTransformer([("txt", TfidfVectorizer(), "text"), ...]) the column name as a string
the most telling words pd.Series(clf.coef_[0], index=names).nlargest(10)
topics, non-negative factors NMF(n_components=10, init="nndsvda") on TF-IDF
topics, probabilistic LatentDirichletAllocation(n_components=10) on counts rows sum to 1
dense document vectors (LSA) make_pipeline(TruncatedSVD(100), Normalizer()) on TF-IDF
similar documents NearestNeighbors(metric="cosine").kneighbors(q) distance = 1 − cosine
cosine similarity matrix cosine_similarity(A, B) sklearn.metrics.pairwise
stack text and other features scipy.sparse.hstack([X_text, X_num]).tocsr()
def clean_text(text: str) -> str:
"""Decode HTML entities, lowercase and collapse whitespace."""
text = html.unescape(text) # & -> &
text = text.lower()
return re.sub(r"\s+", " ", text).strip()
raw = " GREAT value & FAST!!\n\nI've ordered 2 more :) "
print(repr(clean_text(raw)))
print(re.findall(r"[a-z0-9']+", clean_text(raw))) # keeps contractions and digits
print(CountVectorizer().build_analyzer()(raw)) # the default pattern
print(CountVectorizer(token_pattern=r"(?u)\b\w+\b").build_analyzer()(raw))
Output
"great value & fast!! i've ordered 2 more :)"
['great', 'value', 'fast', "i've", 'ordered', '2', 'more']
['great', 'value', 'amp', 'fast', '39', 've', 'ordered', 'more']
['great', 'value', 'amp', 'fast', 'i', '39', 've', 'ordered', '2', 'more']
Step Keeps Loses Use when
html.unescape everything nothing always, first
lower() words shouting, names almost always (vectorizers do it by default)
collapse whitespace words layout always
remove punctuation re.sub(r"[^\w\s']", " ", t) words !!!, :(, ? punctuation carries no signal
replace numbers re.sub(r"\d+", "0", t) the fact “a number” the value prices, ids, dates
stop-word removal content words not, no, very topics, search; never sentiment
stemming / lemmatization base forms word forms small corpora; NLTK or spaCy
Token pattern "I've got 2 TVs!" gives
str.split() ["I've", 'got', '2', 'TVs!']
[a-z0-9']+ on lowercased text ["i've", 'got', '2', 'tvs']
(?u)\b\w\w+\b (scikit-learn default) ['ve', 'got', 'tvs']
(?u)\b\w+\b ['i', 've', 'got', '2', 'tvs']
docs = ["Not worth the money", "Worth every penny", "Not great, not terrible"]
count = CountVectorizer(ngram_range=(1, 2), min_df=1)
X = count.fit_transform(docs) # sparse documents x terms
print(X.shape, X.nnz, list(count.get_feature_names_out()[:6]))
print(pd.DataFrame(X.toarray(), columns=count.get_feature_names_out()).iloc[:, :6])
tfidf = TfidfVectorizer().fit(docs)
idf = pd.Series(tfidf.idf_, index=tfidf.get_feature_names_out())
print(idf[["not", "worth", "money"]].round(2).to_dict()) # rarer term, higher idf
print(tfidf.transform(["not worth it"]).toarray().round(2)) # unknown "it" ignored
Output
(3, 16) 18 ['every', 'every penny', 'great', 'great not', 'money', 'not']
every every penny great great not money not
0 0 0 0 0 1 1
1 1 1 0 0 0 0
2 0 0 1 1 0 2
{'not': 1.29, 'worth': 1.29, 'money': 1.69}
[[0. 0. 0. 0.71 0. 0. 0. 0.71]]
Parameter Default Effect
lowercase True lowercase before tokenizing
token_pattern r"(?u)\b\w\w+\b" regex for one token: 2+ word characters
tokenizer None a function str -> list[str]; set token_pattern=None
preprocessor None a function applied to each raw text first
stop_words None "english" (318 words) or your own list
ngram_range (1, 1) (1, 2) adds bigrams, (2, 2) bigrams only
analyzer "word" "char" or "char_wb": character n-grams
min_df 1 int = minimum document count, float = minimum share
max_df 1.0 drop terms in more than this share of documents
max_features None keep the N most frequent terms
vocabulary None a fixed term list; nothing is learned
binary False 1 if a term is present
dtype int64 / float64 np.float32 halves the memory
TfidfVectorizer only Default Effect
use_idf True multiply term counts by idf
smooth_idf True idf =ln⁡1+n1+df+1= \ln\frac{1 + n}{1 + \text{df}} + 1
sublinear_tf False tf → 1+ln⁡(tf)1 + \ln(\text{tf})
norm "l2" unit-length rows, so a dot product is the cosine
Fitted attribute Gives
vocabulary_ term → column index
get_feature_names_out() column names in order
idf_ the idf weight per column (TF-IDF only)
for name, vec in [
("words 1-2", CountVectorizer(ngram_range=(1, 2))),
("words 1-2, min_df=5", CountVectorizer(ngram_range=(1, 2), min_df=5)),
("char_wb 3-5", CountVectorizer(analyzer="char_wb", ngram_range=(3, 5), min_df=5)),
]:
print(f"{name:<20}", vec.fit_transform(reviews["text"]).shape[1], "columns")
char3 = CountVectorizer(analyzer="char_wb", ngram_range=(3, 3)).build_analyzer()
print(char3("qualty")) # a typo still shares qua, ual with "quality"
Output
words 1-2 3553 columns
words 1-2, min_df=5 1418 columns
char_wb 3-5 3870 columns
[' qu', 'qua', 'ual', 'alt', 'lty', 'ty ']
Setting Captures Cost
unigrams (1, 1) single words smallest vocabulary
(1, 2) negation and phrases: not worth, love it 3–5× the columns: add min_df
(1, 3) longer phrases rarely worth it on short texts
analyzer="char_wb", (3, 5) spelling, typos, word parts many columns; slower
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
binary = reviews[reviews["sentiment"] != "neutral"]
X_train, X_test, y_train, y_test = train_test_split(
binary["text"], binary["sentiment"], test_size=0.25,
stratify=binary["sentiment"], random_state=42,
)
clf = make_pipeline(
TfidfVectorizer(preprocessor=clean_text, ngram_range=(1, 2), min_df=2),
LogisticRegression(C=10, max_iter=1000), # the default C=1 underfits TF-IDF
).fit(X_train, y_train) # the vectorizer learns from the training texts only
print(classification_report(y_test, clf.predict(X_test), digits=3))
print(clf.predict(["Not worth the money.", "Sturdy and built to last."]))
Output
precision recall f1-score support
negative 0.809 0.826 0.817 149
positive 0.949 0.944 0.947 517
accuracy 0.917 666
macro avg 0.879 0.885 0.882 666
weighted avg 0.918 0.917 0.918 666
['negative' 'positive']

Tune the vectorizer and the model together. Step names are the lowercased class names:

from sklearn.model_selection import GridSearchCV
grid = GridSearchCV(clf, {
"tfidfvectorizer__ngram_range": [(1, 1), (1, 2)],
"tfidfvectorizer__min_df": [1, 2, 5],
"logisticregression__C": [1, 10, 100],
}, cv=5, scoring="f1_macro", n_jobs=-1).fit(X_train, y_train)
print(grid.best_params_, grid.best_score_)
Model Input Strengths Watch out
LogisticRegression TF-IDF probabilities, readable weights tune C; class_weight="balanced"
MultinomialNB counts very fast; good on small data overconfident probabilities; tune alpha
ComplementNB counts naive Bayes for imbalanced classes
LinearSVC TF-IDF often the most accurate linear model no predict_proba
SGDClassifier TF-IDF huge corpora, partial_fit tune alpha
trees, k-NN — rarely good on sparse text

Read the weights of a linear model:

names = clf[0].get_feature_names_out()
weights = pd.Series(clf[-1].coef_[0], index=names) # > 0 pushes to classes_[1]
print(clf[-1].classes_, weights.nlargest(4).round(2).to_dict())
print(weights.nsmallest(4).round(2).to_dict())
Output
['negative' 'positive'] {'premium': 4.2, 'one wore': 3.45, 'excellent': 3.23, 'quickly': 3.16}
{'avoid': -4.62, 'not': -3.92, 'disappointing': -3.76, 'confusing': -3.56}

one wore is a rare bigram with a large weight. Rare n-grams get noisy weights; read weights from a model with a higher min_df.

from sklearn.decomposition import NMF, LatentDirichletAllocation
texts = reviews["text"].map(clean_text)
counts_vec = CountVectorizer(stop_words="english", min_df=5, max_df=0.5)
counts = counts_vec.fit_transform(texts)
lda = LatentDirichletAllocation(n_components=6, learning_method="batch",
random_state=42).fit(counts)
tfidf_vec = TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5)
nmf = NMF(n_components=6, init="nndsvda", random_state=42, max_iter=1000)
W = nmf.fit_transform(tfidf_vec.fit_transform(texts)) # documents x topics
def top_words(components, terms, n=5):
return [" ".join(terms[np.argsort(row)[::-1][:n]]) for row in components]
print(*top_words(lda.components_[:3], counts_vec.get_feature_names_out()), sep="\n")
print(*top_words(nmf.components_[:3], tfidf_vec.get_feature_names_out()), sep="\n")
print(lda.transform(counts[:1]).round(2), lda.transform(counts[:1]).sum().round(2))
Output
customer great service arrived package
price quality point purchase happy
size sturdy built recommend friends
months lasted delivery money value
battery charge holds days fast
sturdy built recommend friends definitely
[[0.02 0.35 0.02 0.55 0.02 0.02]] 1.0
NMF LatentDirichletAllocation
Input TF-IDF raw counts
Model X≈WHX \approx WH, all values ≥ 0 documents mix topics; topics are word distributions
transform output topic weights topic probabilities (rows sum to 1)
Short texts usually cleaner topics often mixed topics
Speed fast slower
Repeatable random_state=42 random_state=42

Choose n_components by reading the top words: the smallest number of distinct topics you can name. Remove stop words and set max_df first, or every topic starts with the.

from sklearn.decomposition import TruncatedSVD
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import Normalizer
lsa = make_pipeline(
TfidfVectorizer(preprocessor=clean_text, stop_words="english", min_df=2),
TruncatedSVD(n_components=50, random_state=42), # no centering: stays sparse
Normalizer(), # unit rows: dot product = cosine
)
vectors = lsa.fit_transform(reviews["text"])
nn = NearestNeighbors(n_neighbors=3, metric="cosine").fit(vectors)
dist, idx = nn.kneighbors(lsa.transform(["the battery dies too fast"]))
print(vectors.shape, (1 - dist).round(3)) # cosine similarity = 1 - distance
for text in reviews["text"].iloc[idx[0]]:
print(text.strip()[:60])
Output
(3000, 50) [[0.996 0.835 0.822]]
The battery drains fast.
Bought this for my dad. The battery charges fast and holds t
The battery charges fast &amp; holds teh charge.
Representation Dimensions Similar words close? Needs a download
bag of words / TF-IDF one per term, sparse no no
character n-grams one per letter sequence by spelling no
LSA (TruncatedSVD) 50–300, dense yes, learned from your corpus no
word2vec, GloVe, fastText 100–300 per word yes yes
transformer sentence embeddings 384–1,024 per text yes, in context yes
Similarity search Code
on sparse TF-IDF NearestNeighbors(metric="cosine").fit(X_tfidf) (brute force)
on unit vectors scores = vectors @ query; np.argsort(-scores)[:k]
all pairs cosine_similarity(X) (n × n: small n only)
duplicate detection pairs with cosine above 0.9
Trap Symptom Fix
fitting the vectorizer on all data optimistic CV scores put it in a Pipeline
fit_transform on new text different columns; shape mismatch transform
passing a one-column DataFrame a vocabulary of one term: the column name pass a Series: df["text"]
stop_words="english" for sentiment not worth becomes worth keep stop words; use bigrams
default token_pattern i've → ve; 2 and x vanish token_pattern=r"(?u)\b\w+\b" or your own
HTML entities left in tokens amp, 39 html.unescape first
keep_default_na left on a review text "NA" or "" becomes NaN; the vectorizer fails read_csv(..., keep_default_na=False)
bigrams without min_df a huge, noisy vocabulary min_df=2 or more, max_features
.toarray() on a corpus memory error stay sparse; densify single rows
the default C=1 on TF-IDF underfitting tune C (10 is a common start)
reading weights of rare n-grams big, meaningless weights require a higher min_df before reading weights
accuracy on imbalanced classes a weak minority class is hidden per-class recall; compare with DummyClassifier
LDA on TF-IDF poor topics LDA takes counts
PCA(svd_solver="randomized") or "full" on sparse TF-IDF TypeError; the default solver runs but centers the data (not LSA) TruncatedSVD: no centering, the standard for LSA
a query of unknown words a zero vector; no or random neighbors check X_query.nnz > 0
Euclidean k-NN on raw TF-IDF long documents look far away metric="cosine" or unit rows