The essentials of module 41 on one page. Every runnable block on this page is checked against its output. The blocks run in order and share their names.
I want to…
Use…
Example
decode &, '
html.unescape
html.unescape("a & b") → 'a & b'
collapse whitespace
re.sub(r"\s+", " ", t).strip()
"a \n b " → 'a b'
split into word tokens
re.findall(r"[a-z0-9']+", t.lower())
"Don't buy!" → ["don't", 'buy']
see the tokens a vectorizer uses
vec.build_analyzer()(text)
CountVectorizer().build_analyzer()("A PC") → ['pc']
count words per document
CountVectorizer()
X = CountVectorizer().fit_transform(texts)
weight words by rarity
TfidfVectorizer()
X = TfidfVectorizer().fit_transform(texts)
add phrases
ngram_range=(1, 2)
features not, worth, not worth
drop rare terms (and rare typos)
min_df=2 or min_df=0.01
int: documents, float: share
drop corpus-specific stop words
max_df=0.5
drops terms in more than 50% of documents
cap the vocabulary
max_features=5000
keeps the 5,000 most frequent terms
keep single letters and digits
token_pattern=r"(?u)\b\w+\b"
keeps m, 2
be robust to typos
analyzer="char_wb", ngram_range=(3, 5)
qualty ≈ quality
count only chosen words
CountVectorizer(vocabulary=words)
a lexicon as a matrix
list the vocabulary
vec.get_feature_names_out()
column names, alphabetical
find a word’s column
vec.vocabulary_["refund"]
an int
vectorize new texts
vec.transform(new_texts)
never fit_transform
classify text
make_pipeline(TfidfVectorizer(), LogisticRegression(C=10))
fit(texts, labels)
fast text baseline
make_pipeline(CountVectorizer(), MultinomialNB())
trains in milliseconds
read the strongest words
pd.Series(clf.coef_[0], index=vec.get_feature_names_out())
.nlargest(10)
find topics
NMF(n_components=10, init="nndsvda") on TF-IDF
components_: words per topic
find topics, probabilistic
LatentDirichletAllocation(10) on counts
rows of transform sum to 1
dense document vectors
make_pipeline(TruncatedSVD(100), Normalizer()) on TF-IDF
LSA
most similar documents
vectors @ query_vector (unit rows)
cosine similarity
out-of-fold probabilities
cross_val_predict(pipe, X, y, method="predict_proba")
label-noise checks
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
np.set_printoptions( precision = 3 , suppress = True )
def clean_text (text: str ) -> str :
"""Decode HTML entities, lowercase and collapse whitespace."""
text = html.unescape(text) # 1. entities first
text = text.lower() # 2. one case
text = re.sub( r " \s + " , " " , text) # 3. spaces, tabs, line breaks -> one space
return text.strip() # 4. no edge spaces
raw = " SUPER fast & easy! \n\n I'd buy again. "
print ( repr (clean_text(raw)))
print (re.sub( r " [ ^ \w\s'] " , " " , clean_text(raw)).split()) # optional: drop punctuation
"super fast & easy! i'd buy again."
['super', 'fast', 'easy', "i'd", 'buy', 'again']
Step
Keeps
Loses
Use for
html.unescape
everything
nothing
always
lower()
words
shouting, proper names
almost always
whitespace collapse
words
layout
always for word models
drop punctuation
words
!!!, :(, ?
when punctuation carries no signal
typo dictionary
corrected words
unknown typos stay
known, frequent typos
stemming / lemmatization
base forms
word forms, sometimes meaning
small corpora; needs NLTK or spaCy
Pattern
"I've got 2 TVs!" gives
Note
str.split()
["I've", 'got', '2', 'TVs!']
punctuation stays attached
[a-z0-9']+ (after lower())
["i've", 'got', '2', 'tvs']
keeps contractions
(?u)\b\w\w+\b (scikit-learn default)
['ve', 'got', 'tvs']
drops 1-character tokens
(?u)\b\w+\b
['i', 've', 'got', '2', 'tvs']
keeps 1-character tokens
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
negations = { "not" , "no" , "never" , "but" }
print ( len ( ENGLISH_STOP_WORDS ), sorted (negations & ENGLISH_STOP_WORDS ))
analyzer = CountVectorizer( stop_words = "english" ).build_analyzer()
print (analyzer( "Not worth the money" ), analyzer( "Worth the money" ))
318 ['but', 'never', 'no', 'not']
['worth', 'money'] ['worth', 'money']
Stop words: remove them for topics and search; keep them for sentiment. A custom list is fine: stop_words=["the", "a", "an", "and", "of"].
Parameter
Default
Effect
lowercase
True
lowercase before tokenizing
token_pattern
r"(?u)\b\w\w+\b"
the regex that defines a token
tokenizer
None
your own function str -> list[str] (set token_pattern=None)
stop_words
None
"english" or a list
ngram_range
(1, 1)
(1, 2) adds bigrams
analyzer
"word"
"char_wb": character n-grams inside words
min_df / max_df
1 / 1.0
drop rare / very common terms (int = documents, float = share)
max_features
None
keep the most frequent terms only
vocabulary
None
a fixed list or dict of terms; no learning
binary
False
True: 1 if present, whatever the count
dtype
int64 / float64
np.float32 halves memory
TfidfVectorizer adds:
Parameter
Default
Effect
use_idf
True
multiply by idf
smooth_idf
True
ln 1 + n 1 + df + 1 \ln\frac{1+n}{1+\operatorname{df}} + 1 ln 1 + df 1 + n + 1 ; False: ln n df + 1 \ln\frac{n}{\operatorname{df}} + 1 ln df n + 1
sublinear_tf
False
tf → 1 + ln ( tf ) 1 + \ln(\operatorname{tf}) 1 + ln ( tf )
norm
"l2"
unit-length rows; None keeps raw weights
Fitted attributes: vocabulary_ (term → column), get_feature_names_out() (columns in order), idf_ (TF-IDF only).
idf ( t ) = ln 1 + n 1 + df ( t ) + 1 , w ^ ( t , d ) = tf ( t , d ) idf ( t ) ∥ tf ( ⋅ , d ) idf ∥ 2 \operatorname{idf}(t) = \ln\frac{1 + n}{1 + \operatorname{df}(t)} + 1,
\qquad
\hat{w}(t, d) = \frac{\operatorname{tf}(t, d)\,\operatorname{idf}(t)}{\lVert \operatorname{tf}(\cdot, d)\,\operatorname{idf} \rVert_2} idf ( t ) = ln 1 + df ( t ) 1 + n + 1 , w ^ ( t , d ) = ∥ tf ( ⋅ , d ) idf ∥ 2 tf ( t , d ) idf ( t )
docs = [ "great battery" , "battery died" , "great value great price" ]
counts = CountVectorizer().fit_transform(docs).toarray() # tf
df = (counts > 0 ).sum( axis = 0 ) # documents per term
idf = np.log(( 1 + len (docs)) / ( 1 + df)) + 1 # smooth idf
by_hand = weights / np.linalg.norm(weights, axis = 1 , keepdims = True ) # L2 rows
print (np.allclose(by_hand, TfidfVectorizer().fit_transform(docs).toarray()))
[1.288 1.693 1.288 1.693 1.693]
Operation
Code
Note
shape, stored values
X.shape, X.nnz
density
X.nnz / (X.shape[0] * X.shape[1])
text: often below 1%; this small corpus: about 4%
one row as dense
X[i].toarray().ravel()
fine for a few rows
column sums (corpus counts)
np.asarray(X.sum(axis=0)).ravel()
or X.sum(axis=0).A1
documents per term
(X > 0).sum(axis=0)
the document frequency
dot with a vector
X @ w
dense 1-D result
row-normalize
sklearn.preprocessing.normalize(X)
stays sparse
stack features
scipy.sparse.hstack([X1, X2]).tocsr()
text + other features
whole matrix as dense
X.toarray()
avoid on a real corpus
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
reviews = pd.read_csv( "data/reviews.csv" , keep_default_na = False )
binary = reviews[reviews[ "sentiment" ] != "neutral" ]
texts = binary[ "text" ].map(clean_text)
TfidfVectorizer( ngram_range = ( 1 , 2 ), min_df = 2 ), # refitted inside every CV fold
LogisticRegression( C = 10 , max_iter = 1000 ), # tune C: the default 1 underfits TF-IDF
print (cross_val_score(pipe, texts, binary[ "sentiment" ], cv = 5 ).mean().round( 3 ))
pipe.fit(texts, binary[ "sentiment" ])
print (pipe.predict([ "Not worth the money." , "Sturdy and built to last." ]))
readable = make_pipeline( # stricter copy for reading weights: no rare n-grams
TfidfVectorizer( ngram_range = ( 1 , 2 ), min_df = 10 ),
LogisticRegression( C = 3 , max_iter = 1000 ),
).fit(texts, binary[ "sentiment" ])
coefs = pd.Series(readable[ - 1 ].coef_[ 0 ], index = readable[ 0 ].get_feature_names_out())
print ( list (coefs.nsmallest( 3 ).index), list (coefs.nlargest( 3 ).index))
['not', 'avoid', 'confusing'] ['premium', 'love', 'love it']
Model
Input
Strengths
Watch out
LogisticRegression
TF-IDF
probabilities, readable weights
tune C; class_weight="balanced" for rare classes
MultinomialNB
counts
very fast, strong on small data
overconfident probabilities; alpha smoothing
ComplementNB
counts
naive Bayes for imbalanced classes
same
LinearSVC
TF-IDF
often the most accurate linear model
no predict_proba
SGDClassifier
TF-IDF
huge corpora, partial_fit for streams
tune alpha
trees, KNN
—
rarely good on sparse text
thousands of splits; distance in 10k dimensions
Read the model: pipe[0] is the vectorizer, pipe[-1] the classifier. For MultinomialNB, use feature_log_prob_[1] - feature_log_prob_[0] as the word score.
Approach
Needs
Handles negation
Domain words
Lexicon (word → score, sum)
a word list
no (unless rules are added, as in VADER)
only listed words
Learned classifier
labeled texts (stars are free labels)
with bigrams (not worth)
learned
Pretrained transformer
a model download
yes
partly
Binary (positive vs negative) is easier than three classes. Ratings are noisy labels: find suspects with out-of-fold probabilities below 0.1 for the given label.
from sklearn.decomposition import NMF
topic_vec = TfidfVectorizer( stop_words = "english" , min_df = 5 , max_df = 0.5 ) # content words
X_topics = topic_vec.fit_transform(reviews[ "text" ].map(clean_text))
nmf = NMF( n_components = 10 , init = "nndsvda" , random_state = 42 , max_iter = 1000 )
W = nmf.fit_transform(X_topics) # documents x topics
terms = topic_vec.get_feature_names_out()
for row in nmf.components_[: 3 ]: # topics x terms
print ( " " .join(terms[np.argsort(row)[:: - 1 ][: 5 ]]))
print (W.shape, np.bincount(W.argmax( axis = 1 )).sum())
money value delivery worth excellent
battery charge holds days fast
sturdy built far long say
NMF
LDA
Class
NMF
LatentDirichletAllocation
Input
TF-IDF
counts (CountVectorizer)
Model
X ≈ W H X \approx WH X ≈ W H , all values ≥ 0
documents mix topics; topics are word distributions
Document output
topic weights
topic probabilities (sum to 1)
Short texts
usually cleaner
often mixed topics
Speed
fast
slower
Choosing n_components: the reconstruction error always falls; read the top words, check stability across seeds (init="random"), choose the smallest number of distinct, nameable topics.
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import Normalizer
lsa_vec = TfidfVectorizer( stop_words = "english" , min_df = 2 )
X_lsa = lsa_vec.fit_transform(reviews[ "text" ].map(clean_text))
lsa = make_pipeline(TruncatedSVD( n_components = 50 , random_state = 42 ), Normalizer())
vectors = lsa.fit_transform(X_lsa) # dense, unit-length rows
query = lsa.transform(lsa_vec.transform([ "too small for me" ]))[ 0 ]
best = np.argsort( - (vectors @ query), kind = "stable" )[: 2 ] # cosine = dot product
print (vectors.shape, reviews[ "text" ].iloc[best].tolist())
(3000, 50) ['Runs small, the size is wrong.', 'Too large even in a small size.']
Representation
Dimensions
Similar words close?
Unknown words
Runs offline here
Bag of words / TF-IDF
one per term (sparse)
no
ignored
yes
Character n-grams
one per letter sequence (sparse)
by spelling
partly handled
yes
LSA (TruncatedSVD)
50–300 (dense)
yes, from your corpus
ignored
yes
word2vec, GloVe, fastText
100–300 per word
yes, pretrained
fastText handles them
needs a download
Transformer sentence embeddings
384–1,024 per text
yes, in context
handled (subwords)
needs a download
Fit vectorizers on training data only. Put them in a Pipeline so cross-validation refits them per fold.
transform, not fit_transform, on new data. A refit vocabulary has different columns.
Pass a Series or a list of strings. A one-column DataFrame iterates over its column name.
ENGLISH_STOP_WORDS contains not, no, never, but, very. Never use it for sentiment.
The default token_pattern drops 1-character tokens and splits i've into ve.
Decode HTML entities before tokenizing, or amp and 39 become words.
Typos survive cleaning. min_df hides only the rare ones (qualty appears 51 times and survives); character n-grams make typos similar to the right word.
Bigrams multiply the vocabulary. Add min_df or max_features.
.toarray() on a whole corpus can need gigabytes. Densify single rows only.
The default C=1 underfits TF-IDF features. Tune C with cross-validation.
Rare n-grams get large, noisy weights (one wore in 4 reviews). Read weights next to their document frequency, or from a copy fitted with a higher min_df and a lower C.
Accuracy hides a weak minority class. Read per-class recall and compare with DummyClassifier.
LDA expects counts, not TF-IDF. NMF topics need stop words removed.
PCA with its full or randomized solver rejects sparse input. Use TruncatedSVD for LSA.
Embed queries with the fitted vectorizer and SVD. A query with no known word gets a zero vector and matches nothing.
LSA and topic models capture what a text is about, not its tone. Combine them with a sentiment model when tone matters.