⚡0 XP🔥0

Natural Language Processing (NLP)

Lesson 6 of 8 ⏱ 6 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Python

How computers process human language - tokenisation, normalisation and stop words, bag-of-words and TF-IDF, a sentiment classifier, word embeddings and cosine similarity, and the challenges of Indian languages.

Natural Language Processing (NLP) teaches computers to read, understand and generate human language. It powers search engines, spam filters, chatbots, voice assistants, translation between Indian languages, resume screening and sentiment analysis of product reviews.

Language is hard for computers: it is ambiguous ("I saw her duck"), depends on context and tone ("great, another Monday..."), mixes languages (Hinglish!), and keeps changing.

The NLP pipeline#

  1. Text cleaning / normalisation - lower-case, remove punctuation or HTML, fix spelling.
  2. Tokenisation - split into words or sub-words.
  3. Stop-word removal (optional) - drop very common words like "the", "is", "and".
  4. Stemming / lemmatisation (optional) - reduce words to a base form: "running", "ran" → "run".
  5. Vectorisation - turn text into numbers.
  6. Modelling - classify, cluster, search, translate or generate.
▶ Try it YourselfPython
Ctrl + Enter to run
Output
tokens : ["vindhyaedu's", 'python', 'course', 'was', 'amazing', 'the', 'projects', 'were', 'amazing', 'and', 'the', 'trainer', 'was', 'very', 'helpful']
content: ['vindhyaedu', 'python', 'course', 'amazing', 'projects', 'amazing', 'trainer', 'helpful']
counts : [('amazing', 2), ('vindhyaedu', 1), ('python', 1)]
हिंदी में समझें

NLP का पहला कदम है text को छोटे टुकड़ों (tokens) में तोड़ना और साफ़ करना - छोटे अक्षर (lowercase), बेकार चिह्न हटाना, और "the, is, and" जैसे बहुत आम शब्द (stop words) हटाना। फिर text को numbers में बदला जाता है, क्योंकि model सिर्फ़ numbers पर काम करते हैं।

Bag-of-words and TF-IDF#

Bag-of-words represents a document by how many times each vocabulary word occurs - ignoring order:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
vocabulary: ['and', 'course', 'data', 'interviews', 'java', 'projects', 'python', 'science', 'with']
[[0 1 0 0 0 1 1 0 1]
 [1 1 0 1 1 1 0 0 1]
 [0 0 1 0 0 1 1 1 0]]

TF-IDF of document 2:
  interviews  0.584
  java        0.584
  course      0.445
  projects    0.345

TF-IDF (term frequency × inverse document frequency) lowers the weight of words that appear in many documents ("projects", "course") and raises words that are distinctive for a document ("java", "interviews"). stop_words="english" drops very common words like "and" and "with" first. It is the classic way to build search engines and text classifiers.

A sentiment classifier#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
great trainer and useful projects      -> pos  (P(pos) = 0.77)
poor explanations, boring              -> neg  (P(pos) = 0.37)
not good at all                        -> neg  (P(pos) = 0.49)
highly recommend the python classes    -> pos  (P(pos) = 0.82)

With only 12 training reviews the model already gets clear cases right, but look at "not good at all": bag-of-words sees mostly unfamiliar words and the uncertain probability shows it. Real sentiment systems are trained on tens of thousands of reviews (for example the IMDB or Amazon reviews datasets on Kaggle) or use pre-trained language models.

Word embeddings - meaning as vectors#

Bag-of-words treats "good" and "great" as unrelated columns. Word embeddings (word2vec, GloVe, and the internal vectors of modern language models) represent each word as a dense vector of a few hundred numbers, learned so that words used in similar contexts get similar vectors.

Similarity is measured with cosine similarity - the cosine of the angle between two vectors:

cos(a, b) = (a · b) / (|a| · |b|)      1 = same direction, 0 = unrelated, -1 = opposite
▶ Try it YourselfPython
Ctrl + Enter to run
Output
king ~ queen : 0.891
king ~ python: 0.211
python ~ java: 0.999
king - man + woman ≈ queen

Embeddings power semantic search ("cheap phone with good camera" finds "budget smartphone, excellent photos"), recommendation, clustering of support tickets, and retrieval-augmented generation (RAG) with LLMs.

NLP tasks you will meet#

Task Example
Text classification spam, sentiment, topic, intent of a support message
Named-entity recognition (NER) find names, places, dates, amounts in text
Machine translation English ↔ Hindi, Tamil, Bengali...
Question answering answer from a document or the web
Summarisation shorten a long report
Speech-to-text / text-to-speech voice typing, IVR systems
Text generation chatbots, writing assistants (LLMs - next lesson)
Note

Indian languages add extra challenges: many scripts, rich word forms, code-mixing (Hinglish, Tanglish), and less digital training data. Government initiatives like Bhashini and open models trained on Indian languages are working on this.

Summary#

  • NLP pipeline: clean → tokenise → (stop words, lemmatise) → vectorise → model.
  • Bag-of-words counts words; TF-IDF weights distinctive words; both ignore word order.
  • Text classifiers = vectoriser + model (e.g. TF-IDF + logistic regression).
  • Embeddings place words with similar meaning close together; cosine similarity compares them.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Word frequencies without stop words

Lower-case the text, extract words with re.findall(r"[a-z]+", ...), remove the stop words given, and store the 3 most common remaining words as a list of (word, count) tuples in top3 (use collections.Counter.most_common). Print it.

2

Cosine similarity

Write cosine(a, b) for NumPy vectors and use it to find which word in vectors is most similar to "king" (excluding "king" itself). Store the word in best and print it.

Quick Quiz

Q1.

Tokenisation means...

Q2.

TF-IDF gives a high weight to a word that...

Q3.

What does cosine similarity between two word vectors measure?

Q4.

A weakness of bag-of-words is that it...