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#
Regular expressions
Emails, order ids, dates, phone numbers, log patterns. Deterministic, instant, and testable. Often the best solution outright.
Normalization
Lowercasing, Unicode normalization (NFKC), stripping accents and extra whitespace so 'Café', 'cafe' and 'CAFE ' compare equal.
Tokenization
Splitting text into words or subwords. Language-aware tokenizers handle contractions, punctuation, and scripts without spaces.
Stop-word removal
Drop very common words ('the', 'is') for keyword methods. Keep them for anything that needs meaning or negation.
Stemming
Chop suffixes by rule: 'running' → 'run', 'studies' → 'studi'. Fast and crude - fine for search recall.
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#
Bag of words
Count each vocabulary word in a document. Ignores order, but a surprisingly strong baseline for classification.
N-grams
Count word pairs and triples too ('not good', 'New York') to recover some local order.
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.
Word2Vec / GloVe
Dense word vectors learned from context, where similar words sit close together. The idea that made embeddings mainstream.
Sentence embeddings
Sentence Transformers map whole sentences to vectors for semantic search, clustering, and deduplication. Small, fast, and run locally.
Searching and matching#
BM25
The standard keyword-ranking function behind search engines. Improves on TF-IDF with document-length normalization and term-frequency saturation.
Fuzzy matching
Edit distance (Levenshtein) and token-set ratios to match typos and near-duplicates: 'Jon Smith' ≈ 'John Smith'.
Hybrid search
Combine BM25 (exact terms, ids, names) with embeddings (meaning). Usually beats either alone - and is the default for good RAG.
Phonetic matching
Soundex/Metaphone for names that sound alike but are spelled differently.
Extracting structure#
Named entity recognition (spaCy)
Pre-trained pipelines tag people, organizations, places, dates, and money in milliseconds per document.
GLiNER
A compact model that extracts any entity type you name at runtime ('drug', 'symptom', 'SKU') - zero-shot NER without an LLM.
Part-of-speech tagging
Label nouns, verbs, adjectives. Useful for keyword extraction and rule-based pipelines.
Dependency parsing
Find grammatical relations (who did what to whom) to extract subject-verb-object triples.
Classifying and organizing#
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.
Topic modeling
LDA or embedding-based clustering (e.g., BERTopic) to discover themes across thousands of documents.
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 first | Reach for an LLM when... |
|---|---|---|
| Pull ids, emails, dates | Regex | Formats are wildly inconsistent or buried in prose |
| Find documents by keyword | BM25 | Queries are vague or conceptual |
| Find documents by meaning | Sentence embeddings | You need to synthesize an answer, not just retrieve |
| Tag standard entities | spaCy NER | Entities are subtle or need reasoning |
| Tag custom entities | GLiNER | You also need relations or normalization |
| Classify into fixed labels | TF-IDF + logistic regression | Labels need nuanced judgment and you lack training data |
| Deduplicate records | Fuzzy matching + embeddings | Never, 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 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.
| Activation | Formula | Where you see it |
|---|---|---|
| Sigmoid | σ(x) = 1 / (1 + e⁻ˣ) | Binary outputs (probabilities); gates in LSTMs |
| Tanh | (eˣ − e⁻ˣ) / (eˣ + e⁻ˣ) | Older RNNs; zero-centered |
| ReLU | max(0, x) | The default for CNNs and MLPs - cheap, avoids vanishing gradients |
| GELU / SwiGLU | Smooth ReLU variants | Transformers (GPT, BERT, Llama) |
| Softmax | eᶻⁱ / Σ eᶻʲ | Multi-class output layer; attention weights |
Training: forward pass, loss, backpropagation#
- 01Forward passInputs → predictions
- 02LossHow wrong? (e.g., cross-entropy)
- 03BackpropChain rule → gradient for every weight
- 04UpdateNudge weights against the gradient
↺ Update feeds back into Forward pass
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.
η is the learning rate - too high diverges, too low crawls.
Optimizers#
| Optimizer | Idea | Notes |
|---|---|---|
| SGD | Step along the mini-batch gradient | Simple; still competitive for vision with tuning |
| Momentum | Keep a running average of past gradients | Smooths noisy updates, speeds up ravines |
| Adam | Momentum plus per-parameter adaptive step sizes | The default almost everywhere |
| AdamW | Adam with decoupled weight decay | The 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#
| Task | Function |
|---|---|
| Split data | train_test_split(X, y, test_size=0.2, stratify=y) |
| Scale features | StandardScaler().fit_transform(X) |
| Text features | TfidfVectorizer(ngram_range=(1, 2)) |
| Chain steps | make_pipeline(scaler, model) |
| Cross-validate | cross_val_score(model, X, y, cv=5) |
| Tune | GridSearchCV(model, param_grid, cv=5) |
| Evaluate | classification_report(y_true, y_pred), confusion_matrix(...) |
| Common models | LogisticRegression, 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#
| Task | Function |
|---|---|
| Define | keras.Sequential([layers.Dense(128, activation="relu"), ...]) |
| Configure | model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) |
| Train | model.fit(X, y, validation_split=0.1, epochs=10, callbacks=[EarlyStopping()]) |
| Predict | model.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
Word2Vec: Word Representations in Vector Space
Dense word embeddings trained on context - the idea that meaning can be a vector.
Google, 2013
Sentence-BERT
Siamese BERT networks for fast, comparable sentence embeddings - the backbone of semantic search.
UKP Lab, TU Darmstadt, 2019
GLiNER: Generalist NER
A small bidirectional transformer that extracts any entity type you name - no LLM required.
2023
Adam: Stochastic Optimization
Adaptive per-parameter learning rates from gradient moments - the default optimizer.
Kingma & Ba, 2014