Natural Language Processing – Sentiment Analysis & Sequence-to-Sequence Models
Part 1 – Sentiment Analysis
1. Introduction & Importance
Definition: Automatic decoding of emotions/opinions in text; classifies tone as positive, negative, neutral
Key use-cases
Customer-feedback mining (e.g., Twitter airline dataset)
Brand-reputation monitoring & marketing strategy
Social-media listening in politics/governance
Internal product reviews; large enterprises (IBM, etc.)
Business value: Data-driven decisions, proactive reputation management
2. How Does It Work?
Parses words + context; derives polarity via:
Keyword sentiment lexicons
Negation/modifier handling
Context windows for sarcasm or intensifiers
Example: “Wow! The superhero movie was mind-blowing!” → classified positive
3. Hands-On Build (Twitter Airline Dataset)
Dataset: Kaggle – labelled tweets (positive / neutral / negative)
High-level workflow
Read labelled text
Feature-extract (BoW, TF-IDF, or embeddings)
Train classifier (Naïve Bayes, SVM, etc.)
Evaluate using confusion-matrix, accuracy, precision, recall
Feature-Extraction Options
BoW: sparse frequency vector
TF-IDF: weighting – emphasise discriminative terms
Embeddings: Dense semantic vectors (Word2Vec, GloVe, FastText, contextual BERT)
Model-Training Paths
Classical ML (NB / SVM / Logistic Regression)
Fine-tuning large pre-trained language models (BERT, XLNet, Doc2Vec) for higher accuracy
4. Typical Challenges & Mitigations
Class imbalance → oversampling, SMOTE, weighted loss
Noisy text (slang, misspellings, emojis) → robust pre-processing, normalization, emoji-mapping
Contextual nuance (sarcasm, irony) → transformer-based contextual models + attention
Domain generalization → diverse corpora, transfer-learning & domain adaptation
5. Key Take-Aways
Pre-processing + feature choice critically affect downstream accuracy
Continuous evaluation guides model reliability before deployment
Keep exploring state-of-the-art transformers for competitive edge
Part 2 – Sequence-to-Sequence (Seq2Seq) Modelling
1. Motivation
Many tasks need mapping one sequence → another instead of single label
Examples: machine translation, summarization, chatbot response, captioning, speech-to-text
Standard DNNs process IID inputs; fail to capture order-dependence
2. Sequences in the Real World
Natural language sentences (ordered tokens)
Time-series (stock prices)
Musical notes, video frames, sensor data
3. Baseline: RNNs & Their Limitations
RNN retains hidden-state ; theoretically handles arbitrary length
Problems: Vanishing / exploding gradients, slow sequential computation, poor long-term memory
3.1 LSTM – Long Short-Term Memory
Adds memory-cell with gates
Forget gate
Input gate
Candidate memory
Cell update
Output gate
Hidden state
Selective remembering/forgetting combats vanishing gradient
3.2 GRU – Gated Recurrent Unit
Simpler (no explicit cell state)
Reset gate , Update gate
Faster training, fewer parameters; often comparable accuracy
4. From RNNs to Full Seq2Seq
Encoder–Decoder paradigm
Encoder ingests input sequence → fixed-length context vector ((h,c))
Decoder generates output sequence token-by-token using that context
Supports variable-length input and output
Types of mapping
One-to-one (image → label)
One-to-many (image → caption)
Many-to-one (sentence → sentiment)
Many-to-many (translation, video classification)
5. Input/Output Preparation
Add tokens: /, /
Pad inputs to uniform length with
During training create (encoderinput, decoderinput, decoder_target) triples
Example (EN→FR):
Encoder input: “Nice ▪ to ▪ meet ▪ you …”
Decoder input: “ ▪ Ravi ▪ de ▪ vous ▪ rencontrer”
Decoder target: “Ravi ▪ de ▪ vous ▪ rencontrer ▪ ”
6. Training Mechanics
Teacher forcing
At each decoder timestep use the ground-truth token from previous step as input
Loss:
Faster convergence; mitigates error-propagation early in training
Testing phase
Previous predicted token fed back (autoregressive generation)
Stop when emitted or max length reached
Encoder behavior (train vs test)
Operates identically; parameters shared
Decoder differences
Train: ground-truth prev token → faster learning
Test: predicted prev token → may accumulate error if model under-trained
7. Enhancements for Performance & Accuracy
Bidirectional encoder LSTM/GRU (capturing both past & future context)
Attention mechanism – dynamically weights encoder hidden-states; upcoming topic
Replace LSTM with Autoencoders for latent representation learning
Bayesian hyper-parameter optimization (learning rate, hidden size, #layers)
8. Computational & Interpretability Limitations
Vanishing/exploding gradients (still possible for very long seq) → gradient clipping, GRU, residuals
Compute cost: sequential nature limits GPU parallelism; long seqs slow
Architecture selection/tuning non-trivial; many variants
Black-box predictions; difficult to justify decisions → attention visualisation, LIME/SHAP
Part 3 – Research Highlight
“Deep Visual-Semantic Alignments for Generating Image Descriptions”
Joint CNN (image) + RNN (language) alignment to caption images
Demonstrates Encoder–Decoder across modalities (vision → text)
Consolidated Class Summary
Sentiment Classification categorizes text into polarity classes; key for customer insight.
LSTM & GRU alleviate RNN gradient issues, preserving long-term dependencies.
Seq2Seq with encoder–decoder (built from LSTM/GRU) handles tasks where both input & output are sequences.
Machine translation epitomizes Seq2Seq need; same framework extends to summarization, chatbots, speech recognition, etc.
Encoder compresses, Decoder decompresses; attention and bi-directionality further boost performance.
Practical Checklist for Learners
[ ] Finish pre-class videos before every Sunday
[ ] Attempt all assignments, MCQs → attend Thursday reviews
[ ] Join Discord discussions & raise support tickets when stuck
[ ] Review LSTM/GRU equations; implement tiny Seq2Seq for toy translation
[ ] Experiment with attention & transformers as next step