Knowledge / Artificial Intelligence and Data Science / Natural language processing basics

Natural language processing basics

Artificial Intelligence and Data Science (B.E./B.Tech) · AI applications · free study notes for exams, placements and interviews

In short

Natural Language Processing (NLP) is the branch of AI that lets computers read, interpret and generate human language — text or speech — by combining linguistics, statistics and machine learning. It matters because most enterprise data is unstructured text: support tickets, policy documents, claim notes, court orders, chat logs. Indian university syllabi (AICTE model curriculum for AI&DS, UGC CBCS) examine the classical pipeline — tokenization, morphology, n-gram language models, POS tagging with HMMs, parsing, information extraction and text classification — while GATE DA/CS asks TF-IDF, Naive Bayes, perplexity and edit-distance numericals. Placement rounds at TCS, Infosys, Wipro, Accenture, Fractal, Zoho, Freshworks, Jio Haptik, Gupshup and bank/insurance analytics teams test exactly these fundamentals before any LLM question.

Explained

What NLP is, and why language is hard

Text preprocessing pipeline

  1. Text acquisition and cleaning: strip HTML, fix encoding, Unicode normalisation (NFC/NFKC) so visually identical Devanagari sequences compare equal.
  2. Sentence segmentation: split on ., ?, !, and the Devanagari danda ।; abbreviations ("Dr.", "Rs.") and decimals break naive splitting.
  3. Tokenization: split into tokens (words, punctuation). Types — whitespace, rule-based/regex, Treebank, and subword (BPE, WordPiece, SentencePiece) which handles out-of-vocabulary words and suits morphologically rich Indian languages.
  4. Case folding: lowercasing helps matching but destroys cues (US vs us); irrelevant for Indic scripts, which are unicase.
  5. Stop-word removal: drop high-frequency function words (the, is, of; का, है, और). Harmful for sentiment ("not good") and phrase search.
  6. Stemming: crude suffix chopping to a stem; Porter stemmer (five rule phases), Lovins, Snowball. Fast, language-specific, may produce non-words ("studies" → "studi").
  7. Lemmatization: dictionary- plus POS-based reduction to the valid dictionary form (lemma): "better" → "good", "running/ran" → "run". Slower, more accurate, needs a lexicon such as WordNet (IndoWordNet covers 18 Indian languages, from IIT Bombay).
  8. Other steps: spell correction, normalisation of numbers/dates/currency (₹1,00,000 → NUM), de-accenting, removing rare terms, handling emojis and URLs.
  9. Morphology terms: morpheme (smallest meaning unit), root/stem, affix (prefix/suffix/infix), inflectional morphology (plays, played — same word class) vs derivational (play → playful — new class). Finite-state transducers (FSTs) are the classical morphological analyser; the two-level/Kimmo model is a syllabus favourite.

Representing text: from counts to vectors

Language models and probability

Core sequence and structure tasks

Applied tasks, evaluation and tooling

Key points

Formulas and examples

