NLP Complete Notes
NLP Complete Notes
101 Ram 85
102 Shyam 90
Key Terms:
Record (Row) → One complete entry
Attribute (Column) → Feature/variable
Instance → Single data object
Types of Data
1. Structured Data
Organized in tables
Example: Excel, SQL tables
2. Unstructured Data
No predefined format
Example: Images, videos, text
3. Semi-Structured Data
Partially organized
Example: JSON, XML
Data Formats
1. CSV (Comma-Separated Values)
Definition
CSV (Comma-Separated Values) is a plain text file format used to store tabular
data.
Each row represents a record, and each value is separated by a comma.
Structure
Rows → Records
Columns → Attributes
Separator → Comma (,)
Example
Name Age Marks
Ram 20 85
Shyam 21 90
Explanation:
First row → Column names (Header)
Remaining rows → Data values
Characteristics
Stored as .csv file
Can be opened in:
Notepad
Excel
Python (Pandas)
Advantages
1. Lightweight
Very small file size
No extra formatting
2. Easy to Process
Supported by almost all programming languages
Easy to import/export
3. Human Readable
Can be understood easily by users
Limitations
1. No Hierarchy
Cannot store nested or complex data
Only flat structure
2. No Data Type Support
Everything is stored as text
Cannot distinguish numbers, dates, etc.
3. Limited Features
No formulas, charts, or formatting
Use Cases
Data exchange between systems
Machine learning datasets
Simple data storage
Structure
Data is stored in:
Objects { }
Arrays [ ]
Uses keys and values
Example
{
"Name": "Ram",
"Age": 20,
"Marks": 85
}
Nested Example
{
"Name": "Ram",
"Age": 20,
"Marks": {
"Math": 90,
"Science": 85
}
}
Here:
"Marks" contains another object → nested structure
Characteristics
Stored as .json
Used in web applications and APIs
Language-independent
Advantages
1. Flexible
Supports complex and nested data
Can represent real-world relationships
2. Widely Used in APIs
Used for data exchange between:
Server ↔ Client
Web apps ↔ Databases
3. Lightweight & Readable
Easier than XML
Human-readable format
Limitations
1. Slightly Complex
Harder than CSV for beginners
2. Larger Size than CSV
Due to keys and structure
3. Parsing Required
Needs a parser in programming languages
Use Cases
Web APIs
Configuration files
Mobile and web applications
📌Structure
Workbook → Entire file
Worksheet → Individual sheet
Cells → Intersection of rows and columns
Characteristics
File extensions:
.xls (older)
.xlsx (modern)
Developed by Microsoft Excel
✔ Features
1. Multiple Sheets
One file can contain many worksheets
2. Built-in Formulas
Examples:
SUM()
AVERAGE()
IF()
4. Data Formatting
Colors, fonts, borders
Conditional formatting
Limitations
1. Larger File Size
Compared to CSV
2. Not Ideal for Big Data
Slower with very large datasets
3. Requires Software
Needs Excel or similar tools
Use Cases
Business reports
Data analysis
Financial calculations
Student records
Comparison Table
Feature CSV JSON Excel
Final Summary
CSV → Simple, lightweight, best for basic data storage
JSON → Flexible, supports nested data, used in APIs
Excel → Powerful, user-friendly, used for analysis and reporting
Data Cleaning
Definition
Data Cleaning is the process of identifying and correcting errors, missing values,
duplicates, and inconsistencies in a dataset to improve its quality.
Importance
Improves accuracy of results
Ensures reliable analysis
Essential for Machine Learning models
Prevents wrong conclusions
Example
Name Age Marks
Ram 20 85
Shyam — 90
Riya 19 —
3. Forward/Backward Fill
[Link](method='ffill') # forward fill
[Link](method='bfill') # backward fill
Handling Duplicates
What are Duplicate Values?
Duplicate data means same records appearing more than once.
Example
Name Age Marks
Ram 20 85
Ram 20 85
Problems Caused
Biased analysis
Incorrect statistics
Increased data size
Remove duplicates:
df.drop_duplicates(inplace=True)
Types of Duplicates
Full duplicates → Entire row same
Partial duplicates → Some columns same
📌 Examples
Gender
Male
male
Causes
Human entry errors
Different formats
Multiple data sources
1. Standardization
Convert values into a standard format:
df['Gender'] = df['Gender'].[Link]()
2. Replace Values
df['Gender'].replace({'m': 'male', 'M': 'male'}, inplace=True)
3. Format Correction
Example: Date format
Convert all dates to one format
df['Date'] = pd.to_datetime(df['Date'])
4. Removing Noise
Remove unwanted characters
Fix spelling errors
Summary Table
Problem Type Solution Methods
Data Transformation
Definition
Data Transformation is the process of converting raw data into a clean,
structured, and suitable format for analysis, visualization, or machine learning.
It is a broad step in data preprocessing that includes multiple techniques.
2. Aggregation
Concept:
Combining multiple data points into a summary.
Example:
Daily temperature → Monthly average
Sales per day → Total monthly sales
3. Generalization
Concept:
Convert low-level data into higher-level concepts.
Example:
Age Category
22 Young
65 Senior
Used in:
Data mining
Decision making
Male 1
Female 0
Simple
Can create false relationships
1 0
0 1
No ranking issue
Increases number of columns
5. Feature Construction
Concept:
Create new attributes from existing data.
Example:
DOB → Age
Price + Quantity → Total Cost
Helps improve model performance
6. Discretization
Concept:
Convert continuous data into categories
Example:
Marks Grade
85 A
Marks Grade
65 B
Normalization
Definition
Normalization is the process of scaling numerical data into a specific range
without changing relationships between values.
Solution:
Normalize data → bring all values to same scale
Types of Normalization
Example:
Suppose you have exam scores: [40, 60, 80, 100]
Z-Score Normalization
Formula: z = (x - μ) / σ
Example:
3. Apply formula:
- z = (40-70)/22.36 ≈ -1.34
- z = (60-70)/22.36 ≈ -0.45
- z = (80-70)/22.36 ≈ 0.45
- z = (100-70)/22.36 ≈ 1.34
1. Find mean
2. Find standard deviation
3. Use formula: Z=(X−μ)/σ
4. Compute for each value
Components of a Table
Example Table
Scienc
Student Math Total
e
A 70 80 150
B 85 75 160
C 60 65 125
D 90 85 175
Advantages of Tables
Importance of Charts
Simplifies complex data
Shows trends and relationships
Makes comparison easy
Improves decision-making
TYPES OF CHARTS
1. Bar Chart
Description
Uses rectangular bars (vertical or horizontal) to represent data.
Example Use
Comparing marks of students.
Features
Equal width bars
Space between bars
Height represents value
2. Line Chart
Description
Data points connected by straight lines.
Example Use
Temperature changes over time.
Features
Shows trends
Useful for continuous data
3. Pie Chart
Description
Circular chart divided into sectors.
Example Use
Budget distribution.
Features
Total = 360°
Each slice represents percentage
4. Histogram
Description
Graph showing frequency distribution using bars.
Example Use
Marks distribution in a class.
Features
No gaps between bars
Used for continuous data
5. Scatter Plot
Description
Uses points to show relationship between two variables.
Example Use
Height vs Weight.
Features
Shows correlation
Helps in prediction
TABLE VS CHART
Feature Table Chart
Nature Numerical Visual
Data accuracy Exact Approximate
Trend visibility Low High
Ease of
Moderate Easy
understanding
Feature Table Chart
Detailed
Best use Summary & patterns
data
WHEN TO USE
Use Tables When:
Exact values are required
Data is large and detailed
Performing calculations
Use Charts When:
Showing trends or patterns
Comparing data visually
Presenting to audience
Data preprocessing
Data preprocessing is a crucial step in data analysis and machine learning. Using
NumPy and Pandas (two popular Python libraries), you can efficiently clean,
transform, and prepare data for modeling.
It includes:
Cleaning data
Handling missing values
Removing duplicates
Scaling/normalizing data
Transforming data
Libraries Used
import pandas as pd
import numpy as np
What is Pandas?
Pandas is a powerful, fast, and open-source library built on NumPy. It is used for data
manipulation and real-world data analysis in Python.
Loading Data in Pandas DataFrame
Reading CSV file using pd.read_csv and loading data into a data frame. Import
pandas as using pd for the shorthand. You can download the data from here.
#Importing pandas library
importpandasaspd
Load Dataset
df=pd.read_csv("[Link]")
Example:
If age column = [20, 25, NaN] → mean = 22.5
Result → [20, 25, 22.5]
Mapping:
Male → 0
Female → 1
Example:
["Male", "Female", "Male"] → [0, 1, 0]
import pandas as pd
data = {
"Name": ["A", "B", "C", "D", "E"],
"Age": [20, 25, None, 30, 35],
"Salary": [20000, 25000, 30000, None, 50000]
}
df = [Link](data)
print(df)
import pandas as pd
data = {
df = [Link](data)
df["Age"].fillna(df["Age"].mean(), inplace=True)
df["Salary"].fillna(df["Salary"].mean(), inplace=True)
print(df)
import pandas as pd
data = {
df = [Link](data)
df = [Link]()
print(df)
Removing Duplicates
import pandas as pd
data = {
df = [Link](data)
df = df.drop_duplicates()
print(df)
Data Filtering
import pandas as pd
data = {
df = [Link](data)
print(filtered)
Data Normalization
import pandas as pd
data = {
df = [Link](data)
print(df)
import pandas as pd
data = {
df = [Link](data)
print(df)
Common Functions:
import pandas as pd
df = pd.read_csv("[Link]")
What is NumPy?
import numpy as np
OUTPUT:
[10 20 30 40 50]
import numpy as np
mean = [Link](data)
data = [Link]([Link](data), mean, data)
print(data)
import numpy as np
🔹 . Standardization (Z-score)
import numpy as np
import numpy as np
9. Data Filtering
import numpy as np
[25 30]
🔹 . Sorting Data
import numpy as np
sorted_data = [Link](data)
print(sorted_data)
[10 20 30 40 50]
Purpose
1. Line Plot
A line plot connects data points using straight lines.
Use Case
[Link]
x= [1, 2, 3]
y= [4, 5, 6]
[Link](x, y)
[Link]("Line Graph")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
2. Bar Chart
Use Case
[Link]
[Link](categories, values)
[Link]("Bar Chart")
[Link]()
[Link] Chart
Use Case
Showing proportions
[Link]
[Link](data, labels=labels)
[Link]("Pie Chart")
[Link]()
4. Histogram
Use Case
[Link]
data= [1, 2, 2, 3, 3, 3]
[Link](data)
[Link]("Histogram")
[Link]()
5. Scatter Plot
Use Case
Finding correlation
[Link]
x= [1, 2, 3, 4]
y= [10, 20, 25, 30]
[Link](x, y)
[Link]("Scatter Plot")
[Link]()
Introduction
Language is a method of communication with the help of which we can speak, read and write. For example, we think,
we make decisions, plans and more in natural language; precisely, in words. However, the big question that confronts
us in this AI era is that can we communicate in a similar manner with computers. In other words, can human beings
communicate with computers in their natural language? It is a challenge for us to develop NLP applications because
computers need structured data, but human speech is unstructured and often ambiguous in nature.
Natural Language Processing (NLP) is the sub-field of Computer Science especially Artificial Intelligence (AI) that is
concerned about enabling computers to understand and process human language. Technically, the main task of NLP
would be to program computers for analyzing and processing huge amount of natural language datalike text and
speech—and extract meaningful information from it.
In other words ,we can say that Natural Language Processing (NLP) helps computers understand, interpret and
produce human language. It studies language as data and develops a model that can analyse linguistic structure,
meaning and context in both written and spoken communication.
Examples
1. Text Processing
2. Syntax Analysis
Parsing sentences
3. Semantic Analysis
Understanding meaning:
4. Pragmatics
Sarcasm detection
Intent recognition
Applications
Voice Assistants: Alexa, Siri and Google Assistant use NLP for voice recognition and interaction.
Grammar and Text Analysis: Tools like Grammarly, Microsoft Word and Google Docs apply NLP for grammar
checking.
Information Extraction: Search engines like Google and DuckDuckGo use NLP to extract relevant information.
Chatbots: Website bots and customer support chatbots leverage NLP for automated conversations.
Real-World Applications
Email filtering
Challenges in NLP
1. Ambiguity
2. Context Understanding
4. Multilingual Complexity
5. Data Issues
Advantages of NLP
Text preprocessing is the first and most crucial step in any Natural Language Processing pipeline. It transforms raw,
messy text into a clean and structured format that machines can understand.
Preprocessing improves:
Model accuracy
Training speed
Overall performance
1. Lowercasing
Example:
2. Tokenization
Types:
Sentence Tokenization
Word Tokenization
Example:
3. Stopword Removal
Examples of stopwords:
Example:
4. Stemming
Example:
playing → play
studies → study
5. Lemmatization
better → good
running → run
6. Removing Punctuation
Example:
7. Removing Numbers
Example:
@, #, $, %, &, *
Example:
"<p>Hello</p>" → "Hello"
Example:
😊 → "happy"
11. Normalization
Standardizing text:
Expanding contractions:
Correcting spelling
12. Part-of-Speech (POS) Filtering
Nouns
Verbs
Names
Places
Dates
Example:
Challenges in Preprocessing
Context-dependent words
Tokenization in NLP
Tokenization is one of the most fundamental steps in Natural Language Processing. It involves breaking down text
into smaller units called tokens, which can be words, sentences, or subwords.
What is Tokenization?
Tokenization is the process of splitting a text into meaningful pieces so that machines can process it.
Example:
Input:
"I love learning NLP!"
Output:
["I", "love", "learning", "NLP", "!"]
Types of Tokenization
1. Sentence Tokenization
Input:
"NLP is amazing. It is powerful."
Output:
["NLP is amazing.", "It is powerful."]
Used in:
Text summarization
Document analysis
2. Word Tokenization
Example:
3. Subword Tokenization
Example:
Useful for:
Rare words
4. Character Tokenization
Example:
Useful for:
Spelling correction
Low-resource languages
5. N-gram Tokenization
Types:
Used in:
Language modeling
Predictive text
Challenges in Tokenization
1. Ambiguity
2. Contractions
5. Compound Words
Importance of Tokenization
Stop word removal is a key step in text preprocessing within Natural Language Processing. It involves removing
commonly used words that carry little or no meaningful information for analysis.
Examples:
Example:
Original sentence:
Example:
Step-by-Step Example
Sentence:
Step 1: Tokenization
→ ["This", "is", "a", "simple", "example", "to", "understand", "stop", "word", "removal"]
✔ Reduces dimensionality
✔ Speeds up training
✔ Improves efficiency
Disadvantages / Limitations
Loss of Meaning
Example:
Stemming and Lemmatization are core text normalization techniques used in Natural Language Processing to reduce
words to their base or root form. This helps machines treat similar words as the same, improving efficiency and
accuracy.
What is Stemming?
Stemming is a simple technique that removes suffixes (and sometimes prefixes) from words to get the root form.
🔧 How it Works:
Examples:
Word Stem
playing play
Word Stem
studies studi
happiness happi
✔ Characteristics:
Fast
Simple
What is Lemmatization?
Lemmatization reduces words to their base or dictionary form (lemma) using vocabulary and grammar rules.
How it Works:
Considers:
o Context
Examples:
Word Lemma
running run
better good
studies study
✔ Characteristics:
More accurate
Step-by-Step Example
Sentence:
After Stemming:
After Lemmatization:
✔ Notice:
“children” → “child”
“are” → “be”
“faster” → “fast”
Speed is important
Accuracy is important
Meaning matters
Challenges
1. Over-Stemming
2. Under-Stemming
Doesn’t reduce enough
Word frequency and basic text analysis are foundational techniques in Natural Language Processing used to
understand patterns, importance, and structure in text data.
Word Frequency
Word frequency refers to how often each word appears in a text or corpus.
Example:
Text: “India is a great country. India has diversity.”
Word Frequency
India 2
is 1
a 1
great 1
country 1
has 1
diversity 1
2. Relative Frequency
3. Normalized Frequency
It helps identify:
Important words
Common themes
Keywords in documents
Example:
Term Frequency (TF) refers to how often a particular word (term) appears in a document compared to
the total number of words in that document.
In simple words:
It tells you which words are important in a text based on how frequently they occur.
Formula
TF(t)=Number of times term t appears/Total number of terms in the document
Example
Text:
"Education is important. Education builds society."
Total words = 6
Education = 2
Search engines
AI & NLP
Convert to lowercase
Remove punctuation (.,!?)
Remove extra spaces
3. Tokenization
Example:
“India is diverse” → [India, is, diverse]
4. Stop Word Removal
6. Interpretation
Find:
o Most frequent words
o Themes
o Patterns
Step 2: Tokenize
india 2
diverse 1
country 1
rich 1
culture 1
Applications
Research & surveys
News analysis
Social media trends
Artificial Intelligence (NLP)
Academic assignments
Key Terms
Corpus → collection of texts
Token → individual word
Stop Words → common words removed
Frequency Distribution → table of word counts
1. Frequency Distribution
2. Word Cloud
3. Keyword Extraction
4. N-gram Analysis
Example:
Type Output
Determines emotion:
o Positive
o Negative
o Neutral
Number of:
o Words
o Sentences
o Characters
Developed By
Developed by researchers at the University of Pennsylvania
Widely used in education, research, and AI projects
1. Install NLTK
2. Import NLTK
import nltk
import nltk
[Link]('punkt')
[Link]('stopwords')
[Link]('wordnet')
[Link]('averaged_perceptron_tagger')
[Link]('maxent_ne_chunker')
[Link]('words')
Tokenization
Word Tokenization
import nltk
from [Link] import word_tokenize
words = word_tokenize(text)
print(words)
Output
1. Import NLTK
import nltk
Explanation
2. Import word_tokenize
Explanation
3. Store Text
Explanation
4. Tokenize Text
words = word_tokenize(text)
Explanation
Input:
Output:
Notice:
5. Print Result
print(words)
Explanation
Output
stemmer = PorterStemmer()
Output
play
play
play
1. Import PorterStemmer
Explanation
stemmer = PorterStemmer()
Explanation
Explanation
Explanation
Loops through each word one by one.
Iteration process:
1. playing
2. plays
3. played
5. Apply Stemming
print([Link](word))
Explanation
Lemmatization
lemmatizer = WordNetLemmatizer()
Output
running
better
car
1. Import WordNetLemmatizer
Explanation
lemmatizer = WordNetLemmatizer()
Explanation
Explanation
Explanation
Iteration order:
1. running
2. better
3. cars
5. Apply Lemmatization
print([Link](word))
Explanation
Step-by-Step Working
First Iteration
[Link]("running")
Output
running
tags = pos_tag(words)
print(tags)
Output
[('Python', 'NNP'),
('is', 'VBZ'),
('a', 'DT'),
('powerful', 'JJ'),
('language', 'NN')]
1. Import word_tokenize
Explanation
2. Import pos_tag
Explanation
3. Store Sentence
Explanation
4. Tokenize Sentence
words = word_tokenize(text)
Explanation
Output
Explanation
6. Print Result
print(tags)
Explanation
Output
[
('Python', 'NNP'),
('is', 'VBZ'),
('a', 'DT'),
('powerful', 'JJ'),
('language', 'NN')
]
is VBZ Verb
a DT Determiner
powerful JJ Adjective
language NN Noun
import nltk
from [Link] import word_tokenize
from nltk import pos_tag, ne_chunk
words = word_tokenize(text)
tags = pos_tag(words)
entities = ne_chunk(tags)
print(entities)
Output
(S
(PERSON Sachin/NNP Tendulkar/NNP)
lives/VBZ
in/IN
(GPE India/NNP))
1. Import NLTK
import nltk
Explanation
2. Import word_tokenize
Explanation
Explanation
4. Store Sentence
Explanation
5. Tokenization
words = word_tokenize(text)
Explanation
6. POS Tagging
tags = pos_tag(words)
Explanation
Output
[
('Sachin', 'NNP'),
('Tendulkar', 'NNP'),
('lives', 'VBZ'),
('in', 'IN'),
('India', 'NNP')
]
Tag Meaning
VBZ Verb
IN Preposition
GPE Country/city/location
Text representation techniques are methods used in Natural Language Processing to convert text into numerical
form so machines can understand and process it
Example:
“I love AI” → {I:1, love:1, AI:1}
Example:
Sentence: “I love AI and I love coding”
BoW representation counts each word:
Word Count
I 2
love 2
AI 1
and 1
coding 1
Example:
Lowercasing
Removing punctuation
Tokenization
Vocabulary:
[I, love, AI, is, powerful]
Doc1 1 1 1 0 0
Doc2 0 0 1 1 1
Each row is a feature vector.
• Binary BoW
Example:
“AI is AI” → [AI:1, is:1]
• Count-Based BoW
Instead of just marking whether a word exists (like binary BoW), count-based BoW records the exact frequency of
each word.
In simple terms:
“How many times does each word occur?”
Step-by-Step Example
Given Documents:
Doc1 22 2 1 0 0
Doc2 00 1 0 1 1
Normalized BoW
Normalized BoW is an improved version of the Bag of Words model in Natural Language Processing where word
counts are scaled (normalized) instead of using raw frequencies.
🔸 1. Why Normalization is Needed
In count-based BoW, longer documents naturally have higher word counts, which can bias the model.
Example:
Doc2: 10 words
Even if both talk about the same topic, Doc1 will have much larger counts.
3. Example
Documents:
Step 1: Vocabulary
Doc1 22 2 1 0 0 7
Doc2 00 1 0 1 1 3
Step 3: Normalize
4. Key Characteristics
✔ Values range between 0 and 1
✔ Represents relative importance of words
✔ Reduces bias due to document length
5. Advantages
6. Disadvantages
Still ignores:
Word order
Context/meaning
2. Components of TF-IDF
TF-IDF Formula
TF-IDF=TF×IDF
Step-by-Step Example
Documents:
Step 1: Vocabulary
Step 2: Compute TF
I 1/3 0
love 1/3 0
AI 1/3 1/3
is 0 1/3
powerful 0 1/3
Total documents = 2
I 1 log(2/1)
love 1 log(2/1)
AI 2 log(2/2) = 0
is 1 log(2/1)
powerful 1 log(2/1)
2. Example
Vocabulary:
Assign index:
I→0
love → 1
AI → 2
coding → 3
One-Hot Representation:
Word Vector
I [1, 0, 0, 0]
love [0, 1, 0, 0]
AI [0, 0, 1, 0]
coding [0, 0, 0, 1]
3. Sentence Representation
I → [1,0,0,0]
love → [0,1,0,0]
AI → [0,0,1,0]
6. Advantages
Basic ML models
Small datasets
7. Disadvantages
No Semantic Meaning
Curse of Dimensionality
No Context Awareness
Memory Inefficient
Character Embeddings
Character embeddings are a text representation technique in Natural Language Processing where individual
characters (letters, digits, symbols) are converted into numerical vectors instead of whole words.
1. Core Idea
Word-level:
“I love AI” → [“I”, “love”, “AI”]
Character-level:
“I love AI” → [‘I’, ‘ ’, ‘l’, ‘o’, ‘v’, ‘e’, ‘ ’, ‘A’, ‘I’]
2. How It Works
Example:
[a, b, c, ..., z, A, B, ..., 0–9, punctuation, space]
Example:
a→0
b→1
…
z → 25
Step 3: Represent Characters
One-Hot Encoding
Example:
‘a’ → [1,0,0,...]
‘b’ → [0,1,0,...]
3. Example
Word: “cat”
Character representation:
c → [0,0,1,...]
a → [1,0,0,...]
t → [0,0,0,...,1]
Introduction
Feature extraction from text data is the process of converting unstructured text into numerical features so
that machine learning models can understand and process it. Since algorithms cannot directly interpret text,
this step is essential in Natural Language Processing (NLP) tasks such as sentiment analysis, spam
detection, and text classification.
Text data:
Text Preprocessing
Input Sentence:
Tokenization
→ [“I”, “am”, “loving”, “the”, “Machine”, “Learning”, “course”]
Lowercasing
→ [“i”, “am”, “loving”, “the”, “machine”, “learning”, “course”]
Stopword Removal
→ [“loving”, “machine”, “learning”, “course”]
Stemming/Lemmatization
→ [“love”, “machine”, “learning”, “course”]
Concept:
Example:
Documents:
Vocabulary:
[I, love, AI, ML]
Vectors:
D1 → [1, 1, 1, 0]
D2 → [1, 1, 0, 1]
Key Point:
2 N-grams
Concept:
Example:
Use Case:
Concept:
Example:
Documents:
Word2Vec
Concept:
Example:
Relationship:
king − man + woman ≈ queen
Insight:
Concept:
Example:
BERT
Concept:
Example:
“bank” in:
o “river bank” → land
o “bank account” → financial
Text classification in NLP is the automated process of assigning predefined categories or tags to
unstructured text, such as sentiment analysis, topic labeling, and spam detection. It transforms raw text into
structured information using machine learning, allowing for efficient content analysis and organization at
scale
For example, an email can be classified as spam or not spam, or a product review can be classified as
positive or negative.
2. Multi-class Classification
Here, text is classified into more than two categories, but each text belongs to only one class.
Example:
3. Multi-label Classification
4. Hierarchical Classification
2. Feature Extraction
Computers cannot understand text directly, so it must be converted into numerical form.
Example:
“I love AI” → counts of each word
🔹 TF-IDF
🔹 Word Embeddings
These are dense vector representations of words that capture semantic meaning.
Words with similar meanings have similar vectors.
Example: “king” and “queen” are closely related in vector space.
🔹 Contextual Embeddings
3. Model Building
🔹 Traditional Models
🔹 Transformer Models
Modern models like BERT use attention mechanisms to understand full context of sentences.
They provide very high accuracy and are widely used today.
The model learns by minimizing error using techniques like gradient descent.
5. Evaluation Metrics
To measure performance:
Applications
Text classification is widely used in real life:
Challenges
Ambiguity: Same word has multiple meanings
Sarcasm: Difficult for machines to detect
Imbalanced Data: Some classes have more data than others
Domain Dependency: Model trained in one domain may not work well in another
Stemmer
A stemmer in Natural Language Processing (NLP) is a tool used to reduce words to their root or base form (called a
“stem”).
A stemmer removes suffixes (and sometimes prefixes) from words so that different forms of a word are treated as
the same.
Examples:
Why it is used
Text normalization
ps = PorterStemmer()
Output:
Morphological Analyzer
A morphological analyzer in Natural Language Processing (NLP) is a tool that analyzes the internal structure of
words and breaks them into meaningful components like root (stem), prefixes, suffixes, and grammatical features.
What it does
Instead of just cutting words like a stemmer, a morphological analyzer gives detailed linguistic information.
Example:
unhappiness →
un + happy + ness
(prefix + root + suffix)
running →
root: run
tense: present participle
🔹 Key Functions
🔹 Types of Morphology
1. Inflectional Morphology
2. Derivational Morphology
o happy → happiness
Applications
Machine Translation
Spell Checking
Information Retrieval
Speech Recognition
Chatbots
Sentiment Analysis
Sentiment Analysis in Natural Language Processing (NLP) is the process of determining the emotional tone or
opinion expressed in text.
🔹 What it does
1. Polarity-based
2. Emotion-based
3. Aspect-based
Applications
Customer feedback
Chatbots
Market research
Named Entity Recognition in Natural Language Processing (NLP) is the task of identifying and classifying important
entities in text into predefined categories.
Example
Sentence:
“Virat Kohli plays for Royal Challengers Bangalore in Bangalore.”
NER Output:
Person
Location
Organization
Money
Percentage
Applications
Information extraction
Chatbots
Search engines
Resume parsing
News analysis
. Text Similarity
Text similarity in Natural Language Processing (NLP) measures how similar two pieces of text are.
🔹 Example
Example methods:
o Cosine Similarity
o Jaccard Similarity
🔹 Applications
Plagiarism detection
Search engines
Chatbots
Document clustering
👉 Example:
Text: “Machine learning is widely used in data science and artificial intelligence.”
Keywords:
machine learning
data science
artificial intelligence
🔹 3. Types of Keywords
IDF (Inverse Document Frequency) → how rare the word is across documents
🔸 (D) TextRank
Graph-based algorithm
o BERT
o Word embeddings
1. Text Preprocessing
o Lowercasing
o Removing punctuation
o Removing stopwords
2. Tokenization
3. Scoring
4. Ranking
Applications
🔍 Search engines
📄 Document summarization
📊 Topic modeling
🛒 Product tagging
🔹 8. Advantages
Useful in automation
🔹 9. Limitations
Model deployment in Natural Language Processing (NLP) means making a trained NLP model available for real-world
use.
After training and testing the model, deployment allows users or applications to interact with it and get predictions
automatically.
For example:
The trained model is deployed on a server, cloud platform, website, or mobile app so it can process new text data in
real time.
1. Data Collection
2. Data Preprocessing
3. Feature Extraction
4. Model Training
5. Model Evaluation
6. Model Deployment
Deployment is the final stage where the model becomes usable by end users.
Automate predictions
Python libraries:
Websites
Mobile apps
Chatbots
Tool Purpose
Docker Containerization
Google Cloud
Microsoft Azure
Heroku
Train Model
↓
Save Model
↓
Create API
↓
Deploy on Server/Cloud
↓
Users Send Requests
↓
Model Returns Predictions
We use joblib
What is Joblib?
Scikit-learn
NLP models
Instead of retraining:
1. Train once
Installing Joblib
Importing Joblib
Function Purpose
mport libraries and models sklearn is the library called Scikit-learn used for
Machine Learning. feature_extraction.text
m sklearn.feature_extraction.text import CountVectorizer
contains tools for processing text.
m sklearn.naive_bayes import MultinomialNB
CountVectorizer converts text into numbers so the
m joblib import dump
machine learning model can understand it.
onvert text into numerical vectors Creates labels for each sentence.
torizer = CountVectorizer()
Labels are the correct answers for training.
vectorizer.fit_transform(texts) These sentences will teach the model positive and
negative sentiment.
ain model
Data inside list
del = MultinomialNB()
Sentence Meaning
[Link](X, labels)
I love NLP Positive
ave model
I hate bugs Negative
mp(model, "sentiment_model.joblib")
ave vectorizer Sentence Meaning
mp(vectorizer, "[Link]")
Python is amazing Positive
nt("Model Saved Successfully") This is bad Negative
Build vocabulary
It performs 2 tasks:
1. fit()
Vocabulary becomes:
Word Index
love 0
nlp 1
hate 2
bugs 3
python 4
amazing 5
bad 6
2. transform()
Sentence Vector
# Train model
2. Input:
X → numerical vectors
Example Learning
love Positive
amazing Positive
hate Negative
bad Negative
Save Model
Text Data
↓
CountVectorizer
↓
Numerical Vectors
↓
Naive Bayes Model
↓
Training
↓
Save Model using Joblib
important Terms
Term Meaning
Program
# Load model
model = load("sentiment_model.joblib") #Loads trained model from disk.
# Load vectorizer
vectorizer = load("[Link]") # Loads saved vocabulary.
# New text
text = ["I love Python"]
# Convert text
X = [Link](text) # Converts new text into numerical form.
# Prediction
prediction = [Link](X) # Model predicts sentiment.
print(prediction)
Output
['Positive']
Frontend
NLP model
We use:
Flask
Build APIs
Create web applications
Required Libraries
from flask import Flask, request, jsonify Imports important things from Flask.
from joblib import load
Item Purpose
# Create Flask app Flask Creates web application
app = Flask(__name__)
request Gets data sent by user
# Load model and vectorizer
jsonify Converts Python data into JSON response
model = load("sentiment_model.joblib")
vectorizer = load("[Link]")
configure application
# Return result
return jsonify({ API Route
"prediction": prediction[0]
@[Link]("/predict", methods=["POST"])
})
Explanation
# Run application
if __name__ == "__main__": Creates API endpoint.
[Link](debug=True) Route
/predict
methods=["POST"]
Means:
only POST requests are allowed
def predict():
# Return result
API response:
{
"prediction": "Positive"
}
API response:
{
"prediction": "Positive"
}
if __name__ == "__main__":
Explanation
Checks:
If yes:
[Link](debug=True)
Output
Running on [Link]
[Link]
Platform Purpose
Enter text
Click button
View prediction
<!DOCTYPE html>
<html>
<head>
<title>Sentiment Analysis</title>
</head>
<body>
<h1>Sentiment Analysis</h1>
<button type="submit">Predict</button>
</form>
</body>
</html>
output
Flask Backend with HTML
Program
from flask import Flask, render_template, request Imports important things from Flask.
from joblib import load
Item Purpose
app = Flask(__name__) Flask Creates web application
Purpose:
@[Link]("/predict", methods=["POST"])
def predict(): loads saved model files
text = [Link]["text"]
Imports load() function from Joblib.
X = [Link]([text])
Purpose:
methods=["POST"]
Means:
Folder Structure
project/
│
├── [Link]
├── sentiment_model.joblib
├── [Link]
│
└── templates/
└── [Link]
User Interaction
User opens:
[Link]
Meaning
Part Meaning
/ Home page
Enters:
I love python
Model predicts:
Positive
What is Scikit-learn?
Machine Learning
Data Analysis
Predictive Modeling
Classification
Regression
Clustering
Data preprocessing
Model evaluation
Make predictions
Example:
Recognize faces
Program 1
text = [
"I love NLP",
"I love Python"
]
vectorizer = CountVectorizer()
result = vectorizer.fit_transform(text)
print(vectorizer.get_feature_names_out())
print([Link]())
OUTPUT
This program uses Scikit-learn CountVectorizer to convert text into numerical form using the Bag of Words (BoW)
technique.
Code Explanation
It is used to:
text = [
"I love NLP",
"I love Python"
]
Document 1:
I love NLP
Document 2:
I love Python
vectorizer = CountVectorizer()
Tokenizes words
result = vectorizer.fit_transform(text)
1. fit()
Vocabulary:
love
nlp
python
2. transform()
print(vectorizer.get_feature_names_out())
Output
print([Link]())
Output
[[1 1 0]
[1 0 1]]
Index Word
0 love
1 nlp
2 python
1 1 0
Vector:
[1 1 0]
1 0 1
Vector:
[1 0 1]
Final Output
[[1 1 0]
[1 0 1]]
Program 2
text = [
vectorizer = TfidfVectorizer()
result = vectorizer.fit_transform(text)
print(vectorizer.get_feature_names_out())
print([Link]())
Output
Explatation
This program uses Scikit-learn TfidfVectorizer to convert text into numerical values using the TF-IDF technique.
TF-IDF means:
TF-IDF=TF×IDF
It measures:
1. Import Library
Imports TfidfVectorizer.
Used for:
Text representation
Feature extraction
NLP preprocessing
text = [
"I love NLP",
"I love Python"
]
Document 1
I love NLP
Document 2
I love Python
Functions:
Removes punctuation
result = vectorizer.fit_transform(text)
fit()
Vocabulary becomes:
love
nlp
python
transform()
print(vectorizer.get_feature_names_out())
Output
print([Link]())
Output
Approximate output:
[[0.57973867 0.81480247 0. ]
[0.57973867 0. 0.81480247]]
Vocabulary:
Index Word
0 love
1 nlp
2 python
TF-IDF Meaning
Word: "love"
Word: "nlp"
Higher importance.
Word: "python"
Higher importance.
Document Representation
0.57 0.81 0
Vector:
[0.57, 0.81, 0]
0.57 0 0.81
Vector:
[0.57, 0, 0.81]
Program 3
import numpy as np
encoder = OneHotEncoder()
result = encoder.fit_transform(data)
print([Link]())
Output
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
This program uses Scikit-learn OneHotEncoder to convert categorical text data into numerical format.
Machine learning models cannot understand text directly, so categories are converted into binary vectors.
1. Import Libraries
Imports OneHotEncoder.
Used for:
Data preprocessing
import numpy as np
Imports NumPy.
Used for:
Arrays
Numerical operations
2. Create Data
Animal
cat
dog
fish
Rows = samples
Columns = features
Shape of data:
(3,1)
Meaning:
3 rows
1 column
encoder = OneHotEncoder()
Purpose:
result = encoder.fit_transform(data)
Categories found:
cat
dog
fish
transform()
cat 1 0 0
dog 0 1 0
fish 0 0 1
Others are 0.
5. Print Result
print([Link]())
Final Output
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Output Explanation
cat
[1 0 0]
Meaning:
cat = Yes
dog = No
fish = No
dog
[0 1 0]
Meaning:
cat = No
dog = Yes
fish = No
fish
[0 0 1]
Meaning:
cat = No
dog = No
fish = Yes
spaCy
spaCy is an open-source Python library used for Natural Language Processing (NLP).
It is designed for fast, efficient, and real-world text processing.
Features of spaCy
Tokenization
Part-of-Speech Tagging
Lemmatization
Text Similarity
1. Install spaCy
Tokenization
Program
import spacy
nlp = [Link]("en_core_web_sm")
doc = nlp(text)
Output
I
love
learning
NLP
using
spaCy
.
Explanation:
import spacy
Explanation
nlp = [Link]("en_core_web_sm")
Explanation
Vocabulary
Grammar rules
Tokenizer
POS tagger
Meaning of Name
Part Meaning
en English language
sm Small model
Explanation
doc = nlp(text)
Explanation
It performs:
Tokenization
POS tagging
Parsing
NER
Lemmatization
Explanation
Tokens in sentence:
Token
love
learning
NLP
using
spaCy
print([Link])
Explanation
Output
I
love
learning
NLP
using
spaCy
.
Program
import spacy
nlp = [Link]("en_core_web_sm")
doc = nlp(text)
for token in doc:
print([Link], " --> ", token.pos_)
Output
a DET Determiner
spaCy vs NLTK
Feature spaCy NLTK
Program
import spacy
nlp = [Link]("en_core_web_sm")
doc = nlp(text)
for ent in [Link]:
print([Link], " --> ", ent.label_)
Output
Explanation
Entities detected:
India GPE
Google ORG
Explanation
Part Meaning
Output
Meaning of Labels
Label Meaning
ORG Organization/company
6. Lemmatization
Program
import spacy
nlp = [Link]("en_core_web_sm")
doc = nlp(text)
Output
Program
import spacy
nlp = [Link]("en_core_web_sm")
doc = nlp(text)
Output
simple
example
stop
word
removal
This
is
of
10Text Similarity
Program
import spacy
nlp = [Link]("en_core_web_sm")
print([Link](doc2))
Example Output
0.89