The user wants a sentiment analysis model using LSTM (Long Short-Term Memory) networks. This is a standard Natural Language Processing (NLP) task. I need to provide a complete, runnable code example, likely using Python and a popular deep learning library like TensorFlow/Keras or PyTorch.
1. Choose the framework:
- TensorFlow/Keras: Very popular, high-level API, easy for beginners to grasp quickly. Good for showing the structure of an LSTM model clearly.
- PyTorch: Also popular, more pythonic, flexible. Good for research.
- Decision: I will use TensorFlow/Keras because it's often the default choice for "show me how to build a standard model" requests due to its concise syntax. It makes the architecture very visible.
2. Choose the dataset:
- IMDB Movie Reviews: The "Hello World" of sentiment analysis. It's built into Keras, which makes the code self-contained (no external file loading needed).
- Custom CSV: Requires the user to have a file. Not good for a reproducible example.
- Decision: Use the
tensorflow.keras.datasets.imdb.
3. Outline the steps:
- Imports: Necessary libraries (TensorFlow, NumPy).
- Data Loading & Preprocessing:
- Load data.
- Padding sequences (LSTMs need fixed-length input).
- Model Architecture:
- Embedding Layer (Crucial for text).
- LSTM Layer (The core requirement).
- Dense Layer (Output).
- Compilation: Optimizer (Adam), Loss (Binary Crossentropy), Metrics (Accuracy).
- Training: Fit the model.
- Evaluation/Prediction: Show how to use it on new data.
4. Drafting the Code (Mental or Scratchpad):
-
Hyperparameters: vocab_size = 10000, max_length = 200, embedding_dim = 128.
-
Data Loading:
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size)
x_train = pad_sequences(x_train, maxlen=max_length)
x_test = pad_sequences(x_test, maxlen=max_length)
-
Model:
model = Sequential()
model.add(Embedding(vocab_size, embedding_dim, input_length=max_length))
model.add(LSTM(64, dropout=0.2)) # Maybe return_sequences=False for just final classification
model.add(Dense(1, activation='sigmoid'))
-
Compilation & Training:
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(...)
-
Prediction Helper: Since the IMDB dataset comes pre-tokenized (integers), to test with custom text, I need a helper function to convert text back to integers. This is often the most confusing part for beginners. I should include a simple prediction function that handles the tokenization mapping.
5. Refinement and Polish:
- Explanation: Just code isn't enough. I need to explain why we use an Embedding layer, why we pad, and what the LSTM actually does.
- Code Structure: Make it modular. Put hyperparameters at the top.
- Predictions: Create a function
predict_sentiment(text) to make it interactive and practical.
6. Self-Correction during drafting:
- Issue: The IMDB dataset in Keras returns integers. If I want to show how to predict on new text, I need the word index.
- Fix: I'll include a section on how to map words to indices for prediction. It adds complexity but is necessary for a "complete" guide.
- Simpler alternative: Skip the custom prediction function and just evaluate on the test set.
- Decision: I'll provide the standard training loop first. Then, I will add a "Bonus" section or a clear function for predicting on new raw text, as that's what users ultimately want to do.
7. Final Code Structure:
- Prerequisites: Install tensorflow.
- Imports.
- Hyperparameters.
- Data Prep (Load, Pad).
- Model Definition (Embedding -> LSTM -> Dense).
- Training.
- Evaluation.
- (Crucial) Inference: A function to decode new sentences.
8. Writing the Explanation:
- Explain the Embedding Layer: Converts integers to dense vectors.
- Explain LSTM: Captures context and order of words (unlike Bag of Words).
- Explain Output: Sigmoid for binary classification (0 to 1).
Let's write the response.
Here is a complete implementation of a Sentiment Analysis model using Python, TensorFlow/Keras, and an LSTM network.
We will use the IMDB Movie Reviews dataset (built into TensorFlow), which contains 50,000 reviews labeled as positive (1) or negative (0).
Prerequisites
You will need to install TensorFlow and NumPy:
pip install tensorflow numpy
The Python Code
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout
# ==========================================
# 1. Configuration & Hyperparameters
# ==========================================
VOCAB_SIZE = 10000 # Only keep the top 10,000 most frequent words
MAX_LENGTH = 200 # Max length of a review (truncate longer, pad shorter)
EMBEDDING_DIM = 128 # Dimension of the dense embedding
BATCH_SIZE = 64
EPOCHS = 5
# ==========================================
# 2. Data Preprocessing
# ==========================================
print("Loading data...")
# Load pre-tokenized IMDB dataset
# words are replaced by integers (frequency rank)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=VOCAB_SIZE)
# Pad sequences to ensure uniform input size
# If a review is < 200 words, we add zeros. If > 200, we cut it.
x_train = pad_sequences(x_train, maxlen=MAX_LENGTH, padding='post', truncating='post')
x_test = pad_sequences(x_test, maxlen=MAX_LENGTH, padding='post', truncating='post')
print(f"Training data shape: {x_train.shape}")
print(f"Testing data shape: {x_test.shape}")
# ==========================================
# 3. Build the LSTM Model
# ==========================================
model = Sequential([
# Layer 1: Embedding
# Maps integer indices to dense vectors of fixed size (EMBEDDING_DIM)
Embedding(input_dim=VOCAB_SIZE, output_dim=EMBEDDING_DIM, input_length=MAX_LENGTH),
# Layer 2: LSTM
# The core recurrent layer. 64 units is the dimensionality of the output space.
LSTM(64, return_sequences=False),
# Layer 3: Dropout
# Helps prevent overfitting
Dropout(0.5),
# Layer 4: Dense (Output)
# Single unit with sigmoid activation for binary classification (0 to 1 probability)
Dense(1, activation='sigmoid')
])
# ==========================================
# 4. Compile the Model
# ==========================================
model.compile(
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
model.summary()
# ==========================================
# 5. Train the Model
# ==========================================
print("\nStarting training...")
history = model.fit(
x_train, y_train,
epochs=EPOCHS,
batch_size=BATCH_SIZE,
validation_split=0.2, # Use 20% of training data for validation
verbose=1
)
# ==========================================
# 6. Evaluate on Test Data
# ==========================================
loss, accuracy = model.evaluate(x_test, y_test)
print(f"\nTest Accuracy: {accuracy*100:.2f}%")
# ==========================================
# 7. Prediction Helper Function
# ==========================================
# To predict on custom sentences, we need to convert words to the IMDB integer indices.
# Let's create a helper function to decode/encode text.
# Get the word index dictionary from IMDB dataset
word_index = imdb.get_word_index()
# Adjust indices (IMDB reserves 0, 1, 2 for special tags)
# We create a reverse index to decode integers back to words if needed,
# but for prediction, we map words -> integers.
def predict_sentiment(text):
# 1. Tokenize and map to integers
tokens = text.lower().split()
# Map word to integer. If word not in top 10000, ignore it.
# IMDB index offset: 0=padding, 1=start, 2=unknown (OOV)
# Actual words start at index 3 in the dictionary logic usually,
# but standard logic uses the word_index directly.
sequences = [[word_index.get(word, 0) + 3 for word in tokens]]
# Note: Simple logic implies if word is not found, it becomes 0 (padding) effectively or handled as OOV.
# For production, use a dedicated Tokenizer. Here we use the raw dataset dictionary.
# 2. Pad
padded = pad_sequences(sequences, maxlen=MAX_LENGTH, padding='post', truncating='post')
# 3. Predict
prediction = model.predict(padded)[0][0]
print(f"\nReview: '{text}'")
print(f"Sentiment Score: {prediction:.4f}")
if prediction > 0.5:
print("Verdict: POSITIVE")
else:
print("Verdict: NEGATIVE")
# Test with custom sentences
predict_sentiment("This movie was absolutely fantastic with great acting")
predict_sentiment("I hated this film it was a complete waste of time")
Step-by-Step Explanation
-
Hyperparameters:
VOCAB_SIZE: We limit the vocabulary to the 10,000 most common words to keep the model size manageable.
MAX_LENGTH: LSTMs can handle variable lengths, but for batch processing, tensors must be the same shape. We pad short reviews with zeros and cut off long reviews at 200 words.
-
Data Loading (imdb.load_data):
- The IMDB dataset comes pre-tokenized. Instead of raw text strings, the data is a list of integers. For example, the word "the" might be integer
1, and "movie" might be integer 14.
-
Embedding Layer:
- This turns positive integers (indexes) into dense vectors of fixed size. Instead of using a simple "One-Hot Encoding" (which creates massive sparse vectors), the embedding learns relationships between words (e.g., "good" and "great" will have similar vector values).
-
LSTM Layer:
- This is the Long Short-Term Memory layer. It processes the sequence of word vectors. Unlike a standard RNN, an LSTM can "remember" context from earlier in the sentence (e.g., recognizing that "not" flips the meaning of subsequent adjectives).
-
Dense Layer (Output):
- We use a single neuron with a
sigmoid activation function. This squeezes the output between 0 and 1.
- Closer to 1 = Positive Sentiment.
- Closer to 0 = Negative Sentiment.
-
Compiling:
- Loss:
binary_crossentropy is standard for binary classification (Yes/No).
- Optimizer:
adam is generally the best default optimizer for NLP tasks.
How to improve this model?
For real-world applications, you would typically add:
- Bidirectional LSTM: Wraps the LSTM layer to read text forwards and backwards (
Bidirectional(LSTM(64))), capturing context from both ends of the sentence.
- Pre-trained Embeddings: Instead of training an Embedding layer from scratch (like we did), you would use GloVe or Word2Vec, which are embeddings already trained on massive datasets like Wikipedia.