Introduction to Natural Language Processing (NLP)
Fardina Alam
CMSC - 320 Introduction to Data Science
2026
Today We will Cover
Natural Language Processing (NLP)
NLP is a branch of Artificial Intelligence that enables computers to understand, interpret, and generate human language.
Key Goals:
Why is NLP Important?Powers tools like Google Translate, Siri, Alexa, chatbots, and spam filters
Evolution: Rule-based → Statistical → Neural models (BERT, GPT).
Language Structure: Syntax vs. Semantics
How Language is Structured:
Syntax and Sematics:
There are rules that govern the order in which words can appear.
Syntax | Semantics |
Structure of language (grammar, word order). | Meaning of language (interpretation, context). |
Example: "The cat sat on the mat" (correct structure). | Example: "The chicken is ready to eat" (could mean it’s cooked or hungry). |
Used in parsing sentences (identifying subject-verb-object). | Used in sentiment analysis, intent detection. |
Example of Syntax vs. Semantics in NLP:
UNDERSTANDING LANGUAGE IS HARD
5
or
?
Challenges in NLP
NLP’s practical applications
Sentiment analysis: Determines if the tone of a text is positive or negative, handling ambiguity in sentiment and tone.
Topic modeling: Identifies the main topics of an article, overcoming challenges in word meaning and context variability.
What type of article is this?
Question Answering: Develops systems that can answer questions in any natural language, addressing ambiguity in phrasing and grammar.
Named Entity Resolution: Identifies people, places, or things in text, resolving ambiguity about what a phrase refers to.
Text Summarization: What it sounds like: Condensing a text to its essential points.
Pipeline of NLP
Text Acquisition (Data Collection)
Text Preprocessing
Advanced Preprocessing:
Text Preprocessing in NLP
Transform raw text into a clean, consistent, and structured format to prepare it for feature extraction and modeling.
English-Specific Challenges:
Challenges in Other Languages:
Tokenization is not straightforward!
Stemming or Lemmatization
Goal: Reduce inflected words to a common form so that they're counted as one.
Stemming: Remove affixes from a word to get base form (stem) of a word → stem might not be a lexicographically correct word.
Good for search engines and simple tasks. | Lemmatization: Find lemma (dictionary form) of a inflected word → a lemma is always a lexicographically correct word. Implemented for English in NLTK with WordNetLemmatizer.
Best for tasks where meaning and context are important, like text classification and sentiment analysis. |
Advanced: POS Tagging (Optional for many ML tasks)
Part-of-Speech (POS) tagging → annotate words with lexical categories
Goal: assign a lexical category such as noun, verb, adjective, etc. to each word, needed for lemmatization, helps machines understand grammatical structure.
Next: Feature Extraction: Turning texts into vectors
Convert text data into numerical representations (e.g. numerical vectors that represent text features like word frequencies or semantic meanings) that machine learning models can understand and use for tasks like sentiment analysis, classification, or translation.
Example:
"Hi. This is an example sentence in an Example Document." → [hi, example, sentence, document] → [1, 2, 1, 1]
Machine learning algorithms require numerical inputs for processing.
Feature Engineering / Feature Extraction
Also called as “Text Representation”
Raw Text Documents → Data Cleaning by Tokenization → Vectorization
(BoW/N-Grams/TF-IDF etc.)
Feature Extraction Techniques
Technique | Description | Use Case |
Bag of Words (BoW) | Counts word frequencies (ignores order). | Basic text classification. |
TF-IDF | Weights words by importance in a document. | Search engines, document similarity. |
Word Embeddings (Word2Vec, GloVe) | Represents words as vectors (captures meaning). | Advanced NLP tasks (chatbots, translation). |
N-grams | Groups of N consecutive words ("New York" is a bigram). | Improves context in language models. |
1. Bag of Words (BoW)
Converts text into word frequency vectors (ignores word order).
Limitation: Loses word order & context (e.g., "not good" vs. "good").
counts the frequency of words in a document disregarding grammar and word order.
BoW represent each document as a vector of word frequencies: Order of words does not matter, just #occurrences
Corpus: Consider, our textual data -
Next Step: Design the Vocabulary: make a list of all of the words in our model vocabulary.
The unique words here (ignoring case and punctuation)
Example: BoW or Unigram Approach
I | Like | School | Have | Homework | To | Do | Has | And |
I | Like | School | Have | Homework | To | Do | Has | And |
2 | 2 | 1 | | 1 | | | | 1 |
1 | | | 1 | 1 | 1 | 1 | | |
| | 1 | | 1 | | | 1 | |
| | 1 | | 1 | | | 1 | |
Final Step: Bow: Create Document Vectors: score the words in each document.
a fixed-length document representation of 9, with in each vector, the numbers represent the frequency of the corresponding word in the given sentence.
*Empty are 0
Pros and Cons: Bag of Words (BoW) or Unigram Approach:
Pros | Cons |
Simplicity: Easy to implement and understand. Computational Efficiency: Unigram representations result in sparse vectors that are computationally efficient to process and analyze, especially for large datasets. Language Independence: Applicable to any language. Capture Word Importance: Highlights individual important words (Words with higher frequencies). | Loss of Word Order: Ignores word sequence. Limited Context: Doesn't capture word relationships. Vocabulary Size: Can be large, leading to high-dimensional sparse vectors. This can pose challenges in terms of storage and computation. As such, there is pressure to decrease the size of the vocabulary when using a bag-of-words model. |
Limitation of BoW :
"I like school and I like homework"
"I have homework to do"
"School has homework"
"Homework has school"
I | Like | School | Have | Homework | To | Do | Has | And |
2 | 2 | 1 | | 1 | | | | 1 |
1 | | | 1 | 1 | 1 | 1 | | |
| | 1 | | 1 | | | 1 | |
| | 1 | | 1 | | | 1 | |
"School has homework" and "Homework has school" have the same unigram representation, despite having different meanings (Limited Context Understanding).
(2) N-Grams
A variation of Bag of Words that captures sequences of N adjacent words.
How it works: Instead of single words (unigrams), it considers pairs (bigrams) or triplets (trigrams) of words, capturing local word patterns.
A more sophisticated approach is to create a vocabulary of grouped words.
(2) Example: Bi-Grams
Creating a vocabulary of two-word pairs is, in turn, called a bigram model.
Examples:�"School has homework"
"Homework has school"
These are called 'bigrams'
School has | Has homework | Homework has | Has school |
1 | 1 | | |
| | 1 | 1 |
Note: only the bigrams that appear in the corpus are modeled, not all possible bigrams.
Next: TF-IDF
While N-grams help capture word sequences and local context, they still rely on raw frequency.
To understand, let's Try: Topic Modeling which is Just Supervised Learning!
Topic Modeling!
Assign a general topic to a set of documents (corpus) that best describes and fits the contents of those documents (based on the words present).
Key Challenge: While Bag of Words and N-Grams provide raw counts or frequencies of words, but lack of understanding the importance of each word (or N-gram) in the context of classification.
Example:
Thought Experiment: Classifying Documents with Just Two Words: Spaceship vs. Dragon
A Thought Experiment: Seeing if two books are on the same topic
Imagine books/documents made up of only two words: Spaceship or dragon.
The more occurences of "spaceship" it has, the more purely science fiction it is. The more occurences of "dragon" it is, the more fantasy.
Book/Document | Dragon | Spaceship |
Document A | 10 | 0 |
Document B | 20 | 0 |
Document C | 0 | 10 |
Document D | 0 | 20 |
Document E | 5 | 10 |
Document F | 15 | 15 |
What about this issue?
Let's include another common, non-stop word
Book/Document | Dragon | Spaceship | They |
Document A | 10 | 0 | 100 |
Document B | 20 | 0 | 110 |
Document C | 0 | 10 | 90 |
Document D | 0 | 20 | 80 |
Document E | 5 | 10 | 100 |
Document F | 15 | 15 | 80 |
(Term Frequency-Inverse Document Frequency)
Weights words by their importance in a document vs. entire corpus. TF-IDF tries to decrease the weight of words that occur across many documents → lower the weight of common words.
Measures how often a specific word (term) appears (frequency) in a single document.
Document Frequency (DF) = Measures in how many documents a word appears in the entire corpus.
DF(t)=Number of documents containing term
Example 1: TF-IDF
Example: In a Corpus, there are 2 (N=2) documents
TF-IDF for term "NLP":
Use Case: Search engines (ranks documents based on keyword relevance).
Example 2: TF-IDF
| Dragons | Spaceship | They |
Document Frequency (DF) | 3 | 3 | 6 |
Inverse Document frequency (IDF) | 0.176 | 0.176 | 0 |
| TF (Dragon) | TF(Spaceship) | TF (They) |
Document A | 10/30=0.33 | 0 | 20/30=0.67 |
Document B | 20/45=0.44 | 0 | 25/45=0.56 |
Document C | 0 | 10/40=0.25 | 30/40=0.75 |
Document D | 0 | 20/55=0.36 | 35/55=0/64 |
Document E | 5/35=0.14 | 10/35=0.29 | 20/35=0.57 |
Document F | 0.21 | 15/70=0.21 | 40/70=0.57 |
Table: DF & IDF values
Book/Document | Dragon | Spaceship | They |
Document A | 10 | 0 | 20 |
Document B | 20 | 0 | 25 |
Document C | 0 | 10 | 30 |
Document D | 0 | 20 | 35 |
Document E | 5 | 10 | 20 |
Document F | 15 | 15 | 40 |
New Example:
Example: Document A
Total words in A: 10(Dragon)+0(Spaceship)+20(They)=30. So:
Step 1: Calculate TF
Calculate TF for all other documents
Step 2: Calculate TF and IDF
log(6/4) =
log(6/4) =
Identify N
Documents: A, B, C, D, E, F → N=6
Example 2: TF-IDF
| Dragons | Spaceship | They |
Document Frequency (DF) | 3 | 3 | 6 |
Inverse Document frequency (IDF) | 0.176 | 0.176 | 0 |
| Dragon | Spaceship | They |
Document A | 0.33 × 0.176 = 0.058 | 0 | 0 |
Document B | 0.44* 0.176 = 0.007 | 0 | 0 |
Document C | 0 | 0.25* 0.176=0.044 | 0 |
Document D | 0 | 0.063 | 0 |
Document E | 0.025 | 0.051 | 0 |
Document F | 0.037 | 0.037 | 0 |
| TF (Dragon) | TF(Spaceship) | TF (They) |
Document A | 10/30=0.33 | 0 | 20/30=0.67 |
Document B | 20/45=0.44 | 0 | 25/45=0.56 |
Document C | 0 | 10/40=0.25 | 30/40=0.75 |
Document D | 0 | 20/55=0.36 | 35/55=0/64 |
Document E | 5/35=0.14 | 10/35=0.29 | 20/35=0.57 |
Document F | 0.21 | 15/70=0.21 | 40/70=0.57 |
Table: TF values
Table: DF & IDF values
Table: TF-IDF (TF * Log(N/Df) )
Example 3: TF - IDF Calculation
Document 1: read SVM algorithm article dataaspirant blog
Document 2: read randomforest algorithm article dataaspirant blog
These documents differ mainly in the algorithms they discuss: SVM for the first and random forest for the second. This distinction is clear in TF-IDF scores, where all other words score 0, while 'SVM' and 'randomforest' have non-zero values
Measure similarity between documents: Cosine Similarity
Cosine Similarity measures the angle between two vectors — the closer the angle to 0°, the more similar the texts are.
Example: Use Case: Finding Similar Documents or Plagiarism Detection
Emphasizes the direction, not the magnitude (total occurrences), of the vectors.
Output: A value between -1 (completely dissimilar) to 1 (completely similar):
A Thought Experiment: Seeing if two books are on the same topic
Once we compute TF-IDF scores, each document becomes a vector—a list of numbers representing how important each word or phrase is to that document. For example, a book might be represented as:
[0.8 (spaceship), 0.2 (dragon)]
A natural idea is to use distance to compare how similar or different two documents are.
A Thought Experiment: Seeing if two books are on the same topic
Looking at this graph, should we use Euclidean distance?
Example: Two books with similar occurrences of "spaceship" and "dragon" may appear close in Euclidean distance.
A Thought Experiment: Seeing if two books are on the same topic
Looking at this graph, should we use Euclidean distance?
For instance, using "dragon" 10 times versus 100 times is actually similar, but Euclidean distance might not reflect this accurately.
We need a new measure!!
Cosine Similarity
Books on similar topics will have smaller angles.
Back to Feature Extraction: TF-IDF vs. BoW vs. N-grams
Method | Pros | Cons |
Bag of Words (BoW) | Simple, fast. | Loses word order & context. |
TF-IDF | Weights important words. | Still ignores word order. |
N-grams | Captures word sequences. | Increases dimensionality. |
Another type: Word Embeddings (Word2Vec, GloVe) –
Dense vector representations of words that capture semantic meaning and relationships.
Advantage: Captures relationships (synonyms, analogies).
So far, we have seen some vectorization process with BoW, N-Grams, TF-IDF. We can choose appropriate vectorization and will apply to some NLP task (next topic).
Model Building
Train a machine learning model to perform tasks like:
Example: Text Classification & Sentiment Analysis
Text Classification: Assigning categories (e.g., spam detection).
Sentiment Analysis: Detecting emotions (positive/negative/neutral).
Algorithms Used:
Example: Sentiment Analysis Using TF-IDF and Logistic Regression
From Counting Words to Understanding Language
To go beyond static vectors, we turn to deep learning models that read text like humans do—sequentially and contextually:
The Evolution of Context-Aware Models
Evaluation & Deployment
Evaluation Metrics:
Deployment:
Basic Tools and Libraries
Example: Sentiment Analysis (SELF STUDY)
Example: Step by Step: Sentiment Analysis
Lexicon: Pre-defined word lists with:
Types
✅ POS Lexicon: great, love, perfect
❌ NEG Lexicon: bad, hate, terrible
Applications
Limitations
Most commonly used
Another one: TF-IDF : Simple ideas. Let’s: • disproportionately weight the common words that appear in many documents • Use that info and combine it with the word frequency info
Try: Bag-of-words (BoW)
Steps:
Step: Negation handling
The process of detecting and correctly interpreting the negation in a sentence—especially to avoid reversing or misclassifying the meaning. Negation flips the meaning of words:
Types of Negation:
How to Handle It:
Steps: Stemming/Lemmatization and Feature Extraction
Simplified: Rule-Based Sentiment Analysis Using Lexicons
Core Idea: A simple unsupervised method that calculates sentiment using predefined word sentiment scores.
Lexicon/Dictionary:� Predefined list of words with sentiment weights:
Weight Vector (w):� Vector of sentiment scores for each word�Document Vector (X):� Binary vector (1 = word present, 0 = absent) representing the text
How It Works:
Scoring: Score = ∑(Xⱼ × wⱼ) (dot product of document and weight vectors)
Prediction:
Example: X = [1, 0, 1, 0, 1, 0, 1, 1]
w = [0, 0, 0, 0, 1, 0, 1, 0]
ML based Based Sentiment Analysis
Collect Data: Labeled text (e.g., reviews, tweets)�
Preprocess Text: Clean, tokenize, remove stopwords, lemmatize�
Feature Extraction:Convert text to vectors (BoW, TF-IDF, embeddings)�
Split Data: Train/Test (e.g., 80/20)�
Train Model: Use ML classifiers (e.g., Logistic Regression, SVM, Naive Bayes)�
Evaluate: Accuracy, Precision, Recall, F1�
Predict: Apply model to new/unseen text
Input: Text (e.g., "This phone is amazing!")�
Label: Sentiment class (e.g., positive)�
Goal: Learn patterns that map input text to the correct label.
Rule Based: What Makes a Good Sentiment Lexicon?
The End