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

    1. Read labelled text

    2. Feature-extract (BoW, TF-IDF, or embeddings)

    3. Train classifier (Naïve Bayes, SVM, etc.)

    4. Evaluate using confusion-matrix, accuracy, precision, recall

Feature-Extraction Options

  • BoW: sparse frequency vector

  • TF-IDF: tf!×!idftf!\times!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 hth_t; 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 ctc_t with gates

    • Forget gate f<em>t=σ(W</em>f [h<em>t−1,x</em>t]+bf)f<em>t = \sigma(W</em>f\,[h<em>{t-1},x</em>t]+b_f)

    • Input gate i<em>t=σ(W</em>i [h<em>t−1,x</em>t]+bi)i<em>t = \sigma(W</em>i\,[h<em>{t-1},x</em>t]+b_i)

    • Candidate memory c~<em>t=tanh⁡(W</em>c [h<em>t−1,x</em>t]+bc)\tilde c<em>t = \tanh(W</em>c\,[h<em>{t-1},x</em>t]+b_c)

    • Cell update c<em>t=f</em>t⊙c<em>t−1+i</em>t⊙c~tc<em>t = f</em>t \odot c<em>{t-1} + i</em>t \odot \tilde c_t

    • Output gate o<em>t=σ(W</em>o [h<em>t−1,x</em>t]+bo)o<em>t = \sigma(W</em>o\,[h<em>{t-1},x</em>t]+b_o)

    • Hidden state h<em>t=o</em>t⊙tanh⁡(ct)h<em>t = o</em>t \odot \tanh(c_t)

  • Selective remembering/forgetting combats vanishing gradient

3.2 GRU – Gated Recurrent Unit
  • Simpler (no explicit cell state)

    • Reset gate r<em>tr<em>t, Update gate z</em>tz</em>t

    • 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: L=−∑<em>t=1Tlog⁡P(y</em>t∣y<t,x)\mathcal L= - \sum<em>{t=1}^{T} \log P(y</em>t\mid y_{<t},x)

    • 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

  1. Sentiment Classification categorizes text into polarity classes; key for customer insight.

  2. LSTM & GRU alleviate RNN gradient issues, preserving long-term dependencies.

  3. Seq2Seq with encoder–decoder (built from LSTM/GRU) handles tasks where both input & output are sequences.

  4. Machine translation epitomizes Seq2Seq need; same framework extends to summarization, chatbots, speech recognition, etc.

  5. 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