Term frequency: tf(t,d) = count(t,d) / (total tokens in d) [raw count or log(1+count) also used; dimensionless]
Inverse document frequency: idf(t) = log( N / df(t) ) or the smoothed log( (1+N)/(1+df(t)) ) + 1
N = number of documents in the corpus; df(t) = number of documents containing term t
TF-IDF weight: w(t,d) = tf(t,d) × idf(t)
Cosine similarity: cos θ = (A · B) / (|A| |B|) = Σ aᵢbᵢ / (√Σaᵢ² · √Σbᵢ²) (1 = identical direction, 0 = orthogonal)
Jaccard similarity: J(A,B) = |A ∩ B| / |A ∪ B|
Chain rule: P(w₁…wₙ) = Π P(wᵢ | w₁…wᵢ₋₁)
Bigram MLE: P(wᵢ | wᵢ₋₁) = C(wᵢ₋₁ wᵢ) / C(wᵢ₋₁)
Laplace (add-one): P(wᵢ | wᵢ₋₁) = (C(wᵢ₋₁ wᵢ) + 1) / (C(wᵢ₋₁) + V) V = vocabulary size
Perplexity: PP(W) = P(w₁…w_N)−1/N = 2H, where H = −(1/N) Σ log₂ P(wᵢ | context) N = number of tokens
Naive Bayes: ĉ = argmax_c [ log P(c) + Σ_i log P(wᵢ | c) ]
P(w | c) with Laplace = (count(w,c) + 1) / (Σ_w' count(w',c) + |V|)
Precision P = TP/(TP+FP); Recall R = TP/(TP+FN); F1 = 2PR/(P+R)
Accuracy = (TP+TN)/(TP+TN+FP+FN)
BLEU = BP × exp( Σ wₙ log pₙ ), BP = 1 if c > r else e1−r/c (c = candidate length, r = reference length)
Levenshtein edit distance: D(i,j) = min[ D(i−1,j)+1, D(i,j−1)+1, D(i−1,j−1) + (0 if xᵢ=yⱼ else cost_sub) ]
Zipf's law: f(r) ∝ 1/r (f = frequency, r = frequency rank)

Example 1 — TF-IDF by hand. Corpus of N = 4 support tickets. The term "refund" appears in 2 of them. In ticket d₁ of 50 tokens, "refund" appears 3 times.

Example 2 — Cosine similarity of two documents. Vocabulary (loan, EMI, delay, refund). A = (2, 1, 0, 0), B = (3, 0, 1, 0).

Example 3 — Bigram probability and perplexity. Training corpus (3 sentences, <s> and </s> added): <s> I like NLP </s>, <s> I like tea </s>, <s> I love NLP </s> Counts: C(<s>) = 3, C(<s> I) = 3, C(I) = 3, C(I like) = 2, C(I love) = 1, C(like) = 2, C(like NLP) = 1, C(like tea) = 1, C(NLP) = 2, C(NLP </s>) = 2.

Example 4 — Naive Bayes sentiment classification. Training: 3 positive and 2 negative reviews. Positive class has 10 word tokens with counts {good:4, fast:3, service:3}; negative class has 8 tokens with counts {bad:4, slow:2, service:2}. Vocabulary V = {good, fast, service, bad, slow} → |V| = 5. Classify "good service".

Example 5 — Edit distance and NER evaluation. (a) Levenshtein distance between "kitten" and "sitting" (unit substitution cost) = 3: k→s, e→i, insert g. (b) An NER model on 100 Hindi news sentences predicts 120 PERSON spans; 90 are exactly correct; the gold data has 150 PERSON spans.

AspectStemmingLemmatization
MethodSuffix-stripping rulesDictionary + POS/morphology
OutputMay not be a real word (studi)Always a valid lemma (study)
SpeedVery fastSlower
Needs POSNoYes, for accuracy
Typical useSearch indexing, large corporaLinguistic analysis, QA, chatbots
RepresentationOrder keptDimensionalitySemantics captured
One-hotNo\V\per word, sparseNone
Bag of WordsNo\V\, sparseFrequency only
TF-IDFNo\V\, sparseTerm importance
n-gram countsLocal onlyVery largeShort phrases
Dense embeddingsVia model100-1,024, denseSimilarity, analogy
# Classical pipeline: TF-IDF + Naive Bayes on support tickets
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.metrics import classification_report

X_train = ["refund not received", "EMI debited twice", "loan approved fast"]
y_train = ["refund", "payment", "loan"]

clf = make_pipeline(
    TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True, min_df=1),
    MultinomialNB(alpha=1.0),          # alpha = Laplace smoothing
)
clf.fit(X_train, y_train)
print(clf.predict(["my refund is pending"]))   # -> ['refund']

Where it is used

Interview questions

Common mistakes

Related topics

Text embeddings and semantic search · Large language models and prompt engineering · Speech recognition and audio AI · Machine learning classification and evaluation metrics · Probability and information theory (entropy, Bayes) · Automata and formal languages (regular expressions, CFGs)

Open in the Knowledge reader →Find jobs →