Step 3 of 5

Classical ML & NLP - What LLMs Don't Replace

Regex, TF-IDF, BM25, embeddings, and small models that solve many text problems for $0 - plus the neural-network basics underneath it all.

17 min read

It's tempting to send every text problem to an LLM. Often that's the wrong call. A regular expression runs in microseconds, costs nothing, never hallucinates, and gives the same answer every time. A TF-IDF classifier trains in seconds on a laptop. A 200-MB embedding model does semantic search faster and cheaper than any chat model.

This guide covers the classical toolkit worth trying first, the neural-network fundamentals every model is built on, and a cheat sheet of the library functions you'll use most.

22 NLP techniques before reaching for an LLM#

Cleaning and splitting text#

1

Regular expressions

Emails, order ids, dates, phone numbers, log patterns. Deterministic, instant, and testable. Often the best solution outright.

2

Normalization

Lowercasing, Unicode normalization (NFKC), stripping accents and extra whitespace so 'Café', 'cafe' and 'CAFE ' compare equal.

3

Tokenization

Splitting text into words or subwords. Language-aware tokenizers handle contractions, punctuation, and scripts without spaces.

4

Stop-word removal

Drop very common words ('the', 'is') for keyword methods. Keep them for anything that needs meaning or negation.

5

Stemming

Chop suffixes by rule: 'running' → 'run', 'studies' → 'studi'. Fast and crude - fine for search recall.

6

Lemmatization

Map words to their dictionary form using vocabulary and part of speech: 'better' → 'good', 'was' → 'be'. Slower, cleaner than stemming.

Representing text as numbers#

1

Bag of words

Count each vocabulary word in a document. Ignores order, but a surprisingly strong baseline for classification.

2

N-grams

Count word pairs and triples too ('not good', 'New York') to recover some local order.

3

TF-IDF

Weight words by how often they appear in a document, discounted by how common they are across all documents. Rare, specific words score high.

4

Word2Vec / GloVe

Dense word vectors learned from context, where similar words sit close together. The idea that made embeddings mainstream.

5

Sentence embeddings

Sentence Transformers map whole sentences to vectors for semantic search, clustering, and deduplication. Small, fast, and run locally.

Searching and matching#

1

BM25

The standard keyword-ranking function behind search engines. Improves on TF-IDF with document-length normalization and term-frequency saturation.

2

Fuzzy matching

Edit distance (Levenshtein) and token-set ratios to match typos and near-duplicates: 'Jon Smith' ≈ 'John Smith'.

3

Hybrid search

Combine BM25 (exact terms, ids, names) with embeddings (meaning). Usually beats either alone - and is the default for good RAG.

4

Phonetic matching

Soundex/Metaphone for names that sound alike but are spelled differently.

Extracting structure#

1

Named entity recognition (spaCy)

Pre-trained pipelines tag people, organizations, places, dates, and money in milliseconds per document.

2

GLiNER

A compact model that extracts any entity type you name at runtime ('drug', 'symptom', 'SKU') - zero-shot NER without an LLM.

3

Part-of-speech tagging

Label nouns, verbs, adjectives. Useful for keyword extraction and rule-based pipelines.

4

Dependency parsing

Find grammatical relations (who did what to whom) to extract subject-verb-object triples.

Classifying and organizing#

1

Linear classifiers on TF-IDF

Logistic regression or Naive Bayes on TF-IDF features. Train in seconds; often within a few points of a fine-tuned transformer for topic or spam classification.

2

Topic modeling

LDA or embedding-based clustering (e.g., BERTopic) to discover themes across thousands of documents.

3

Language detection

Tiny character n-gram models identify the language of a string almost instantly.

That's 22. Here's how to choose:

If you need to...Try firstReach for an LLM when...
Pull ids, emails, datesRegexFormats are wildly inconsistent or buried in prose
Find documents by keywordBM25Queries are vague or conceptual
Find documents by meaningSentence embeddingsYou need to synthesize an answer, not just retrieve
Tag standard entitiesspaCy NEREntities are subtle or need reasoning
Tag custom entitiesGLiNERYou also need relations or normalization
Classify into fixed labelsTF-IDF + logistic regressionLabels need nuanced judgment and you lack training data
Deduplicate recordsFuzzy matching + embeddingsNever, usually

A complete, strong baseline classifier in a few lines:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score

clf = make_pipeline(
    TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True),
    LogisticRegression(max_iter=1000),
)
print(cross_val_score(clf, texts, labels, cv=5).mean())  # measure before you upgrade

Neural network fundamentals#

Every model on this site - from a sentiment classifier to a frontier LLM - is built from the same parts.

The neuron#

A neuron takes inputs, multiplies each by a weight, adds a bias, and passes the result through a nonlinear activation function:

z=∑iwixi+b⟶a=f(z)z = \sum_i w_i x_i + b \quad \longrightarrow \quad a = f(z)

z is the weighted sum; f is the activation. Stack many neurons into a layer, and layers into a network.

Without the nonlinearity, any stack of layers collapses into a single linear function. The activation is what lets networks model curves, interactions, and eventually language.

