Concepts and worked examples
Text representation and mining
Turn text into useful features for search, prediction, and analysis.
Documents become measurable features
A document can be a message, sentence, report, or clinical note; a corpus is a collection of documents. Tokens are units produced by a tokenizer, not necessarily ordinary words: punctuation, subwords, codes, and phrases may be tokens. Text is called unstructured because it lacks a ready-made tabular schema, not because grammar, layout, and meaning lack structure. Decide the unit of analysis and prediction moment before constructing features.
A bag-of-words representation fixes a vocabulary and gives each document a vector of term counts or indicators. Most entries are zero, so a sparse matrix stores only nonzero values and their locations. This can represent thousands of terms efficiently, though vocabulary growth, rare identifiers, and accidental memorization remain concerns. Unknown terms at prediction time are typically ignored by a fixed vocabulary or handled by a documented alternative such as hashing.
TF, document frequency, and explicit IDF conventions
Term frequency TF(t, d) measures occurrence within document d. State whether it is a raw count, a document-length-normalized count, a binary indicator, or a transformed count such as 1 + ln(count). Document frequency df(t) counts documents containing t, regardless of repetitions. With N documents, unsmoothed IDF(t) = ln[N/df(t)]. TF-IDF(t, d) = TF(t, d) × IDF(t). Token count and document frequency answer different questions and cannot be substituted without changing the weighting.
Worked corpus: D1 = “red red apple”, D2 = “red berry”, D3 = “red apple”, D4 = “red pear”. There are four documents; df(red) = 4, df(apple) = 2, and df(berry) = df(pear) = 1. Under raw-count TF and natural-log unsmoothed IDF, IDF(red) = 0, IDF(apple) = ln 2 ≈ 0.693, and IDF(berry) = ln 4 ≈ 1.386. In vocabulary order (red, apple, berry, pear), D1 becomes (0, 0.693, 0, 0). Repeating a ubiquitous term does not make its unsmoothed TF-IDF nonzero.
Optional L2 normalization divides the resulting vector by its Euclidean length. It helps compare direction rather than document length. An empty or all-zero vector has no cosine direction and requires a fallback. IDF is learned from the training corpus only during predictive evaluation; fitting it on held-out documents leaks their distribution. A retrieval system may intentionally index its available document collection, but that is a different evaluation boundary.
Rarity is not supervised information gain
If p = df(t)/N is the probability a randomly chosen document contains a term, unsmoothed IDF equals its presence self-information −ln p. For a binary presence variable, absence has self-information −ln(1 − p), and entropy is H = −p ln p − (1 − p) ln(1 − p). At p = 0.25, presence information is ln 4 ≈ 1.386, absence information is −ln 0.75 ≈ 0.288, and expected self-information is 0.25 × 1.386 + 0.75 × 0.288 ≈ 0.562 nats. At probability zero, use the limiting convention 0 ln 0 = 0.
This is entropy of term presence, not class uncertainty removed by the term. Supervised information gain is IG(Y; T) = H(Y) − Σₜ P(T = t)H(Y | T = t). A rare random identifier can have large IDF and negligible reliable class information. A common term can be predictive. Minimum document frequency is an unsupervised stability filter; information gain uses labels. Neither high rarity nor high training information gain guarantees generalization after searching thousands of candidate terms. Select features inside cross-validation.
Preprocess for the task, not by ritual
Lowercasing merges case variants but can erase distinctions between names, acronyms, and ordinary words. Stemming heuristically removes or transforms endings; lemmatization uses linguistic analysis to map forms. Neither guarantees that the result preserves meaning. Stopword removal can reduce noise but deleting “not” can reverse sentiment, and deleting function words can damage authorship or phrase analysis. Preserve negation, dosage units, dates, or domain abbreviations when the task needs them. Validate decisions rather than assuming every preprocessing step helps.
For “the quick brown fox jumps”, unigrams are “the”, “quick”, “brown”, “fox”, “jumps”. Adjacent bigrams are “the quick”, “quick brown”, “brown fox”, “fox jumps”. The notes' list of isolated words is a unigram representation, not an example of longer word sequences. If stopwords are removed before forming bigrams, adjacency changes; define the ordering of operations. Combining unigrams and bigrams captures some local order but increases dimensionality and creates many rare features. Bag-of-words still cannot represent arbitrary long-range relations or fully understand negation.
Retrieval and supervised classification
Cosine retrieval ranks documents by normalized vector dot product with a query. It does not require class labels. A supervised classifier instead learns from document labels to predict categories or probabilities. Linear logistic regression, linear SVMs, and multinomial naive Bayes are useful baselines. Tune vocabulary limits, n-grams, feature selection, and the classifier together within training folds; split duplicate messages, authors, patients, or time windows according to deployment.
Naive Bayes assumes feature independence conditional on the class, not unconditional independence. Multiplying class-conditional evidence can be efficient and incrementally updated, but correlated terms can double-count evidence. Contrary to an overly reassuring reading of the notes, double-counting can change the winning class as well as distort probabilities. Smoothing prevents unseen terms from forcing zero likelihood. Assess calibration if downstream decisions depend on probabilities, not merely labels or ranking.
Entities and latent topics
Named entity recognition identifies spans such as people, organizations, locations, medications, or dates. Entity normalization or linking maps variants to a common entity and is a separate task: recognizing “New York” does not by itself disambiguate every place reference. Rules, dictionaries, and trained models can all help, with domain-specific annotation and error analysis. Sensitive spans demand additional controls; see PII and PHI handling. Automatic redaction can miss identifiers or remove clinically useful context.
Latent semantic indexing, also called latent semantic analysis, uses truncated SVD of a term–document representation to produce low-dimensional factors. These factors can have positive and negative weights and are not topic probabilities. Latent Dirichlet Allocation is a probabilistic topic model in which documents mix topics and topics distribute probability over words. Here LDA means Latent Dirichlet Allocation, not linear discriminant analysis. Topics summarize statistical co-occurrence; they do not automatically recover intent, causal explanations, or stable human categories. Compare topic stability and downstream usefulness, not only attractive word lists.
Question: Why might removing stopwords lower performance?
Stopwords can carry negation, syntax, domain phrases, or stylistic signals. Removal is task-dependent and must be evaluated inside the same leakage-safe pipeline as the model.
Question: Does TF-IDF measure how predictive a word is?
No. It combines within-document frequency and corpus rarity. Prediction requires label-based evidence evaluated on held-out data; information gain is supervised, whereas IDF is not.
Connect text vectors to cosine similarity and SVD and pipeline validation.