The user wants to create a sentiment analysis model using LSTM (Long Short-Term Memory) networks. This is a classic Natural Language Processing (NLP) task.
To provide a complete and useful answer, I need to cover the following steps:
- Prerequisites: Mention necessary libraries (TensorFlow/Keras or PyTorch, NumPy, etc.). I'll stick to TensorFlow/Keras as it's very beginner-friendly for this specific architecture.
- Data Preparation:
- Load a dataset (IMDB movie reviews are the standard "Hello World" for this).
- Tokenization: Converting text to numbers.
- Padding: Ensuring sequences are the same length.
- Train/Test split.
- Model Architecture:
- Embedding Layer: To learn vector representations of words.
- LSTM Layer: The core recurrent layer.
- Dense Layer: For the final classification (Sigmoid for binary, Softmax for multi-class).
- Training: Compile and fit the model.
- Evaluation: Check accuracy/loss.
- Inference/Prediction: A function to test new, custom sentences.
Drafting the Code Structure:
- Imports:
tensorflow, keras, numpy, matplotlib (optional, but good for plotting).
- Hyperparameters:
vocab_size, max_length, embedding_dim, epochs.
- Data Loading:
tensorflow.keras.datasets.imdb.
- Preprocessing:
pad_sequences.
- Model:
model = Sequential()
model.add(Embedding(vocab_size, embedding_dim, input_length=max_length))
model.add(LSTM(64)) # Maybe add dropout here?
model.add(Dense(1, activation='sigmoid'))
- Compile:
loss='binary_crossentropy', optimizer='adam'.
- Prediction helper: Needs to handle tokenization of raw text using the same word index.
Refining the Explanation:
The code alone isn't enough. I need to explain why we are doing each step.
- Why Embedding? To turn integers into dense vectors.
- Why Padding? LSTMs need fixed-size input tensors (usually).
- Why LSTM? To capture sequence dependencies (context).
Choice of Framework:
I will use TensorFlow/Keras because it handles the dataset loading (imdb.load_data) and preprocessing (pad_sequences) very seamlessly for a tutorial context. PyTorch is great, but requires a bit more boilerplate for custom datasets and data loaders.
Adding a "Real-world" Prediction Step:
The IMDB dataset in Keras comes pre-tokenized. This is confusing for beginners who want to test it on their own sentences because they need the word index. I need to include a section on how to download the word index and preprocess a custom string so the user can actually see it work on "I loved this movie" vs "This movie was terrible".
Plan:
- Introduction: Briefly explain LSTMs in sentiment analysis.
- Code Implementation (Step-by-Step):
- Setup & Hyperparameters.
- Data Loading & Preprocessing (IMDB).
- Model Building (Embedding -> LSTM -> Dense).
- Training.
- Testing on Custom Data: Write a helper function to predict sentiment on a user-input string.
- Explanation: Briefly explain the layers.
Let's write the code mentally.
imdb.load_data(num_words=10000) -> limits vocabulary.
pad_sequences(..., maxlen=120, truncating='post') -> standard padding.
model.fit(..., epochs=10) -> don't overdo epochs to avoid overfitting, maybe 10 is fine for a demo.
Self-Correction during thought process: The IMDB dataset in Keras returns integers. To predict on a new sentence, I need to map words to those specific integers. Keras provides imdb.get_word_index(). I must handle the offset (indices start at 3 because 0, 1, 2 are reserved for padding, start, unknown). I will write a function to handle this mapping.
Final Output Structure:
- Python Code block.
- Explanation of the code.
- How to use it.
Let's generate the response.
Here is a complete guide to building a Sentiment Analysis model using an LSTM network with Python and TensorFlow/Keras.
We will use the IMDB Movie Reviews dataset (built into Keras), which contains 50,000 reviews labeled as positive (1) or negative (0).
1. The Python Code
You can run this code directly in a Jupyter Notebook or Python script.
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout
# --- 1. Configuration ---
VOCAB_SIZE = 20000 # Only keep the top 20,000 most frequent words
MAX_LEN = 200 # Cut off reviews after 200 words
EMBEDDING_DIM = 128 # Size of the vector representation for each word
# --- 2. Data Preparation ---
print("Loading data...")
# Load data (words are already converted to integers)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=VOCAB_SIZE)
# Pad sequences so they are all the same length (required for matrix operations)
# If review < 200 words, add zeros. If > 200, truncate.
x_train = sequence.pad_sequences(x_train, maxlen=MAX_LEN)
x_test = sequence.pad_sequences(x_test, maxlen=MAX_LEN)
print(f"Training data shape: {x_train.shape}")
print(f"Testing data shape: {x_test.shape}")
# --- 3. Model Architecture ---
model = Sequential()
# Layer 1: Embedding
# Maps integer indices to dense vectors of fixed size (EMBEDDING_DIM)
model.add(Embedding(VOCAB_SIZE, EMBEDDING_DIM, input_length=MAX_LEN))
# Layer 2: LSTM
# 64 units = dimensionality of the output space.
# dropout/recurrent_dropout help prevent overfitting.
model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2))
# Layer 3: Dense (Output)
# Single neuron with sigmoid activation for binary classification (0 or 1)
model.add(Dense(1, activation='sigmoid'))
# --- 4. Compilation ---
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.summary()
# --- 5. Training ---
print("\nStarting training...")
history = model.fit(x_train, y_train,
batch_size=128,
epochs=5, # 5 epochs is usually enough for a demo
validation_data=(x_test, y_test))
# --- 6. Evaluation ---
score, acc = model.evaluate(x_test, y_test, batch_size=128)
print(f'\nTest score: {score:.4f}')
print(f'Test accuracy: {acc:.4f}')
# --- 7. Prediction on New Data ---
# To test on custom sentences, we need to preprocess them exactly like the training data
word_index = imdb.get_word_index()
def predict_sentiment(text):
# 1. Tokenize and map to integers
words = text.lower().split()
# imdb word index offset: 0=padding, 1=start, 2=unknown
# We map words to indices; if not found, use 2 (unknown)
encoded = [word_index.get(w, 0) + 3 for w in words]
# Handle specific Keras IMDB offsets usually handled internally
# But for manual prediction, we ensure indices are within range
encoded = [min(idx, VOCAB_SIZE - 1) for idx in encoded]
# 2. Pad
padded = sequence.pad_sequences([encoded], maxlen=MAX_LEN)
# 3. Predict
prediction = model.predict(padded)
sentiment = "Positive" if prediction > 0.5 else "Negative"
print(f"\nReview: '{text}'")
print(f"Sentiment: {sentiment} (Score: {prediction[0][0]:.4f})")
# Test examples
predict_sentiment("this movie was absolutely amazing and fantastic")
predict_sentiment("i hated this film it was a complete waste of time")
2. Explanation of Key Components
The Embedding Layer
model.add(Embedding(VOCAB_SIZE, EMBEDDING_DIM, input_length=MAX_LEN))
Text data is typically converted into integers (e.g., "the" = 1, "movie" = 2). However, integers imply that "movie" (2) is mathematically greater than "the" (1), which is false for meaning.
The Embedding layer transforms these integers into dense vectors (lists of decimal numbers). The neural network learns that words with similar meanings (like "film" and "movie") should have similar vectors.
The LSTM Layer
model.add(LSTM(64, ...))
This is the core of the model.
- Why LSTM? Standard neural networks treat inputs independently. Sentiment depends on context (e.g., "not good" is different from "good"). LSTMs have internal memory loops that allow information to persist across the sequence of words.
- Dropout: We randomly turn off neurons during training to force the model to learn robust features and prevent it from memorizing the training data (overfitting).
The Dense Output Layer
model.add(Dense(1, activation='sigmoid'))
We use a single neuron because this is binary classification (Positive vs. Negative).
- Sigmoid squashes the output between 0 and 1.
- Closer to 0: Negative
- Closer to 1: Positive
3. How to Improve the Model
- Pre-trained Embeddings: Instead of learning word vectors from scratch, you can use pre-trained vectors like GloVe or Word2Vec. This helps if you have a small dataset.
- Bidirectional LSTM: Use
Bidirectional(LSTM(64)). This reads the text forwards and backwards. Sometimes the sentiment is clarified by words that appear later in the sentence.
- Stacking LSTMs: You can stack two LSTM layers on top of each other to learn more complex patterns.