Preparing sentiment classification code
The user is looking for Python code for text sentiment classification using LSTM and Keras/TensorFlow. I need to create a full pipeline that includes tokenizing, padding, building the model, training, evaluating, and predicting. As I write this code, I want it to be concise but informative, with comments where necessary. Since the IMDb dataset is already integer-encoded, I won’t focus on tokenization but will provide an example using it for clarity while keeping the Keras API stability in mind.Developing LSTM sentiment classification
I’ll create a standalone script that includes data loading, training, and example predictions. It’s crucial to specify that TensorFlow 2.x is needed. I'll set a vocabulary size of 10,000 and maximum sequence length of 200.
I’ll load the IMDb dataset and pad sequences accordingly. The model will use an embedding layer, an LSTM layer, and a dense output layer with sigmoid activation. After compiling, I’ll fit the model to the training data and evaluate its performance. I also need a function to encode and decode custom reviews, accounting for the pre-existing word index. Let's implement that!Creating the LSTM script
I’m aiming to provide a comprehensive Python script with inline comments, while keeping the explanation concise. I’ll start by importing necessary modules from TensorFlow, like pad_sequences, Sequential, Embedding, LSTM, Dense, and Dropout from the Keras library, along with the IMDb dataset.
It’s also a good idea to include a random seed for reproducibility. I'll define the main function and follow a straightforward structure without unnecessary embellishments. I’ll remind users to pip install any dependencies, ensuring an efficient response! Below is a minimal, end‑to‑end example in Python using TensorFlow/Keras to train an LSTM sentiment classifier on the built‑in IMDB movie review dataset and then use it to predict sentiment of new text.
"""
Sentiment classification with an LSTM on the IMDB dataset.
Requirements:
pip install "tensorflow>=2.9"
"""
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. Hyperparameters
# -----------------------------
VOCAB_SIZE = 10000 # Only keep the top 10,000 words
MAX_LEN = 200 # Pad / truncate all reviews to length 200
EMBED_DIM = 128
LSTM_UNITS = 128
BATCH_SIZE = 64
EPOCHS = 5
# -----------------------------
# 2. Load and preprocess data
# -----------------------------
print("Loading IMDB dataset...")
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=VOCAB_SIZE)
print(f"Train samples: {len(x_train)}, Test samples: {len(x_test)}")
# Pad sequences to the same length
x_train = pad_sequences(x_train, maxlen=MAX_LEN, padding='post', truncating='post')
x_test = pad_sequences(x_test, maxlen=MAX_LEN, padding='post', truncating='post')
# -----------------------------
# 3. Define LSTM model
# -----------------------------
model = Sequential([
Embedding(input_dim=VOCAB_SIZE, output_dim=EMBED_DIM, input_length=MAX_LEN),
LSTM(LSTM_UNITS, dropout=0.2, recurrent_dropout=0.2),
Dense(1, activation='sigmoid') # Binary sentiment: positive / negative
])
model.compile(
loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
model.summary()
# -----------------------------
# 4. Train model
# -----------------------------
history = model.fit(
x_train, y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_split=0.2,
verbose=1
)
# -----------------------------
# 5. Evaluate on test data
# -----------------------------
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
print(f"\nTest accuracy: {test_acc:.4f}, Test loss: {test_loss:.4f}")
# -----------------------------
# 6. Inference on new text
# -----------------------------
# IMDB dataset comes pre-tokenized as integer indices.
# We need to map raw text -> IMDB word index -> integer sequence -> pad -> predict.
word_index = imdb.get_word_index()
# Offsets used by Keras for IMDB (0,1,2 are reserved; real tokens start at 3)
INDEX_OFFSET = 3
word_to_id = {k: (v + INDEX_OFFSET) for k, v in word_index.items()}
word_to_id["<PAD>"] = 0
word_to_id["<START>"] = 1
word_to_id["<UNK>"] = 2
word_to_id["<UNUSED>"] = 3
id_to_word = {value: key for key, value in word_to_id.items()}
def encode_text(text: str) -> np.ndarray:
"""
Convert a raw text string into a padded integer sequence
compatible with the IMDB model's vocabulary.
"""
tokens = text.lower().split()
seq = []
for w in tokens:
idx = word_to_id.get(w, word_to_id["<UNK>"])
# Keep only within vocabulary size
if idx < VOCAB_SIZE:
seq.append(idx)
else:
seq.append(word_to_id["<UNK>"])
return pad_sequences([seq], maxlen=MAX_LEN, padding='post', truncating='post')
def predict_sentiment(text: str) -> float:
"""
Predict sentiment of `text`.
Returns probability that the text is positive (0.0–1.0).
"""
x = encode_text(text)
prob = float(model.predict(x, verbose=0)[0][0])
return prob
# Example predictions
examples = [
"This movie was fantastic! I really loved it and would watch it again.",
"Terrible film. It was a waste of time and the acting was awful."
]
for review in examples:
p = predict_sentiment(review)
label = "Positive" if p >= 0.5 else "Negative"
print(f"\nReview: {review}")
print(f"Predicted sentiment: {label} (prob={p:.4f})")
This script:
- Loads and pads the IMDB dataset.
- Builds an LSTM-based model for binary sentiment classification.
- Trains and evaluates it.
- Provides a helper to encode raw text and get a sentiment prediction.