Natural Language Processing
Turn human language into computable evidence. Trace tokenization, construct TF-IDF vectors, measure semantic similarity and design reliable classification and extraction systems.
text → x ∈ ℝᵈ → model(x)By the End of This Level, You Can
Six Building Blocks of Language Learning
NLP connects raw symbols to representations, context, tasks and measurable decisions.
Documents, sentences or conversations sampled from the environment where the system will operate.
A word, subword, character or byte produced by a defined tokenizer.
A mapping from token strings to numerical identifiers or vector dimensions.
Nearby words, sentence structure, document topic and conversational history change interpretation.
Sparse counts, TF-IDF values or dense embeddings expose evidence to a model.
Classification, extraction, retrieval, translation, summarization or generation defines the output and metric.
Language Is Symbolic, Ambiguous and Context Dependent
The same characters can express different meanings, while different sentences can communicate the same intent.
“Bank” can mean a financial institution or the side of a river.
“I saw the student with a telescope” does not state who owns the telescope.
“Can you open the window?” is grammatically a question but functionally a request.
“Dog bites man” and “man bites dog” contain the same words but describe different events.
Natural language contains morphology, syntax, semantics, discourse and pragmatics. Characters form tokens; tokens participate in phrases and sentences; references can cross sentence boundaries; speaker intent depends on shared knowledge. An NLP model never observes meaning directly. It learns statistical relationships between language inputs and task outputs from a corpus. Therefore the data definition, annotation rules, tokenizer and evaluation slices are part of the model—not merely preprocessing details.
In “This phone is sick,” the word “sick” may be negative in medical text but positive slang in a product conversation. Domain and surrounding context determine the useful interpretation.
Begin an NLP system-design answer by defining the document unit, language, domain, output task and latency requirement.
Text is not clean simply because it is readable. Encoding, Unicode variants, repeated text, templates, annotation disagreement and hidden metadata can dominate results.
Normalization and Tokenization Define What the Model Can See
Every cleaning rule can remove noise, destroy meaning or change the vocabulary.
Read text using the correct encoding and Unicode policy.
Apply justified case, whitespace and punctuation rules.
Create words, subwords, characters or bytes.
Convert tokens into stable vocabulary IDs.
Pad batches while preventing padding from affecting the model.
Whitespace tokenization is easy but fails for punctuation-rich text and languages without spaces. Word tokenizers preserve readable units but create large vocabularies and out-of-vocabulary words. Subword methods such as BPE and WordPiece learn reusable fragments, balancing vocabulary size with sequence length. Character and byte models remove unknown-token problems but produce longer sequences. Lowercasing, stemming, lemmatization, stop-word removal and punctuation deletion are task-dependent decisions: negation, casing, emoji and hashtags may be essential evidence.
“unhelpful” may be unseen as a whole word but represented using familiar fragments such as “un”, “help” and “ful”.
State whether the tokenizer is trained only on training data, versioned with the model and identical during serving.
Removing every stop word can reverse sentiment: deleting “not” from “not useful” leaves the opposite evidence.
🧮 Tokenization & Vector-Space Workbench
Process a real mini-corpus from raw text to normalized tokens, vocabulary, document vectors and cosine similarity. Every displayed number is calculated from the selected corpus.
Sparse Vectors Preserve Explicit Lexical Evidence
Bag of Words and TF-IDF ignore much structure, yet remain fast, interpretable and difficult to beat on many small-data tasks.
xⱼ ∈ {0,1}Token presenceUseful when repetition should not increase evidence.
xⱼ = count(tⱼ,d)Token frequencyPreserves repeated occurrences but favours long documents.
tf(t,d) × log((N+1)/(df+1))Local importance, global rarityDownweights tokens appearing across many documents.
(a·b)/(‖a‖‖b‖)Direction similarityCompares lexical profiles while reducing document-length effects.
A vocabulary gives every feature a stable coordinate. Unigrams capture individual tokens; n-grams add local order such as “not useful” but increase dimensionality and sparsity. TF-IDF multiplies within-document frequency by inverse document frequency. Exact library formulas differ in smoothing, normalization and sublinear term frequency, so save vectorizer settings with the model. Sparse matrices store only nonzero entries and pair naturally with linear classifiers.
If “course” occurs in every review, it identifies the domain but contributes little discrimination. “confusing” appearing in one review receives higher IDF and can be strong negative evidence.
For limited labelled text, compare word and character TF-IDF with Logistic Regression or Linear SVM before choosing a deep model.
TF-IDF does not understand meaning. Synonyms occupy different dimensions unless training examples connect them through the downstream model.
Classical NLP Models Turn Token Evidence into Decisions
Simple models expose their assumptions clearly and provide strong production baselines.
- Count documents and tokens per class.
- Estimate class priors.
- Apply Laplace smoothing to token likelihoods.
- Add log probabilities for query tokens.
- Choose the class with maximum log score.
- Construct sparse document vectors.
- Calculate a weighted linear score.
- Map the score through sigmoid or softmax.
- Optimize regularized cross-entropy.
- Calibrate and tune the decision threshold.
- Represent documents in sparse space.
- Find a maximum-margin separator.
- Penalize margin violations using C.
- Use class weights when appropriate.
- Calibrate scores if probabilities are required.
- Create overlapping character fragments.
- Build sparse counts or TF-IDF.
- Train a regularized linear model.
- Capture spelling and morphology variation.
- Evaluate by language and text quality.
Naive Bayes assumes conditional independence of tokens given the class, an unrealistic assumption that still produces useful estimates in high-dimensional text. Logistic Regression learns discriminative feature weights, while Linear SVM optimizes margin and often performs strongly with TF-IDF. Character n-grams are robust to misspellings and helpful for language identification, toxicity and morphologically rich languages. Use pipelines so vectorization is fitted within each training fold rather than on the full dataset.
A spam classifier may assign large positive weight to “free offer” and negative weight to “meeting schedule”; bigrams distinguish “not selected” from “selected”.
Be ready to derive Laplace-smoothed Naive Bayes in log space and explain why multiplying many probabilities underflows.
High accuracy can hide failure on a rare intent. Inspect per-class precision, recall, confusion and threshold-dependent costs.
Embeddings Learn Distributed Semantic Representations
Dense vectors place tokens or documents in a geometry where useful relationships can become measurable.
The distributional hypothesis says words used in similar contexts tend to have related meanings. Count-based methods construct a word–context matrix and may transform it with PPMI before dimensionality reduction. Word2Vec learns embeddings using predictive objectives such as skip-gram or CBOW; GloVe combines global co-occurrence statistics with a weighted factorization objective. These static methods assign one vector per token. Contextual encoders instead compute a vector from the complete input, allowing “bank” to differ across financial and river sentences.
If “Python” and “Java” frequently occur near “developer”, “code” and “application”, their context vectors become more similar than either is to an unrelated word.
Explain the difference among one-hot identity, sparse TF-IDF evidence, static word embeddings and contextual token embeddings.
Cosine proximity is learned association, not guaranteed synonymy, truth or fairness. Embeddings can encode stereotypes present in the corpus.
🧭 Context Window & Semantic Geometry Laboratory
Build a word–context matrix from actual sentences, apply count or PPMI weighting, calculate cosine similarity and reveal data-derived semantic neighbours.
NLP Tasks Require Different Output Structures and Metrics
A model is useful only when its output, matching policy and evaluation reflect the real language decision.
Predict document or sentence labels. Use macro/micro F1, per-class recall, calibration and threshold cost.
Predict a tag per token for NER or POS. Evaluate entity spans, not only individual token accuracy.
Rank relevant text. Use Recall@K, MRR, nDCG and judgement quality.
Generate target-language text. Combine automatic metrics with human adequacy and fluency review.
Produce concise faithful text. Measure overlap, semantic coverage, factual consistency and usefulness.
Return spans or generated answers. Use exact match/F1 plus groundedness and unanswerable-case evaluation.
Token classification requires alignment between tokenizer subwords and human labels. Named entities should usually be evaluated as complete spans using schemes such as BIO. Retrieval metrics care about rank position, while generation metrics cannot fully capture factuality or usefulness. Establish an annotation guide, measure inter-annotator agreement, preserve difficult examples and evaluate slices by language, length, topic, demographic mention and input quality.
If the reference entity is “New York City,” predicting only “New York” may achieve good token accuracy but fails exact span extraction.
Match each task to its output unit: document label, token tag, span, ranked list or generated sequence.
BLEU, ROUGE or embedding similarity alone cannot establish factual correctness or safe deployment.
Sequence Models Add Context Beyond Independent Tokens
Language meaning depends on order, long-range relationships and structured output constraints.
P(wₜ | wₜ₋ₙ₊₁…wₜ₋₁)Finite lexical contextCounts local sequences and requires smoothing for unseen n-grams.
hₜ = f(xₜ,hₜ₋₁)Recurrent learned memoryProcesses tokens sequentially using shared parameters.
P(y₁…yₙ | x)Structured label sequenceScores transitions so neighbouring output tags remain compatible.
context = ΣαᵢvᵢSelective accessLets a representation use relevant positions directly—the foundation for Level 21.
N-gram models estimate next-token probabilities from limited history and need additive, backoff or interpolation smoothing. Recurrent networks compress earlier inputs into a hidden state, while bidirectional encoders use left and right context when the complete sentence is available. CRFs are useful when output labels obey transition rules, such as an inside-entity tag following a valid beginning. Attention reduces the distance between related positions and leads directly to transformer architectures.
In named-entity recognition, a CRF can discourage an I-ORG tag immediately after O unless a valid B-ORG begins the organization span.
Distinguish causal language modelling, masked encoding and bidirectional sequence labelling by what context is legally visible.
A bidirectional encoder is valid for classifying a completed sentence but leaks future tokens in left-to-right generation.
Reliable NLP Depends on Data Boundaries, Languages and Human Impact
Text models often learn source, author and annotation shortcuts that disappear after deployment.
Keep the same user, thread, template or near-duplicate document inside one split.
Use chronological evaluation when topics, vocabulary or policy change over time.
Exclude moderator outcomes, future replies and metadata unavailable when prediction occurs.
Report performance by language, script, code-mixing, dialect and transliteration pattern.
Minimize personal text, control retention, redact identifiers and restrict diagnostic logs.
Define confidence-based escalation, appeal and override for consequential language decisions.
Near-duplicate templates can cross random splits and make memorization look like generalization. A support-ticket classifier may learn agent signatures instead of customer intent; a toxicity model may associate identity terms with harmful labels; a multilingual model may perform well overall while failing a smaller language. Evaluation must mirror deployment and include abstention, confidence calibration, drift monitoring, privacy review and a documented response when the model is uncertain or harmful.
If messages from one conversation appear in both train and test, repeated phrases and quoted replies leak the answer even when no row is identical.
For system design, connect model errors to workflow cost: false routing, missed abuse, delayed support or unfair moderation.
Removing explicit names does not guarantee anonymity; rare phrases, locations and metadata can still identify a person.
Trace Multinomial Naive Bayes from First Principles
Follow class priors, every training document, token counts, Laplace-smoothed query likelihoods and final log-score comparison. The cursor returns through each loop exactly as Python executes.
—Waiting for print(...)
NLP Logic Before Framework Calls
Use these compact procedure maps for revision, coding rounds and interviews.
- Fit normalization and vocabulary on training text.
- Count term frequency per document.
- Count document frequency per token.
- Calculate smoothed inverse document frequency.
- Multiply, normalize and transform validation consistently.
- Estimate class priors from training labels.
- Count token occurrences per class.
- Add smoothing to numerator and vocabulary denominator.
- Add log prior and query-token log likelihoods.
- Select the class with the greatest total log score.
- Select a centre token and context window.
- Create positive centre–context pairs.
- Sample unrelated negative context tokens.
- Score pairs using embedding dot products.
- Update vectors to separate positive and negative pairs.
- Define entity schema and annotation rules.
- Tokenize while retaining label alignment.
- Encode contextual token representations.
- Predict token or structured sequence labels.
- Reconstruct spans and measure entity-level F1.
💻 Natural Language Processing Challenges
Attempt each program independently. Workspaces, hints and model programs remain collapsed initially.
Test Your Language-Model Reasoning
Select one answer per question. Results show your choice, the correct answer and a clear explanation.
Diagnose NLP Systems Like an ML Engineer
Use evidence from data, representations, evaluation slices and deployment constraints before changing the architecture.
Check duplicate templates, author overlap, thread leakage, vectorizer fitting and label-revealing metadata.
Inspect annotation volume, class weights, thresholds, macro F1 and hard-negative examples.
Compare word, subword, character or byte tokenization and inspect vocabulary coverage.
Measure each language and script; inspect transliteration, code-mixing and tokenizer fragmentation.
Track new terms, topic distribution, embedding neighbours, confidence and human disagreement.
Add confidence-based abstention, policy filters, human review, appeals and diagnostic logging controls.
🎤 Natural Language Processing — Interview Questions
Answer aloud before selecting Show Answer for each explanation.
An NLP Model Is a Language Decision Pipeline
Specify language, unit and task.
Preserve useful linguistic evidence.
Build sparse or dense vectors.
Choose a task-aligned model.
Evaluate slices and human impact.
Natural language processing becomes trustworthy when the corpus, tokenizer, representation, model evidence, evaluation unit and failure-handling policy can all be explained.
Eight Practical NLP Habits
Inspect raw Unicode text, language distribution and repeated templates before cleaning.
Keep normalization conservative until task evidence justifies removing information.
Measure token lengths and unknown or fragmented words by language and domain.
Build word and character TF-IDF linear baselines before expensive fine-tuning.
Fit tokenizers and vectorizers only on training data within each evaluation fold.
Read false positives and false negatives; text errors reveal annotation and shortcut problems.
Evaluate confidence, abstention and calibration when predictions trigger actions.
Version the tokenizer, vocabulary, labels, normalization and maximum-length policy with the model.
Strengthen NLP Reasoning
Calculate intermediate representations and defend every modelling decision.
- 01
Compare word, subword, character and byte tokenization for Telugu–English code-mixed text.
- 02
Explain when lowercasing changes task evidence.
- 03
Create unigram and bigram vocabularies for three short documents.
- 04
Calculate TF, document frequency and smoothed IDF by hand.
- 05
Calculate cosine similarity for two sparse document vectors.
- 06
Derive one Laplace-smoothed Naive Bayes prediction.
- 07
Explain why log probabilities are used in Naive Bayes.
- 08
Compare Logistic Regression and Linear SVM for TF-IDF text.
- 09
Construct centre–context pairs for skip-gram training.
- 10
Calculate one PPMI word–context value.
- 11
Convert BIO tags into named-entity spans.
- 12
Select metrics for imbalanced intent classification.
- 13
Identify five leakage paths in support-ticket text.
- 14
Design multilingual monitoring for a production moderation model.
