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 20k most frequent words
MAX_LEN = 200 # Cut off reviews after 200 words
EMBEDDING_DIM = 128 # Size of the vector representation for each word
# 2. Load and Preprocess Data
print("Loading data...")
# The IMDB dataset comes pre-tokenized (words are replaced by 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 LSTM batches)
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"Test data shape: {x_test.shape}")
# 3. Build the LSTM Model
model = Sequential()
# Layer 1: Embedding
# Converts integer sequences into dense vectors of fixed size.
model.add(Embedding(VOCAB_SIZE, EMBEDDING_DIM, input_length=MAX_LEN))
# Layer 2: LSTM
# The core recurrent layer. 64 is the dimensionality of the output space.
model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2))
# Layer 3: Dense (Output)
# A single neuron with sigmoid activation outputs a value between 0 and 1.
model.add(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,
batch_size=128,
epochs=5, # 5 epochs is usually enough for a demo
validation_data=(x_test, y_test))
# 6. Evaluate
score, acc = model.evaluate(x_test, y_test, batch_size=128)
print(f'\nTest score: {score:.4f}')
print(f'Test accuracy: {acc*100:.2f}%')
# 7. Prediction Helper Function
# This function converts raw text strings into the integer format the model expects
def predict_sentiment(text, model, word_index, max_len):
# 1. Tokenize and map to integers
# Note: IMDB word index offset (indices 0,1,2,3 are special reserved tokens)
words = text.lower().split()
# map words to integers; use 0 for unknown words
integers = [word_index.get(w, 0) for w in words]
# 2. Pad
padded = sequence.pad_sequences([integers], maxlen=max_len)
# 3. Predict
prediction = model.predict(padded)[0][0]
return prediction
# Retrieve the word index to decode text for prediction
word_index = imdb.get_word_index()
# Test with custom sentences
sample_text_positive = "This movie was absolutely amazing and fantastic"
sample_text_negative = "I hated this film it was a complete waste of time"
pred_pos = predict_sentiment(sample_text_positive, model, word_index, MAX_LEN)
pred_neg = predict_sentiment(sample_text_negative, model, word_index, MAX_LEN)
print(f"\nReview: '{sample_text_positive}'\nSentiment: {pred_pos:.4f} (Positive)")
print(f"\nReview: '{sample_text_negative}'\nSentiment: {pred_neg:.4f} (Negative)")