Module 3 — NLP + Financial Text AI
Same theory-first structure as Modules 1 and 2: for every technique below, what it is, why it exists — the specific problem it was invented to solve — what else you could use instead, and a real financial example. Modules 1 and 2 worked on numbers and pixels; Module 3 adds a third kind of input entirely — free-flowing text — and the techniques here exist because text doesn't arrive as a table or a fixed-size grid.
Recap — what RR Finance already has
Module 3 is not a fresh start. Here's exactly what it inherits before adding text as a new capability.
A validated 800-row loan-risk dataset, a logistic-regression baseline (ROC-AUC ≈ 0.70), an Isolation Forest anomaly screen, and a documented data-poisoning defence — all saved as reusable artifacts.
An ANN benchmarked honestly against the Module 1 baseline, a cheque-digit CNN, and the first inference-time attack (FGSM/PGD adversarial examples) with a measured adversarial-training defence.
Why text needs its own techniques
A sentence has no fixed length the way a 28×28 image always has 784 pixels, and the word "loan" is not a number. How you turn text into numbers is most of what this module teaches — and it brings two new risks with it that pixels and tabular ratios never did.
A librarian, not a conversation partner
Bag-of-Words/TF-IDF catalogue which words appear — blind to order and meaning. Contextual embeddings track what each word means given everything around it.
A dictionary vs. context
Word2Vec gives "bank" one fixed vector. BERT-style contextual embeddings give the same word a different vector depending on the sentence — a fundamentally different idea.
Two new attack surfaces
Prompt injection — text trying to hijack instructions, not just describe facts — and PII exposure, both explored as this module's security lessons.
Bag-of-Words & TF-IDF
The simplest possible way to turn text into numbers — and still a strong baseline today.
Bag-of-Words represents a document as raw word counts, ignoring order entirely. TF-IDF (Term Frequency–Inverse Document Frequency) refines this by down-weighting words that appear in almost every document and up-weighting words distinctive to a specific one.
| Option | Trade-off |
|---|---|
| TF-IDF | Fast, interpretable, no training corpus needed beyond your own documents — the right first baseline before reaching for embeddings |
| Word2Vec (next lesson) | Captures word meaning/similarity, needs a large training corpus |
| BERT embeddings (Lesson 3) | Captures context-dependent meaning, needs the most compute and data |
✓ Use it when
- You need a fast, interpretable baseline classifier over text
- Word order and deep context matter less than topic/keyword signal
✗ Reach for something else when
- Word order and meaning genuinely matter — "the bank approved the loan" and "the loan approved the bank" are identical to a bag-of-words model
Word2Vec
Giving words meaning by teaching a model to guess them from their neighbours.
Word2Vec learns a dense vector per word by training a shallow neural network to predict a word from its surrounding context (or vice versa) across a large corpus — words used in similar contexts end up with similar vectors, learned entirely without labels.
| Option | Trade-off |
|---|---|
| Word2Vec | Fast, well-understood, the historical breakthrough that made "dense word embeddings" the default — but gives every word exactly ONE vector, regardless of context |
| GloVe | A similar-era alternative using global co-occurrence statistics rather than a prediction task; comparable quality |
| fastText | Extends Word2Vec with subword information, handling misspellings and rare words better |
| Contextual embeddings (Lesson 3) | Solves Word2Vec's core limitation directly — the same word gets different vectors in different contexts |
P(w_O|w_I) = softmax(v'_O · v_I)
Contextual Embeddings: The Idea Behind BERT
The same word, a different vector, depending on what surrounds it.
A Transformer's self-attention mechanism computes each word's representation while looking at every other word in the sentence — so "bank" in "loan from the bank" and "bank" in "river bank" produce genuinely different output vectors, something Word2Vec structurally cannot do.
✓ What the notebook shows
- A tiny, fully local, from-scratch transformer encoder proving the mechanism: the same token produces different vectors in different sentences
- Real pretrained BERT loaded from Hugging Face (when internet access allows) for genuinely meaningful contextual embeddings
✗ What the toy encoder can't show
- Untrained weights mean the toy version's exact numbers aren't meaningful — only the mechanism is real. Meaningful values require the pretrained model, or real training on real data.
Named Entity Recognition (NER)
Pulling structured facts out of prose.
NER automatically identifies and labels spans of text as specific entity types — people, organisations, money amounts, dates — turning unstructured prose into structured, extractable facts.
Fine-Tuning NER for Domain-Specific Entities
Teaching a general-purpose model your organisation's own vocabulary.
Adding a new entity label (e.g. LOAN_PRODUCT) to an existing pretrained NER pipeline, then training just that component on a small set of labelled examples — far cheaper than training a full NER model from nothing.
| Option | Trade-off |
|---|---|
| Fine-tune spaCy's existing NER component | Works with a handful of labelled examples, fast to train, lower capacity ceiling |
| Fine-tune a BERT-based token classifier | Higher capacity, generally better with hundreds+ of labelled examples, needs a GPU and meaningfully more time |
Sentiment Analysis: TF-IDF Baseline to FinBERT
Classifying financial text as positive, negative or neutral — and why domain matters.
Sentiment analysis classifies text by emotional/evaluative tone. The notebook builds a fast TF-IDF + Logistic Regression baseline (Module 1's classification pattern, applied to text), then shows FinBERT — BERT further pretrained specifically on financial text — as the production upgrade.
✓ When the TF-IDF baseline is enough
- Text is fairly unambiguous, or you need something fast and fully local with no external dependency
✗ When you need FinBERT instead
- Real financial text is genuinely ambiguous — the notebook's baseline scores near-perfect accuracy on synthetic templates, then is shown honestly for what it is: a demo that doesn't yet face the ambiguity real headlines contain
Event Study: Sentiment vs. Next-Day Returns
Testing whether a signal has real predictive value before trusting it.
An event study compares outcomes (like next-day stock returns) around a defined event (like a strongly positive or negative news day) to test whether the event actually relates to what happens next — rather than assuming it does because a story sounds plausible.
Aspect-Based Sentiment on Earnings Calls
One sentence can be simultaneously positive and negative — about different things.
Aspect-Based Sentiment Analysis (ABSA) assigns sentiment per topic within a document, rather than one blended label for the whole thing — "revenue grew strongly but costs also rose" is positive about revenue and negative about costs at the same time.
Prompt Injection & Evasion Attacks
Text is the first data type in this course anyone can write directly.
Evasion attacks manipulate a text classifier's output by exploiting how it represents text (e.g. stuffing buzzwords to shift a TF-IDF vector) without changing the underlying facts. Prompt injection specifically targets systems that follow instructions embedded in text, hijacking their behaviour via text crafted to look like a command.
| Attack | Targets | Demonstrated how |
|---|---|---|
| Evasion (keyword stuffing) | Any text classifier, including plain TF-IDF/LogReg | Real, working attack in the notebook — buzzwords mechanically shift the model's decision |
| Prompt injection proper | Instruction-following systems (LLMs) | Illustrated with a deliberately naive mock system — the real thing arrives with real LLMs in Modules 4–5 |
PII Detection & Redaction
Free text leaks personal data in ways a spreadsheet of ratios never does.
Automatically finding and removing personally identifiable information — names, emails, phone numbers, ID numbers — from free text before it flows into training data, logs, or shared reports.
| Option | Trade-off |
|---|---|
| Regex only | Transparent and fast for fixed-pattern PII (emails, phone numbers) — but a person's name has no fixed pattern at all, so regex alone structurally cannot catch it |
| Presidio (NLP + patterns) | Catches names via NER, patterns via regex — genuinely more complete, though not perfect (see the honest false-positive finding below) |
Module 3 hand-off
The notebook saves a sentiment baseline model, a fine-tuned NER pipeline recognising loan products, and redacted case-note datasets — extending RR Finance's system with a third data modality alongside Module 1's tables and Module 2's images.