Sentiment Analysis on IMDB Reviews
Goal
We will train a model that reads a movie review and tells if it is positive or negative. The IMDB dataset has 50,000 reviews, half for training and half for testing.
Step 1: Load Data
python
import keras
from keras import layers
import numpy as np
# Download the reviews as raw text
keras.utils.get_file(
"aclImdb_v1.tar.gz",
"https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz",
untar=True, cache_dir=".", cache_subdir=""
)
# The folder aclImdb/train has subfolders pos and neg (and unsup, which we remove)
bash
rm -r aclImdb/train/unsup
python
train_ds = keras.utils.text_dataset_from_directory(
"aclImdb/train", batch_size=32, validation_split=0.2, subset="training", seed=1)
val_ds = keras.utils.text_dataset_from_directory(
"aclImdb/train", batch_size=32, validation_split=0.2, subset="validation", seed=1)
test_ds = keras.utils.text_dataset_from_directory("aclImdb/test", batch_size=32)
Quicker alternative:
keras.datasets.imdb.load_data() gives reviews that are already converted to integers. The raw text version teaches you more, because you see the full pipeline.
Step 2: Text Vectorization
python
vectorize = layers.TextVectorization(
max_tokens=20000, output_mode="int", output_sequence_length=250)
vectorize.adapt(train_ds.map(lambda text, label: text))
Step 3: Build the Model
python
model = keras.Sequential([
keras.Input(shape=(1,), dtype="string"),
vectorize,
layers.Embedding(20000, 64),
layers.GlobalAveragePooling1D(),
layers.Dropout(0.4),
layers.Dense(32, activation="relu"),
layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
Step 4: Train and Evaluate
python
history = model.fit(train_ds, validation_data=val_ds, epochs=8)
loss, acc = model.evaluate(test_ds)
print("Test accuracy:", acc) # about 0.86 to 0.88
Step 5: Predict New Text
python
reviews = [
"This movie was fantastic, I loved every minute!",
"Boring plot and terrible acting. A waste of time.",
]
scores = model.predict(np.array(reviews))
for r, s in zip(reviews, scores.ravel()):
print(f"{s:.2f} -> {'positive' if s > 0.5 else 'negative'} | {r}")
Result
The first review gets a score close to 1 (positive), the second a score close to 0 (negative).
How to Improve
- Use an LSTM or a bidirectional GRU instead of average pooling
- Use pretrained embeddings
- Try a Transformer or a pretrained language model for 90 percent and above
- Check misclassified reviews to find patterns such as sarcasm
Conclusion
You built a working sentiment analyzer. The same pipeline works for spam detection, ticket classification and many other text tasks.
Quick Summary: Load text, vectorize, embed, pool, classify with sigmoid and evaluate on the test set.

