Analyzing LSTM Architecture
I've been deeply analyzing the LSTM's architecture for sentiment analysis. Currently, I'm focusing on the input layer's structure and how it handles the tokenized text data, aiming for efficient processing. I'm considering different embedding techniques, from word2vec to GloVe, to optimize the model's performance and accuracy. My next step will be to explore different LSTM cell configurations, weighing the pros and cons of each in this specific context.
Constructing a Classifier
I'm structuring the code for a basic text classifier. First, I'm setting up the essential libraries, including tensorflow and numpy, and preparing the data with the IMDb movie review dataset. Next, I'll work on preprocessing steps, such as tokenization and padding for consistent sequence lengths. The model architecture will consist of an embedding layer, LSTM layer, and a dense output layer. I'll focus on model compilation, training, evaluation, and finally, a prediction function to apply the model to custom text inputs.
Developing the Model Structure
I'm now integrating crucial hyperparameters into the model design for sentiment analysis. The vocabulary size is set to 10,000, max review length to 200 words, and the embedding dimension to 128. I've initiated data loading with imdb.load_data and will preprocess sequences using pad_sequences to ensure uniform input length. The architecture begins with an embedding layer, followed by LSTM with dropout, and a dense output layer with sigmoid activation for binary classification.
Refining Model Implementation
I'm presently building upon the established framework, specifically concentrating on the concrete instantiation of the LSTM model. I've integrated an embedding layer, followed by a 64-unit LSTM layer with dropout. The model culminates in a sigmoid activated dense layer. I'm focusing on defining the compilation with binary crossentropy loss, adam optimizer, and accuracy metrics. Now I'm preparing the model training stage, including the essential parameters such as batch size and epochs. Finally, I'm working to provide a function for translating raw text for custom prediction, which needs a way to encode the text into integers using the provided word index.
Clarifying Data Preparation
I'm now detailing how the IMDb dataset is already tokenized, which could be misleading for newcomers expecting to handle raw text directly. I'll include a "Real World" section, demonstrating how to process raw input. For the primary code, I'll stick to the IMDb dataset for immediate execution. Crucially, I'm integrating a section to showcase the reverse word dictionary usage to allow users to apply the model to any text.
Updating Model Parameters
I've discovered that using recurrent_dropout slows down the model, so I'm sticking to standard dropout for faster execution. I also double-checked that maxlen is consistently defined for padding. Now, I'm focusing on the final code touches, including adding clarifying comments. I'll also add a predict_sentiment function to simplify prediction with new sentences for anyone working with the IMDb dataset. Finally, I'll review the explanation, ensuring it explains the rationale behind LSTM and the role of the Embedding layer.
Here is a complete, runnable Python example using TensorFlow/Keras.
This code uses the IMDb movie review dataset (built into Keras). It classifies reviews as either Positive or Negative.
Prerequisites
You need to install TensorFlow:
pip install tensorflow numpy
The Python Code
import numpy as np
from tensorflow.keras.datasets import imdb
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Embedding
from tensorflow.keras.preprocessing.sequence import pad_sequences
# --- Configuration ---
VOCAB_SIZE = 10000 # Only consider the top 10k words
MAX_LEN = 200 # Cut/pad reviews to 200 words
EMBEDDING_DIM = 128 # Vector size for each word
EPOCHS = 3
BATCH_SIZE = 64
print("Loading data...")
# Load the dataset (already tokenized as integers)
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=VOCAB_SIZE)
print(f"Training samples: {len(X_train)}")
print(f"Test samples: {len(X_test)}")
# --- Preprocessing ---
# Pad sequences so they all have the same length (required for the neural network)
X_train = pad_sequences(X_train, maxlen=MAX_LEN)
X_test = pad_sequences(X_test, maxlen=MAX_LEN)
# --- Build the LSTM Model ---
model = Sequential()
# 1. Embedding Layer: turns integers (word indices) into dense vectors of fixed size
model.add(Embedding(input_dim=VOCAB_SIZE, output_dim=EMBEDDING_DIM, input_length=MAX_LEN))
# 2. LSTM Layer: The memory layer.
# 64 units is the dimensionality of the output space.
# dropout helps prevent overfitting.
model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2))
# 3. Dense Layer: Output layer
# Sigmoid activation outputs a value between 0 and 1 (0=Negative, 1=Positive)
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# --- Train the Model ---
print("\nStarting training...")
model.fit(X_train, y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_data=(X_test, y_test))
# --- Evaluation ---
loss, accuracy = model.evaluate(X_test, y_test)
print(f"\nTest Accuracy: {accuracy * 100:.2f}%")
# --- Function to Predict Custom Text ---
# Since the dataset is pre-encoded, we need the word_index to encode new text
word_index = imdb.get_word_index()
def predict_sentiment(text):
# 1. Tokenize: Convert words to lower case and split
tokens = text.lower().split()
# 2. Encode: Map words to integers based on the IMDb dictionary
# The index is offset by 3 because 0=pad, 1=start, 2=unknown
encoded = [word_index.get(word, 0) + 3 for word in tokens]
# Cap indices at VOCAB_SIZE (treat others as unknown)
encoded = [idx if idx < VOCAB_SIZE else 2 for idx in encoded]
# 3. Pad: Ensure length matches the model input
padded = pad_sequences([encoded], maxlen=MAX_LEN)
# 4. Predict
prediction = model.predict(padded)[0][0]
print(f"\nText: '{text}'")
print(f"Score: {prediction:.4f} ({'POSITIVE' if prediction > 0.5 else 'NEGATIVE'})")
# --- Test on custom sentences ---
predict_sentiment("This movie was fantastic and the acting was great")
predict_sentiment("I wasted my time watching this terrible film")
Explanation of Key Components
-
Preprocessing (pad_sequences):
- Neural networks require rectangular input (matrices).
- Text sequences are naturally different lengths.
pad_sequences ensures every review is exactly 200 numbers long by adding zeros to the front or cutting off the end.
-
Embedding Layer:
- Raw text comes in as integers (e.g., "Movie" = 45).
- The model cannot learn mathematical relationships from raw integers easily.
- The Embedding layer transforms that integer 45 into a vector of 128 floats (e.g.,
[0.1, -0.5, ... 0.9]). This allows the model to learn that "Good" and "Great" are mathematically similar directions.
-
LSTM Layer:
- Long Short-Term Memory is a Recurrent Neural Network (RNN).
- Unlike standard networks that look at input all at once, LSTMs process text sequentially (left to right).
- It keeps an internal "state" (memory) that remembers previous words in the sentence to understand the context of the current word (e.g., understanding that "not" before "good" flips the meaning).
-
Dense Output:
- We use
sigmoid activation because we want a probability between 0 and 1.
- Closer to 0 = Negative.
- Closer to 1 = Positive.
How to run this on your own dataset (CSV/Text files)
The example above uses the pre-packaged IMDb dataset. If you have a CSV file with text and label columns, you need to add a step to tokenize your raw text before passing it to the model:
from tensorflow.keras.preprocessing.text import Tokenizer
# Assume texts is a list of strings: ["I love this", "I hate this"]
tokenizer = Tokenizer(num_words=10000)
tokenizer.fit_on_texts(texts) # Build the dictionary
sequences = tokenizer.texts_to_sequences(texts) # Convert text to integers
data = pad_sequences(sequences, maxlen=200)