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
from tensorflow.keras.callbacks import EarlyStopping
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
# Parameters
MAX_FEATURES = 10000 # Number of words to consider from vocabulary
MAX_LEN = 500 # Maximum length of sequences (truncate/pad to this length)
EMBEDDING_DIM = 128 # Dimension of embedding vectors
LSTM_UNITS = 128 # Number of LSTM units
BATCH_SIZE = 64
EPOCHS = 10
print("Loading IMDb dataset...")
# Load the IMDb dataset (binary sentiment: 0=negative, 1=positive)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=MAX_FEATURES)
print(f"Training data shape: {x_train.shape}")
print(f"Test data shape: {x_test.shape}")
# Preprocess: Pad sequences to fixed length
print("Padding sequences...")
x_train = pad_sequences(x_train, maxlen=MAX_LEN)
x_test = pad_sequences(x_test, maxlen=MAX_LEN)
# Build the LSTM model
print("Building LSTM model...")
model = Sequential([
Embedding(MAX_FEATURES, EMBEDDING_DIM, input_length=MAX_LEN),
LSTM(LSTM_UNITS, return_sequences=False), # Single LSTM layer for simplicity
Dropout(0.5),
Dense(1, activation='sigmoid') # Binary classification
])
# Compile the model
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
model.summary()
# Callbacks
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
# Train the model
print("Training model...")
history = model.fit(
x_train, y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_split=0.2,
callbacks=[early_stopping],
verbose=1
)
# Evaluate on test set
print("Evaluating on test set...")
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
print(f"Test Accuracy: {test_accuracy:.4f}")
# Predictions for classification report
y_pred = (model.predict(x_test) > 0.5).astype(int).flatten()
# Print classification report and confusion matrix
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))
# Plot training history
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Val Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()
# Example prediction function
def predict_sentiment(text):
# This is a simple demo; for real use, use a tokenizer fitted on your data
# Here, we'll assume the text is pre-tokenized similarly to IMDb
word_index = imdb.get_word_index()
sequence = [word_index.get(word, 0) for word in text.lower().split() if word in word_index]
sequence = sequence[:MAX_LEN]
padded = pad_sequences([sequence], maxlen=MAX_LEN)
pred = model.predict(padded)[0][0]
return "Positive" if pred > 0.5 else "Negative", pred
# Example usage
example = "This movie was amazing and I loved it!"
sentiment, score = predict_sentiment(example)
print(f"\nExample: '{example}' -> {sentiment} (score: {score:.4f})")
Key Features of This Code:
Dataset: Uses the built-in Keras IMDb dataset (50k movie reviews).
Preprocessing: Tokenization is handled by the dataset; sequences are padded to 500 tokens.