session: "6103-advanced-ml/2026-11-14 0933 Advance Machine Learning"
title: "Advance Machine Learning"
date: "2026-11-14 09:33"
duration: "--"
language: "en"
model: "deepseek-ai/DeepSeek-V3.2"
parts: 2
transcript_chars: 38074
generated: "2026-11-23T00:31:58+05:30"
Advanced Machine Learning
Overview
This class introduced the practical implementation of Recurrent Neural Networks (RNNs) for sequence data, specifically binary sentiment classification on the IMDB dataset. It covered foundational steps including data preprocessing (padding sequences), building a simple RNN model with an embedding layer, and training. The session then progressed to hyperparameter tuning and architectural modifications, such as changing activation functions and adding layers, while troubleshooting common errors like shape mismatches. The latter part introduced more advanced recurrent architectures, namely LSTM and GRU, explaining their gating mechanisms and the role of dropout for regularization. This class serves as a bridge from basic feedforward networks to sequence modeling, setting the stage for more complex architectures like Transformers.
Learning outcomes
- Preprocess sequence data (text) by padding to a fixed length for model input.
- Construct a simple RNN model using an embedding layer, RNN layer(s), and a dense output layer for binary classification.
- Compile and train an RNN model, interpreting training and validation accuracy.
- Modify model hyperparameters (optimizer, activation functions, layers) and understand their impact on performance.
- Identify and resolve shape mismatch errors related to output dimensions and
return_sequences. - Implement dropout in a neural network to mitigate overfitting.
- Describe the core components and gates of LSTM and GRU architectures.
- Explain the function of the
return_sequences parameter in recurrent layers.
Core concepts
Sequence Preprocessing
Textual data, like sentences, are sequences of words. To process them in batches, sequences must be of uniform length. This involves defining a maximum length and padding shorter sequences with placeholder tokens (e.g., zeros). This standardization is a prerequisite for batch processing in neural networks.
Embedding Layer
This layer maps discrete word indices (from a vocabulary) to dense vectors of fixed size (e.g., 32 dimensions). It transforms high-dimensional, sparse one-hot encodings into a lower-dimensional, dense representation where semantically similar words are closer in space, providing a more efficient and meaningful input for the network.
Vanilla RNN
A basic Recurrent Neural Network where neurons have recurrent connections, allowing them to maintain a hidden state that captures information from previous time steps. It is the foundational architecture for processing sequential data but can suffer from issues like vanishing gradients.
Return_sequences Parameter
In a recurrent layer, setting return_sequences=True outputs the hidden state at every time step, producing a sequence of outputs. This is necessary when stacking recurrent layers, as the subsequent layer expects a sequence input. Setting it to False outputs only the final hidden state, which is suitable for tasks like classification where a single prediction per sequence is needed.
Dropout
A regularization technique where a random subset of neurons is temporarily "dropped out" (set to zero) during training. This prevents the network from becoming overly reliant on specific neurons, encouraging a more robust and generalized model by making the architecture simpler during each training step.
LSTM (Long Short-Term Memory)
An advanced RNN variant designed to address the vanishing gradient problem. It uses three gates (input, forget, and output) to regulate the flow of information into, within, and out of a memory cell, allowing it to learn long-term dependencies more effectively than a vanilla RNN.
GRU (Gated Recurrent Unit)
A simplified alternative to LSTM that uses two gates (update and reset) instead of three. It combines the LSTM's forget and input gates into a single update gate, making it computationally faster and often equally effective for many tasks, while also being less prone to vanishing gradients.
Formulas and maths
(No explicit formulas with LaTeX were derived in the provided notes. The discussion focused on architectural dimensions and parameter counts from model summaries.)
Worked examples
1. Dataset & Preprocessing: Used the IMDB reviews dataset. Sequences were padded to a maximum length of 500. A simplified example: for the sentence "wish you good morning" (4 words) and a maxlen of 10, padding adds 6 zero tokens.
2. Initial Model Architecture:
- Embedding Layer:
input_dim=10000 (vocabulary size), output_dim=32. - Simple RNN Layer:
units=32. - Dense Output Layer:
units=1, activation='sigmoid'. - Result: After 3 epochs, training accuracy ~92.16%, validation accuracy ~80.48%.
3. Hyperparameter Tuning:
- Changed output activation to
softmax and optimizer to AdamW. Result: Accuracy dropped to ~50% (validation ~49%). - Added a second RNN layer with
return_sequences=True and activation='tanh'. Result: Accuracy improved to ~89%, validation to ~84%. - Attempted to increase RNN units to 64 and add dense layers, but this caused a shape mismatch error because the final output for binary classification must be a single value, not a sequence or higher dimension.
4. Advanced Model (LSTM/GRU):
- Architecture discussed: Two LSTM layers with dropout (0.5), dimensions: 64 units, then reduced to 432 units, final output of 1 unit for binary classification.
Questions asked in class
- Q: "From where this neuron is getting its value?"
- A: From the previous layer;
return_sequences passes the sequence of outputs from the previous RNN layer to the next. - Q: "Why the output layer dimension is 1, 32?"
- A: For a simple RNN, the output shape is (batch_size, units). With 32 units, the final dense layer reduces this to 1 for binary classification.
- Q: "In the dense layer, why we are using 1 here?"
- A: Because only one output is needed for binary classification (probability of positive class). Adding more layers doesn't change this fundamental requirement.
- Q: "Can we expect two outputs?"
- A: No, the output is always 1 for this binary classification task. Expecting two causes a shape mismatch error.
- Q: "What if
return_sequences is set to False?" - A: The computed output from the first recurrent cell will not be sent to the next recurrent cell. Only the original input data progresses, breaking the recurrence between layers.
- Q: "Can we decide which specific neurons to deactivate with dropout?"
- A: When using high-level APIs (like Keras layers), you only define the dropout percentage; neurons are deactivated randomly. To choose specific neurons, you would need to build a custom model from scratch.
- Q: "Is GRU a simpler and faster alternative to LSTM?"
- A: Yes, GRU uses two gates instead of three, making it faster and often less prone to issues like vanishing gradients.
Key takeaways
- Text sequence data requires preprocessing via padding to a fixed
maxlen for batch processing. - An embedding layer is crucial for converting sparse word indices into dense, meaningful vector representations.
- The
return_sequences parameter must be set to True when stacking recurrent layers so the next layer receives a sequence. - For binary classification, the final dense layer must have 1 unit with a sigmoid activation, regardless of the number of hidden layers.
- Shape mismatch errors often arise from a discrepancy between the model's output dimensions (e.g., expecting a sequence) and the target shape (a single value per sample).
- Dropout randomly deactivates neurons during training to prevent overfitting and improve model generalization.
- LSTM uses three gates (input, forget, output) to control information flow and mitigate the vanishing gradient problem.
- GRU is a simplified variant of LSTM with two gates (update, reset), offering faster training and comparable performance for many tasks.
- Binary cross-entropy is the correct loss function for binary classification, while categorical cross-entropy is for multi-class problems.
- Hyperparameter tuning (optimizer, activation, architecture) can significantly impact model accuracy and must be done while respecting output shape constraints.
- Validation split (e.g., 20%) is used during training to monitor performance on unseen data and detect overfitting.
Exam-style questions
1. You are building a sentiment classifier with two stacked LSTM layers. The model throws a shape mismatch error. What is the most likely cause and how do you fix it?
- Outline: The error likely occurs because the first LSTM layer's
return_sequences parameter is set to False. This means it outputs only the final time step, but the second LSTM layer expects a sequence of outputs. The fix is to set return_sequences=True in the first LSTM layer.
2. Compare and contrast the gating mechanisms of LSTM and GRU. What is the practical advantage of GRU?
- Outline: LSTM uses three gates: Input, Forget, and Output. GRU combines the input and forget gates into a single Update gate and has a Reset gate. The practical advantage of GRU is its simpler architecture, which leads to faster training times and fewer parameters, often with comparable performance.
3. During training of your RNN model, the training accuracy reaches 99% while the validation accuracy stalls at 75%. Name one technique to address this issue and explain how it works.
- Outline: This indicates overfitting. Implementing Dropout is a suitable technique. It works by randomly disabling a percentage of neurons during each training batch, preventing the network from becoming overly reliant on specific neurons and thus encouraging more robust feature learning.
4. For a binary classification task using an RNN, why is the final dense layer configured with 1 unit and a sigmoid activation, even if the hidden layers have many units?
- Outline: Binary classification requires a single output representing the probability of the positive class. A single unit with a sigmoid activation outputs a value between 0 and 1, which is interpreted as this probability. The number of hidden units affects the model's capacity to learn features but does not change the single-output requirement.
Glossary
- Vocabulary Size - The number of unique words kept in the dataset to reduce dimensionality.
- Padding - Adding tokens (like zeros) to sequences to make them all the same length.
- Units (in RNN) - The number of neurons in a recurrent layer; defines the dimensionality of the output space.
- Binary Classification - A task with two possible output classes.
- Validation Split - The portion of training data set aside to evaluate model performance during training.
- Vanishing Gradient - A problem in deep networks where gradients become extremely small, hindering weight updates in early layers.
- Encoder-Decoder - An architecture where one network (encoder) processes the input into a context vector, and another (decoder) generates the output sequence (mentioned as upcoming).
Follow-ups
- Identify the specific name of the padding technique used in the example (students were instructed to search for it).
- A more detailed explanation of how activation functions operate within RNN cells.
- Practical implementation and exploration of Vanilla/Simple RNN (students were advised to try it themselves).
- Handling classification tasks with multiple input features.
- Upcoming topics: Encoder-Decoder architecture, Transformer models, BERT, GPT, GPT-2, and Large Language Models (LLMs).