The user wants me to write Python code for sentiment analysis on tweets using an LSTM (Long Short-Term Memory) model. Let me create a comprehensive example that includes:
- Data loading and preprocessing
- Text tokenization and padding
- Building an LSTM model
- Training the model
- Evaluation and prediction
I'll use TensorFlow/Keras for the LSTM model and include proper text preprocessing steps for tweets (handling mentions, hashtags, URLs, etc.).
Let me write a well-structured, educational code with comments explaining each step. # Sentiment Analysis on Tweets using LSTM
This implementation includes data preprocessing, model building, training, and evaluation.
Complete Implementation
"""
Twitter Sentiment Analysis using LSTM
=====================================
A complete pipeline for sentiment analysis on tweets using LSTM neural networks.
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
import string
from collections import Counter
# Deep Learning imports
import tensorflow as tf
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import (
Embedding, LSTM, Dense, Dropout, Bidirectional,
SpatialDropout1D, Conv1D, MaxPooling1D, GlobalMaxPooling1D,
Input, Concatenate, BatchNormalization
)
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
classification_report, confusion_matrix,
accuracy_score, f1_score, roc_curve, auc
)
import warnings
warnings.filterwarnings('ignore')
# Set random seeds for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
class TweetPreprocessor:
"""
Handles all text preprocessing for tweets.
"""
def __init__(self):
# Common contractions mapping
self.contractions = {
"won't": "will not", "can't": "cannot", "n't": " not",
"'re": " are", "'s": " is", "'d": " would", "'ll": " will",
"'ve": " have", "'m": " am", "dont": "do not",
"doesnt": "does not", "didnt": "did not", "isnt": "is not",
"wasnt": "was not", "werent": "were not", "wont": "will not",
"cant": "cannot", "couldnt": "could not", "shouldnt": "should not",
"wouldnt": "would not", "aint": "am not", "gonna": "going to",
"gotta": "got to", "wanna": "want to", "kinda": "kind of",
"lemme": "let me", "gimme": "give me"
}
# Emoticons mapping to sentiment words
self.emoticons = {
':)': 'happy', ':-)': 'happy', ':D': 'happy', ':-D': 'happy',
':P': 'playful', ':-P': 'playful', ';)': 'wink', ';-)': 'wink',
':(': 'sad', ':-(': 'sad', ":'(": 'crying', ':,(': 'crying',
':O': 'surprised', ':-O': 'surprised', '<3': 'love',
':*': 'kiss', ':-*': 'kiss', 'xD': 'laughing', 'XD': 'laughing',
':@': 'angry', '>:(': 'angry', ':|': 'neutral', ':-|': 'neutral'
}
def clean_tweet(self, text):
"""
Clean and preprocess a single tweet.
"""
if not isinstance(text, str):
return ""
# Convert to lowercase
text = text.lower()
# Replace emoticons with words
for emoticon, word in self.emoticons.items():
text = text.replace(emoticon, f' {word} ')
# Remove URLs
text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
# Remove HTML tags
text = re.sub(r'<.*?>', '', text)
# Handle mentions - replace with token or remove
text = re.sub(r'@\w+', '', text)
# Handle hashtags - keep the word, remove the #
text = re.sub(r'#(\w+)', r'\1', text)
# Expand contractions
for contraction, expansion in self.contractions.items():
text = re.sub(rf'\b{contraction}\b', expansion, text)
# Remove special characters and numbers (keep letters and spaces)
text = re.sub(r'[^a-zA-Z\s]', '', text)
# Handle repeated characters (e.g., 'happyyyyy' -> 'happy')
text = re.sub(r'(.)\1{2,}', r'\1\1', text)
# Remove extra whitespace
text = ' '.join(text.split())
return text.strip()
def preprocess_dataset(self, texts):
"""
Preprocess a list of tweets.
"""
return [self.clean_tweet(text) for text in texts]
class SentimentDataLoader:
"""
Handles loading and preparing sentiment analysis datasets.
"""
@staticmethod
def create_sample_dataset(n_samples=10000):
"""
Create a synthetic dataset for demonstration.
In practice, you would load real Twitter data.
"""
np.random.seed(42)
# Positive tweet templates
positive_templates = [
"I love this {}! Amazing experience!",
"Best {} ever! Highly recommend it!",
"So happy with my new {}! Great quality!",
"This {} is absolutely fantastic!",
"Wonderful {}! Exceeded my expectations!",
"Finally got my {} and I'm thrilled!",
"The {} was incredible! 5 stars!",
"Can't believe how good this {} is!",
"Loving every moment with my {}!",
"This {} made my day! So grateful!",
"Outstanding {}! Worth every penny!",
"The best {} I've ever experienced!",
"Brilliant {}! Everyone should try it!",
"Super impressed with this {}!",
"What a fantastic {} experience!"
]
# Negative tweet templates
negative_templates = [
"Terrible {}. Total waste of money.",
"Worst {} ever. Very disappointed.",
"I hate this {}. Complete disaster.",
"Awful {} experience. Never again.",
"This {} is horrible. Do not buy.",
"Very upset with my {}. Poor quality.",
"The {} broke immediately. Useless.",
"Regret buying this {}. Terrible.",
"Disappointed with the {}. Not worth it.",
"This {} is a scam. Avoid at all costs.",
"Frustrated with this {}. Bad service.",
"The {} was a huge letdown.",
"Absolutely hate my new {}.",
"This {} ruined my day. Horrible.",
"Never buying {} again. Trash."
]
# Topics to fill in templates
topics = [
"product", "service", "phone", "laptop", "movie", "restaurant",
"hotel", "flight", "app", "game", "book", "show", "coffee",
"pizza", "course", "experience", "purchase", "delivery"
]
tweets = []
labels = []
for _ in range(n_samples // 2):
# Generate positive tweet
template = np.random.choice(positive_templates)
topic = np.random.choice(topics)
tweets.append(template.format(topic))
labels.append(1)
# Generate negative tweet
template = np.random.choice(negative_templates)
topic = np.random.choice(topics)
tweets.append(template.format(topic))
labels.append(0)
# Shuffle the data
indices = np.random.permutation(len(tweets))
tweets = [tweets[i] for i in indices]
labels = [labels[i] for i in indices]
return pd.DataFrame({'text': tweets, 'sentiment': labels})
@staticmethod
def load_sentiment140(filepath=None):
"""
Load the Sentiment140 dataset.
Download from: http://help.sentiment140.com/for-students
"""
if filepath is None:
print("Creating sample dataset instead...")
return SentimentDataLoader.create_sample_dataset()
# Sentiment140 columns
columns = ['sentiment', 'id', 'date', 'query', 'user', 'text']
df = pd.read_csv(
filepath,
encoding='latin-1',
names=columns
)
# Convert sentiment: 0 = negative, 4 = positive -> 0, 1
df['sentiment'] = df['sentiment'].map({0: 0, 4: 1})
return df[['text', 'sentiment']]
class TextVectorizer:
"""
Handles text tokenization and sequence padding.
"""
def __init__(self, max_words=20000, max_len=100, oov_token='<OOV>'):
self.max_words = max_words
self.max_len = max_len
self.oov_token = oov_token
self.tokenizer = Tokenizer(
num_words=max_words,
oov_token=oov_token
)
self.word_index = None
def fit(self, texts):
"""
Fit the tokenizer on training texts.
"""
self.tokenizer.fit_on_texts(texts)
self.word_index = self.tokenizer.word_index
print(f"Vocabulary size: {len(self.word_index)}")
return self
def transform(self, texts):
"""
Transform texts to padded sequences.
"""
sequences = self.tokenizer.texts_to_sequences(texts)
padded = pad_sequences(
sequences,
maxlen=self.max_len,
padding='post',
truncating='post'
)
return padded
def fit_transform(self, texts):
"""
Fit and transform in one step.
"""
self.fit(texts)
return self.transform(texts)
def get_vocab_size(self):
"""
Get the vocabulary size (capped at max_words).
"""
return min(len(self.word_index) + 1, self.max_words)
class LSTMSentimentModel:
"""
LSTM-based sentiment analysis model.
"""
def __init__(self, vocab_size, embedding_dim=128, max_len=100):
self.vocab_size = vocab_size
self.embedding_dim = embedding_dim
self.max_len = max_len
self.model = None
self.history = None
def build_simple_lstm(self):
"""
Build a simple LSTM model.
"""
model = Sequential([
Embedding(
input_dim=self.vocab_size,
output_dim=self.embedding_dim,
input_length=self.max_len
),
SpatialDropout1D(0.2),
LSTM(64, dropout=0.2, recurrent_dropout=0.2),
Dense(32, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid')
])
self.model = model
return model
def build_bidirectional_lstm(self):
"""
Build a Bidirectional LSTM model.
"""
model = Sequential([
Embedding(
input_dim=self.vocab_size,
output_dim=self.embedding_dim,
input_length=self.max_len
),
SpatialDropout1D(0.3),
Bidirectional(LSTM(64, return_sequences=True, dropout=0.2)),
Bidirectional(LSTM(32, dropout=0.2)),
Dense(64, activation='relu', kernel_regularizer=l2(0.01)),
BatchNormalization(),
Dropout(0.5),
Dense(1, activation='sigmoid')
])
self.model = model
return model
def build_stacked_lstm(self):
"""
Build a stacked LSTM model.
"""
model = Sequential([
Embedding(
input_dim=self.vocab_size,
output_dim=self.embedding_dim,
input_length=self.max_len
),
SpatialDropout1D(0.2),
LSTM(128, return_sequences=True, dropout=0.2, recurrent_dropout=0.2),
LSTM(64, return_sequences=True, dropout=0.2, recurrent_dropout=0.2),
LSTM(32, dropout=0.2, recurrent_dropout=0.2),
Dense(64, activation='relu'),
Dropout(0.5),
Dense(32, activation='relu'),
Dropout(0.3),
Dense(1, activation='sigmoid')
])
self.model = model
return model
def build_cnn_lstm(self):
"""
Build a hybrid CNN-LSTM model.
"""
model = Sequential([
Embedding(
input_dim=self.vocab_size,
output_dim=self.embedding_dim,
input_length=self.max_len
),
SpatialDropout1D(0.2),
Conv1D(64, 5, activation='relu'),
MaxPooling1D(pool_size=2),
LSTM(64, dropout=0.2, recurrent_dropout=0.2),
Dense(32, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid')
])
self.model = model
return model
def build_attention_lstm(self):
"""
Build an LSTM model with attention mechanism.
"""
# Input layer
inputs = Input(shape=(self.max_len,))
# Embedding layer
x = Embedding(
input_dim=self.vocab_size,
output_dim=self.embedding_dim,
input_length=self.max_len
)(inputs)
x = SpatialDropout1D(0.2)(x)
# Bidirectional LSTM
x = Bidirectional(LSTM(64, return_sequences=True))(x)
# Simple attention mechanism
attention = Dense(1, activation='tanh')(x)
attention = tf.keras.layers.Softmax(axis=1)(attention)
x = tf.keras.layers.Multiply()([x, attention])
x = tf.keras.layers.GlobalAveragePooling1D()(x)
# Dense layers
x = Dense(64, activation='relu')(x)
x = Dropout(0.5)(x)
outputs = Dense(1, activation='sigmoid')(x)
model = Model(inputs=inputs, outputs=outputs)
self.model = model
return model
def compile_model(self, learning_rate=0.001):
"""
Compile the model with optimizer and loss function.
"""
optimizer = Adam(learning_rate=learning_rate)
self.model.compile(
optimizer=optimizer,
loss='binary_crossentropy',
metrics=['accuracy']
)
return self
def train(self, X_train, y_train, X_val, y_val,
epochs=10, batch_size=64, verbose=1):
"""
Train the model with callbacks.
"""
callbacks = [
EarlyStopping(
monitor='val_loss',
patience=3,
restore_best_weights=True,
verbose=1
),
ReduceLROnPlateau(
monitor='val_loss',
factor=0.5,
patience=2,
min_lr=1e-7,
verbose=1
),
ModelCheckpoint(
'best_sentiment_model.keras',
monitor='val_accuracy',
save_best_only=True,
verbose=1
)
]
self.history = self.model.fit(
X_train, y_train,
validation_data=(X_val, y_val),
epochs=epochs,
batch_size=batch_size,
callbacks=callbacks,
verbose=verbose
)
return self.history
def evaluate(self, X_test, y_test):
"""
Evaluate the model on test data.
"""
loss, accuracy = self.model.evaluate(X_test, y_test, verbose=0)
return {'loss': loss, 'accuracy': accuracy}
def predict(self, X):
"""
Make predictions.
"""
return self.model.predict(X, verbose=0)
def predict_classes(self, X, threshold=0.5):
"""
Make class predictions.
"""
predictions = self.predict(X)
return (predictions > threshold).astype(int).flatten()
def summary(self):
"""
Print model summary.
"""
return self.model.summary()
class SentimentAnalyzer:
"""
Complete sentiment analysis pipeline.
"""
def __init__(self, max_words=20000, max_len=100, embedding_dim=128):
self.max_words = max_words
self.max_len = max_len
self.embedding_dim = embedding_dim
self.preprocessor = TweetPreprocessor()
self.vectorizer = TextVectorizer(max_words, max_len)
self.model = None
self.X_train = None
self.X_test = None
self.y_train = None
self.y_test = None
def prepare_data(self, texts, labels, test_size=0.2):
"""
Prepare data for training.
"""
print("Preprocessing tweets...")
cleaned_texts = self.preprocessor.preprocess_dataset(texts)
# Split data
X_train_text, X_test_text, self.y_train, self.y_test = train_test_split(
cleaned_texts, labels, test_size=test_size, random_state=42, stratify=labels
)
print("Vectorizing text...")
# Fit vectorizer on training data only
self.X_train = self.vectorizer.fit_transform(X_train_text)
self.X_test = self.vectorizer.transform(X_test_text)
# Convert labels to numpy arrays
self.y_train = np.array(self.y_train)
self.y_test = np.array(self.y_test)
print(f"Training samples: {len(self.X_train)}")
print(f"Test samples: {len(self.X_test)}")
return self
def build_model(self, model_type='bidirectional'):
"""
Build the specified model type.
"""
vocab_size = self.vectorizer.get_vocab_size()
self.model = LSTMSentimentModel(
vocab_size=vocab_size,
embedding_dim=self.embedding_dim,
max_len=self.max_len
)
if model_type == 'simple':
self.model.build_simple_lstm()
elif model_type == 'bidirectional':
self.model.build_bidirectional_lstm()
elif model_type == 'stacked':
self.model.build_stacked_lstm()
elif model_type == 'cnn_lstm':
self.model.build_cnn_lstm()
elif model_type == 'attention':
self.model.build_attention_lstm()
else:
raise ValueError(f"Unknown model type: {model_type}")
self.model.compile_model()
print(f"\n{model_type.upper()} Model built successfully!")
self.model.summary()
return self
def train_model(self, epochs=10, batch_size=64, validation_split=0.1):
"""
Train the model.
"""
# Create validation split from training data
X_train, X_val, y_train, y_val = train_test_split(
self.X_train, self.y_train,
test_size=validation_split,
random_state=42
)
print("\nTraining model...")
history = self.model.train(
X_train, y_train,
X_val, y_val,
epochs=epochs,
batch_size=batch_size
)
return history
def evaluate_model(self):
"""
Comprehensive model evaluation.
"""
print("\n" + "="*50)
print("MODEL EVALUATION")
print("="*50)
# Get predictions
y_pred_prob = self.model.predict(self.X_test).flatten()
y_pred = (y_pred_prob > 0.5).astype(int)
# Basic metrics
metrics = self.model.evaluate(self.X_test, self.y_test)
print(f"\nTest Loss: {metrics['loss']:.4f}")
print(f"Test Accuracy: {metrics['accuracy']:.4f}")
# F1 Score
f1 = f1_score(self.y_test, y_pred)
print(f"F1 Score: {f1:.4f}")
# Classification Report
print("\nClassification Report:")
print(classification_report(
self.y_test, y_pred,
target_names=['Negative', 'Positive']
))
return {
'loss': metrics['loss'],
'accuracy': metrics['accuracy'],
'f1_score': f1,
'y_pred': y_pred,
'y_pred_prob': y_pred_prob
}
def predict_sentiment(self, texts):
"""
Predict sentiment for new texts.
"""
if isinstance(texts, str):
texts = [texts]
# Preprocess
cleaned_texts = self.preprocessor.preprocess_dataset(texts)
# Vectorize
sequences = self.vectorizer.transform(cleaned_texts)
# Predict
predictions = self.model.predict(sequences).flatten()
results = []
for text, pred in zip(texts, predictions):
sentiment = 'Positive' if pred > 0.5 else 'Negative'
confidence = pred if pred > 0.5 else 1 - pred
results.append({
'text': text,
'sentiment': sentiment,
'confidence': float(confidence),
'raw_score': float(pred)
})
return results
class Visualizer:
"""
Visualization utilities for sentiment analysis.
"""
@staticmethod
def plot_training_history(history):
"""
Plot training and validation metrics.
"""
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Accuracy plot
axes[0].plot(history.history['accuracy'], label='Training', linewidth=2)
axes[0].plot(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(loc='lower right')
axes[0].grid(True, alpha=0.3)
# Loss plot
axes[1].plot(history.history['loss'], label='Training', linewidth=2)
axes[1].plot(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(loc='upper right')
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('training_history.png', dpi=300, bbox_inches='tight')
plt.show()
@staticmethod
def plot_confusion_matrix(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=300, bbox_inches='tight')
plt.show()
@staticmethod
def plot_roc_curve(y_true, y_pred_prob):
"""
Plot ROC curve.
"""
fpr, tpr, _ = roc_curve(y_true, y_pred_prob)
roc_auc = auc(fpr, tpr)
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, color='darkorange', lw=2,
label=f'ROC curve (AUC = {roc_auc:.3f})')
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend(loc='lower right')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('roc_curve.png', dpi=300, bbox_inches='tight')
plt.show()
@staticmethod
def plot_prediction_distribution(y_pred_prob):
"""
Plot distribution of prediction probabilities.
"""
plt.figure(figsize=(10, 5))
plt.hist(y_pred_prob, bins=50, edgecolor='black', alpha=0.7)
plt.axvline(x=0.5, color='red', linestyle='--', linewidth=2,
label='Decision boundary')
plt.xlabel('Predicted Probability (Positive)')
plt.ylabel('Frequency')
plt.title('Distribution of Prediction Probabilities')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('prediction_distribution.png', dpi=300, bbox_inches='tight')
plt.show()
def main():
"""
Main function to run the sentiment analysis pipeline.
"""
print("="*60)
print("TWITTER SENTIMENT ANALYSIS USING LSTM")
print("="*60)
# Configuration
CONFIG = {
'max_words': 20000, # Vocabulary size
'max_len': 100, # Maximum sequence length
'embedding_dim': 128, # Embedding dimension
'epochs': 10, # Training epochs
'batch_size': 64, # Batch size
'model_type': 'bidirectional' # Model architecture
}
# Load data
print("\n1. Loading data...")
data_loader = SentimentDataLoader()
df = data_loader.create_sample_dataset(n_samples=10000)
print(f"Dataset shape: {df.shape}")
print(f"Sentiment distribution:\n{df['sentiment'].value_counts()}")
print(f"\nSample tweets:")
print(df.head())
# Initialize analyzer
print("\n2. Initializing sentiment analyzer...")
analyzer = SentimentAnalyzer(
max_words=CONFIG['max_words'],
max_len=CONFIG['max_len'],
embedding_dim=CONFIG['embedding_dim']
)
# Prepare data
print("\n3. Preparing data...")
analyzer.prepare_data(
texts=df['text'].tolist(),
labels=df['sentiment'].tolist()
)
# Build model
print(f"\n4. Building {CONFIG['model_type']} model...")
analyzer.build_model(model_type=CONFIG['model_type'])
# Train model
print("\n5. Training model...")
history = analyzer.train_model(
epochs=CONFIG['epochs'],
batch_size=CONFIG['batch_size']
)
# Evaluate model
print("\n6. Evaluating model...")
results = analyzer.evaluate_model()
# Visualizations
print("\n7. Generating visualizations...")
Visualizer.plot_training_history(history)
Visualizer.plot_confusion_matrix(analyzer.y_test, results['y_pred'])
Visualizer.plot_roc_curve(analyzer.y_test, results['y_pred_prob'])
Visualizer.plot_prediction_distribution(results['y_pred_prob'])
# Test on new tweets
print("\n8. Testing on new tweets...")
test_tweets = [
"I absolutely love this product! Best purchase ever!",
"This is terrible. Waste of money. Never buying again.",
"Pretty good overall, some minor issues but satisfied.",
"Worst experience of my life. Horrible customer service.",
"Amazing quality! Exceeded all my expectations!",
"Not what I expected. Very disappointed.",
"The best thing I've bought this year! So happy!",
"Complete garbage. Don't waste your time."
]
print("\nPredictions on new tweets:")
print("-" * 60)
predictions = analyzer.predict_sentiment(test_tweets)
for pred in predictions:
print(f"Tweet: {pred['text'][:50]}...")
print(f" → Sentiment: {pred['sentiment']} "
f"(Confidence: {pred['confidence']:.2%})")
print()
print("\n" + "="*60)
print("ANALYSIS COMPLETE!")
print("="*60)
return analyzer, results
if __name__ == "__main__":
analyzer, results = main()
Usage with Real Data
# Using with Sentiment140 dataset
# Download from: http://help.sentiment140.com/for-students
# Load real Twitter data
df = pd.read_csv(
'training.1600000.processed.noemoticon.csv',
encoding='latin-1',
names=['sentiment', 'id', 'date', 'query', 'user', 'text']
)
# Convert labels (0=negative, 4=positive -> 0, 1)
df['sentiment'] = df['sentiment'].map({0: 0, 4: 1})
# Use a subset for faster training
df_sample = df.sample(n=100000, random_state=42)
# Initialize and train
analyzer = SentimentAnalyzer(max_words=30000, max_len=150)
analyzer.prepare_data(df_sample['text'].tolist(), df_sample['sentiment'].tolist())
analyzer.build_model(model_type='attention')
analyzer.train_model(epochs=15, batch_size=128)
Key Features
| Component | Description |
|---|
| Preprocessing | URL removal, mention handling, emoticon mapping, contraction expansion |
| Models | Simple LSTM, Bidirectional, Stacked, CNN-LSTM, Attention |
| Callbacks | Early stopping, learning rate reduction, model checkpointing |
| Visualization | Training curves, confusion matrix, ROC curve |
Model Architectures
Simple LSTM: Embedding → LSTM → Dense → Output
Bidirectional: Embedding → BiLSTM → BiLSTM → Dense → Output
Stacked: Embedding → LSTM → LSTM → LSTM → Dense → Output
CNN-LSTM: Embedding → Conv1D → MaxPool → LSTM → Dense → Output
Attention: Embedding → BiLSTM → Attention → Dense → Output
This implementation provides a complete, production-ready sentiment analysis pipeline that can be easily adapted to your specific dataset and requirements.