Activation function
A nonlinear function applied after each neuron's weighted sum - without it, any depth of layers would collapse to a single linear transformation.
ReLU
Rectified Linear Unit: max(0, x). The default activation for most networks - cheap to compute and avoids vanishing gradients.
GELU / SwiGLU
Smooth alternatives to ReLU used in modern transformers - slightly better quality at slightly higher compute cost.
Softmax
Turns a vector of raw scores into a probability distribution that sums to 1 - used for classification outputs and attention weights.
ActivationFormulaWhere you see it
Sigmoidσ(x) = 1 / (1 + e⁻ˣ)Binary outputs (probabilities); gates in LSTMs
Tanh(eˣ − e⁻ˣ) / (eˣ + e⁻ˣ)Older RNNs; zero-centered
ReLUmax(0, x)The default for CNNs and MLPs - cheap, avoids vanishing gradients
GELU / SwiGLUSmooth ReLU variantsTransformers (GPT, BERT, Llama)
Softmaxeᶻⁱ / Σ eᶻʲMulti-class output layer; attention weights

Training: forward pass, loss, backpropagation#

  1. 01Forward passInputs → predictions
  2. 02LossHow wrong? (e.g., cross-entropy)
  3. 03BackpropChain rule → gradient for every weight
  4. 04UpdateNudge weights against the gradient

↺ Update feeds back into Forward pass

One training step. Repeat over mini-batches of data for many epochs.

Backpropagation is just the chain rule applied layer by layer from the output backwards, computing how much each weight contributed to the error. Gradient descent then moves every weight a small step downhill:

Backpropagation
Applies the chain rule layer by layer from output to input, computing how much each weight contributed to the error.
Gradient descent
An optimization algorithm that repeatedly nudges parameters in the direction that reduces the loss - the foundation of all neural network training.
AdamW
The default optimizer for transformers - combines momentum, per-parameter adaptive learning rates, and properly decoupled weight decay.
Learning rate
Controls how big each parameter update is - too high and training diverges, too low and it crawls.
θ←θ−η ∇L(θ)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\, \nabla L(\boldsymbol{\theta})

η is the learning rate - too high diverges, too low crawls.

Optimizers#

OptimizerIdeaNotes
SGDStep along the mini-batch gradientSimple; still competitive for vision with tuning
MomentumKeep a running average of past gradientsSmooths noisy updates, speeds up ravines
AdamMomentum plus per-parameter adaptive step sizesThe default almost everywhere
AdamWAdam with decoupled weight decayThe default for transformers

Regularization: fighting overfitting#

A model that memorizes training data fails on new data. The standard defenses:

  • Dropout - randomly zero a fraction of activations during training so no neuron can rely on another.
  • Weight decay - penalize large weights, nudging toward simpler functions.
  • Early stopping - stop when validation loss stops improving.
  • Data augmentation - more varied training examples (crops and flips for images; paraphrases for text).
  • Normalization - batch norm (CNNs) or layer norm (transformers) stabilizes activations and speeds training.

CNNs and RNNs in one paragraph each#

Convolutional networks (CNNs) slide small learned filters across an image, detecting edges, then textures, then parts, then objects. Weight sharing makes them efficient and translation-invariant; they still power much of computer vision.

Recurrent networks (RNNs, LSTMs, GRUs) process sequences one step at a time, carrying a hidden state. LSTMs added gates to preserve information over longer spans. Transformers replaced them for language because attention parallelizes and connects distant tokens directly - see the Transformers deep dive.

ML library cheat sheets#

The functions you'll reach for most, by library.

scikit-learn - classical ML#

TaskFunction
Split datatrain_test_split(X, y, test_size=0.2, stratify=y)
Scale featuresStandardScaler().fit_transform(X)
Text featuresTfidfVectorizer(ngram_range=(1, 2))
Chain stepsmake_pipeline(scaler, model)
Cross-validatecross_val_score(model, X, y, cv=5)
TuneGridSearchCV(model, param_grid, cv=5)
Evaluateclassification_report(y_true, y_pred), confusion_matrix(...)
Common modelsLogisticRegression, RandomForestClassifier, KMeans, PCA

PyTorch - building and training networks#

import torch, torch.nn as nn

model = nn.Sequential(nn.Linear(784, 256), nn.ReLU(), nn.Dropout(0.1), nn.Linear(256, 10))
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
loss_fn = nn.CrossEntropyLoss()

for x, y in loader:            # a torch.utils.data.DataLoader
    opt.zero_grad()
    loss = loss_fn(model(x), y)
    loss.backward()            # backprop
    opt.step()                 # update

Also know: model.train() / model.eval(), torch.no_grad() for inference, .to("cuda"), and torch.save(model.state_dict(), path).

Keras - high-level training#

TaskFunction
Definekeras.Sequential([layers.Dense(128, activation="relu"), ...])
Configuremodel.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
Trainmodel.fit(X, y, validation_split=0.1, epochs=10, callbacks=[EarlyStopping()])
Predictmodel.predict(X_new)

XGBoost - the tabular-data champion#

For structured, tabular data, gradient-boosted trees usually beat neural networks.

from xgboost import XGBClassifier

model = XGBClassifier(n_estimators=500, learning_rate=0.05, max_depth=6,
                      subsample=0.8, colsample_bytree=0.8, early_stopping_rounds=50)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)])

Hugging Face Transformers - pretrained models#

from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification

classifier = pipeline("sentiment-analysis")          # batteries included
tok = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=3)

For fine-tuning, Trainer + TrainingArguments; for embeddings, the sentence-transformers library's SentenceTransformer("all-MiniLM-L6-v2").encode(texts).

Papers behind this guide

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.