The user wants Python code to classify text sentiment using an LSTM (Long Short-Term Memory) neural network. I'll create a comprehensive example that includes:
- Data preprocessing
- Text tokenization and padding
- Building an LSTM model
- Training the model
- Evaluating the model
- Making predictions
I'll use TensorFlow/Keras as the deep learning framework and include options for both using a sample dataset and using custom data.
Let me create a well-structured, educational example with proper comments and explanations. # Text Sentiment Classification with LSTM Neural Network
I'll provide a comprehensive implementation of sentiment classification using LSTM, from data preprocessing to model evaluation.
Complete Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
import seaborn as sns
# TensorFlow/Keras imports
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (
Embedding, LSTM, Dense, Dropout,
Bidirectional, SpatialDropout1D
)
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from tensorflow.keras.utils import plot_model
# Set random seed for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
class SentimentLSTM:
"""LSTM-based Sentiment Classification Model"""
def __init__(self, max_words=10000, max_len=200, embedding_dim=128):
"""
Initialize the sentiment classifier.
Args:
max_words: Maximum vocabulary size
max_len: Maximum sequence length
embedding_dim: Dimension of word embeddings
"""
self.max_words = max_words
self.max_len = max_len
self.embedding_dim = embedding_dim
self.tokenizer = Tokenizer(num_words=max_words, oov_token='<OOV>')
self.model = None
self.history = None
def preprocess_text(self, texts):
"""
Basic text preprocessing.
Args:
texts: List of text strings
Returns:
Preprocessed texts
"""
import re
processed = []
for text in texts:
# Convert to lowercase
text = text.lower()
# Remove HTML tags
text = re.sub(r'<[^>]+>', '', text)
# Remove special characters but keep basic punctuation
text = re.sub(r'[^a-zA-Z\s]', '', text)
# Remove extra whitespace
text = ' '.join(text.split())
processed.append(text)
return processed
def prepare_data(self, texts, labels, test_size=0.2):
"""
Tokenize and pad sequences, then split data.
Args:
texts: List of text strings
labels: List of labels (0 or 1)
test_size: Proportion for test set
Returns:
X_train, X_test, y_train, y_test
"""
# Preprocess texts
texts = self.preprocess_text(texts)
# Fit tokenizer on texts
self.tokenizer.fit_on_texts(texts)
# Convert texts to sequences
sequences = self.tokenizer.texts_to_sequences(texts)
# Pad sequences
X = pad_sequences(sequences, maxlen=self.max_len, padding='post', truncating='post')
y = np.array(labels)
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_size, random_state=42, stratify=y
)
print(f"Vocabulary size: {len(self.tokenizer.word_index)}")
print(f"Training samples: {len(X_train)}")
print(f"Testing samples: {len(X_test)}")
return X_train, X_test, y_train, y_test
def build_model(self, model_type='bidirectional'):
"""
Build the LSTM model architecture.
Args:
model_type: 'simple', 'stacked', or 'bidirectional'
"""
self.model = Sequential(name=f'{model_type}_lstm')
# Embedding layer
self.model.add(Embedding(
input_dim=self.max_words,
output_dim=self.embedding_dim,
input_length=self.max_len,
name='embedding'
))
# Spatial dropout after embedding
self.model.add(SpatialDropout1D(0.2, name='spatial_dropout'))
if model_type == 'simple':
# Simple single LSTM layer
self.model.add(LSTM(64, name='lstm'))
elif model_type == 'stacked':
# Stacked LSTM layers
self.model.add(LSTM(128, return_sequences=True, name='lstm_1'))
self.model.add(Dropout(0.3, name='dropout_1'))
self.model.add(LSTM(64, name='lstm_2'))
elif model_type == 'bidirectional':
# Bidirectional LSTM
self.model.add(Bidirectional(
LSTM(64, return_sequences=True),
name='bidirectional_1'
))
self.model.add(Dropout(0.3, name='dropout_1'))
self.model.add(Bidirectional(
LSTM(32),
name='bidirectional_2'
))
# Dense layers
self.model.add(Dropout(0.4, name='dropout_final'))
self.model.add(Dense(64, activation='relu', name='dense_1'))
self.model.add(Dropout(0.3, name='dropout_dense'))
self.model.add(Dense(1, activation='sigmoid', name='output'))
# Compile model
self.model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
print(self.model.summary())
return self.model
def train(self, X_train, y_train, X_val=None, y_val=None,
epochs=20, batch_size=64):
"""
Train the model.
Args:
X_train, y_train: Training data
X_val, y_val: Validation data (optional)
epochs: Number of training epochs
batch_size: Batch size
"""
# Callbacks
callbacks = [
EarlyStopping(
monitor='val_loss',
patience=3,
restore_best_weights=True,
verbose=1
),
ModelCheckpoint(
'best_model.keras',
monitor='val_accuracy',
save_best_only=True,
verbose=1
)
]
# Determine validation data
if X_val is not None and y_val is not None:
validation_data = (X_val, y_val)
else:
validation_data = None
# Train
self.history = self.model.fit(
X_train, y_train,
epochs=epochs,
batch_size=batch_size,
validation_split=0.15 if validation_data is None else 0.0,
validation_data=validation_data,
callbacks=callbacks,
verbose=1
)
return self.history
def evaluate(self, X_test, y_test):
"""
Evaluate the model on test data.
Args:
X_test: Test features
y_test: Test labels
Returns:
Dictionary with evaluation metrics
"""
# Get predictions
y_pred_proba = self.model.predict(X_test)
y_pred = (y_pred_proba > 0.5).astype(int).flatten()
# Calculate metrics
loss, accuracy = self.model.evaluate(X_test, y_test, verbose=0)
print("\n" + "="*50)
print("MODEL EVALUATION")
print("="*50)
print(f"Test Loss: {loss:.4f}")
print(f"Test Accuracy: {accuracy:.4f}")
print("\nClassification Report:")
print(classification_report(y_test, y_pred,
target_names=['Negative', 'Positive']))
return {
'loss': loss,
'accuracy': accuracy,
'predictions': y_pred,
'probabilities': y_pred_proba
}
def predict_sentiment(self, texts):
"""
Predict sentiment for new texts.
Args:
texts: List of text strings
Returns:
Predictions and probabilities
"""
# Preprocess
texts = self.preprocess_text(texts)
# Convert to sequences
sequences = self.tokenizer.texts_to_sequences(texts)
padded = pad_sequences(sequences, maxlen=self.max_len,
padding='post', truncating='post')
# Predict
probabilities = self.model.predict(padded, verbose=0)
predictions = (probabilities > 0.5).astype(int).flatten()
results = []
for text, pred, prob in zip(texts, predictions, probabilities):
sentiment = 'Positive' if pred == 1 else 'Negative'
confidence = prob[0] if pred == 1 else 1 - prob[0]
results.append({
'text': text[:50] + '...' if len(text) > 50 else text,
'sentiment': sentiment,
'confidence': float(confidence)
})
return results
def plot_training_history(self):
"""Plot training history."""
if self.history is None:
print("No training history available.")
return
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Accuracy plot
axes[0].plot(self.history.history['accuracy'], label='Training', linewidth=2)
axes[0].plot(self.history.history['val_accuracy'], label='Validation', linewidth=2)
axes[0].set_title('Model Accuracy', fontsize=14)
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('Accuracy')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# Loss plot
axes[1].plot(self.history.history['loss'], label='Training', linewidth=2)
axes[1].plot(self.history.history['val_loss'], label='Validation', linewidth=2)
axes[1].set_title('Model Loss', fontsize=14)
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('Loss')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('training_history.png', dpi=150)
plt.show()
def plot_confusion_matrix(self, y_true, y_pred):
"""Plot confusion matrix."""
cm = confusion_matrix(y_true, y_pred)
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=['Negative', 'Positive'],
yticklabels=['Negative', 'Positive'])
plt.title('Confusion Matrix', fontsize=14)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.tight_layout()
plt.savefig('confusion_matrix.png', dpi=150)
plt.show()
# =============================================================================
# EXAMPLE 1: Using IMDB Dataset (Built-in)
# =============================================================================
def example_with_imdb():
"""Example using the built-in IMDB dataset."""
print("="*60)
print("EXAMPLE: IMDB Movie Review Sentiment Classification")
print("="*60)
# Load IMDB dataset
from tensorflow.keras.datasets import imdb
vocab_size = 10000
max_len = 200
# Load data (already tokenized)
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=vocab_size)
print(f"Training samples: {len(X_train)}")
print(f"Testing samples: {len(X_test)}")
# Pad sequences
X_train = pad_sequences(X_train, maxlen=max_len, padding='post')
X_test = pad_sequences(X_test, maxlen=max_len, padding='post')
# Build model
model = Sequential([
Embedding(vocab_size, 128, input_length=max_len),
SpatialDropout1D(0.2),
Bidirectional(LSTM(64, return_sequences=True)),
Dropout(0.3),
Bidirectional(LSTM(32)),
Dropout(0.4),
Dense(64, activation='relu'),
Dropout(0.3),
Dense(1, activation='sigmoid')
])
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
print(model.summary())
# Train
history = model.fit(
X_train, y_train,
epochs=5,
batch_size=64,
validation_split=0.2,
callbacks=[EarlyStopping(patience=2, restore_best_weights=True)]
)
# Evaluate
loss, accuracy = model.evaluate(X_test, y_test)
print(f"\nTest Accuracy: {accuracy:.4f}")
return model, history
# =============================================================================
# EXAMPLE 2: Using Custom Dataset
# =============================================================================
def example_with_custom_data():
"""Example using custom text data."""
print("\n" + "="*60)
print("EXAMPLE: Custom Text Sentiment Classification")
print("="*60)
# Sample custom dataset
texts = [
"This movie was absolutely wonderful! I loved every moment of it.",
"Terrible experience. The service was awful and rude.",
"I'm so happy with this purchase. Highly recommended!",
"Waste of money. Very disappointed with the quality.",
"Great product! Exceeded all my expectations.",
"The worst movie I've ever seen. Complete garbage.",
"Amazing performance by the actors. A masterpiece!",
"Not worth the time. Boring and predictable plot.",
"Fantastic customer service. They resolved my issue quickly.",
"I regret buying this. Poor quality and overpriced.",
"This restaurant has the best food in town!",
"Horrible taste, never ordering from here again.",
"Such a delightful experience. Will definitely return.",
"The staff was unfriendly and unhelpful.",
"Perfect gift for my wife. She absolutely loved it!",
"Broke after one use. Total waste of money.",
"Incredible value for the price. Very satisfied.",
"Avoid at all costs. Scam product.",
"Best purchase I've made this year!",
"Extremely disappointed. Does not match the description.",
"Five stars! Would buy again without hesitation.",
"One star is too generous for this garbage.",
"Lovely atmosphere and friendly staff.",
"Never again. Lost my trust completely.",
"Exceeded my expectations in every way!",
"Complete disaster from start to finish.",
"Highly recommend to everyone!",
"Save your money and look elsewhere.",
"Outstanding quality and fast shipping.",
"Arrived damaged and customer service was unhelpful.",
] * 50 # Replicate to have more data
# Labels: 1 = positive, 0 = negative
labels = [
1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0
] * 50
# Initialize classifier
classifier = SentimentLSTM(
max_words=5000,
max_len=100,
embedding_dim=64
)
# Prepare data
X_train, X_test, y_train, y_test = classifier.prepare_data(texts, labels)
# Build model
classifier.build_model(model_type='bidirectional')
# Train model
classifier.train(X_train, y_train, epochs=10, batch_size=32)
# Evaluate
results = classifier.evaluate(X_test, y_test)
# Plot training history
classifier.plot_training_history()
# Plot confusion matrix
classifier.plot_confusion_matrix(y_test, results['predictions'])
# Test predictions on new texts
new_texts = [
"This is absolutely fantastic! I love it!",
"Terrible product. Total waste of money.",
"Pretty good overall, but could be better.",
"I would never recommend this to anyone.",
"Best thing I've ever experienced!"
]
print("\n" + "="*50)
print("PREDICTIONS ON NEW TEXTS")
print("="*50)
predictions = classifier.predict_sentiment(new_texts)
for pred in predictions:
print(f"\nText: {pred['text']}")
print(f"Sentiment: {pred['sentiment']} (Confidence: {pred['confidence']:.2%})")
return classifier
# =============================================================================
# ADVANCED: Multi-class Sentiment with Attention
# =============================================================================
class AttentionLayer(tf.keras.layers.Layer):
"""Custom Attention Layer for LSTM."""
def __init__(self, **kwargs):
super(AttentionLayer, self).__init__(**kwargs)
def build(self, input_shape):
self.W = self.add_weight(
name='attention_weight',
shape=(input_shape[-1], 1),
initializer='glorot_uniform',
trainable=True
)
self.b = self.add_weight(
name='attention_bias',
shape=(input_shape[1], 1),
initializer='zeros',
trainable=True
)
super(AttentionLayer, self).build(input_shape)
def call(self, x):
# Compute attention scores
e = tf.tanh(tf.tensordot(x, self.W, axes=1) + self.b)
a = tf.nn.softmax(e, axis=1)
output = tf.reduce_sum(x * a, axis=1)
return output
def build_lstm_with_attention(vocab_size, max_len, embedding_dim=128, num_classes=3):
"""Build LSTM model with attention mechanism."""
inputs = tf.keras.Input(shape=(max_len,))
# Embedding
x = Embedding(vocab_size, embedding_dim)(inputs)
x = SpatialDropout1D(0.2)(x)
# Bidirectional LSTM
x = Bidirectional(LSTM(64, return_sequences=True))(x)
x = Dropout(0.3)(x)
# Attention layer
x = AttentionLayer()(x)
# Dense layers
x = Dense(64, activation='relu')(x)
x = Dropout(0.4)(x)
# Output layer
if num_classes == 2:
outputs = Dense(1, activation='sigmoid')(x)
loss = 'binary_crossentropy'
else:
outputs = Dense(num_classes, activation='softmax')(x)
loss = 'sparse_categorical_crossentropy'
model = tf.keras.Model(inputs, outputs)
model.compile(optimizer='adam', loss=loss, metrics=['accuracy'])
return model
# =============================================================================
# Main execution
# =============================================================================
if __name__ == "__main__":
# Run IMDB example
print("\nRunning IMDB example...")
model_imdb, history_imdb = example_with_imdb()
# Run custom data example
print("\nRunning custom data example...")
classifier = example_with_custom_data()
# Demonstrate attention model
print("\n" + "="*60)
print("Building LSTM with Attention Mechanism")
print("="*60)
attention_model = build_lstm_with_attention(
vocab_size=10000,
max_len=200,
num_classes=2
)
print(attention_model.summary())
Model Architecture Visualization
┌─────────────────────────────────────────────────────────────┐
│ LSTM ARCHITECTURE │
├─────────────────────────────────────────────────────────────┤
│ │
│ Input Text: "This movie was great!" │
│ ↓ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ TOKENIZATION & PADDING │ │
│ │ [231, 45, 12, 897, 0, 0, 0, ... , 0] │ │
│ └─────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ EMBEDDING LAYER │ │
│ │ Converts tokens to dense vectors (128-dim) │ │
│ └─────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ SPATIAL DROPOUT (0.2) │ │
│ └─────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ BIDIRECTIONAL LSTM (64 units) │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ Forward LSTM │ │ Backward LSTM │ │ │
│ │ │ ────→ │ │ ←──── │ │ │
│ │ └─────────────────┘ └─────────────────┘ │ │
│ │ └──────────┬──────────┘ │ │
│ │ Concatenate │ │
│ └─────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ DROPOUT (0.4) │ │
│ └─────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ DENSE LAYER (64, ReLU) │ │
│ └─────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ OUTPUT LAYER (1, Sigmoid) │ │
│ │ Output: 0.92 → Positive Sentiment │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Key Components Explained
| Component | Purpose |
|---|
| Embedding | Converts word indices to dense vectors |
| SpatialDropout1D | Drops entire embedding channels (regularization) |
| LSTM | Captures sequential patterns and long-term dependencies |
| Bidirectional | Processes text forward and backward |
| Dropout | Prevents overfitting |
| Dense + Sigmoid | Binary classification output |
Installation Requirements
pip install tensorflow numpy scikit-learn matplotlib seaborn
Tips for Better Performance
- Use pretrained embeddings (GloVe, Word2Vec)
- Increase dataset size for better generalization
- Tune hyperparameters (LSTM units, dropout rates)
- Use learning rate scheduling
- Try GRU layers as a faster alternative to LSTM
This implementation provides a complete pipeline for sentiment classification with options for simple, stacked, and bidirectional LSTM architectures!