The user wants Python code to perform sentiment analysis on tweets using an LSTM (Long Short-Term Memory) model.
Key Components Required:
- Libraries: TensorFlow/Keras (for the LSTM), Pandas (for data handling), NumPy, Scikit-learn (for preprocessing/metrics), and NLTK or similar for text cleaning.
- Data Loading: A dummy dataset creation or instructions to download a real one (like the Sentiment140 dataset). For a self-contained example, generating a small synthetic dataset is safer, but mentioning how to load a CSV is crucial.
- Preprocessing (Crucial for Tweets):
- Lowercasing.
- Removing URLs, mentions (@user), hashtags (#) - though sometimes hashtags are kept.
- Removing punctuation/numbers.
- Tokenization.
- Stopword removal (optional but good).
- Padding/Truncation sequences.
- Model Architecture:
- Embedding Layer.
- LSTM Layer (or Bidirectional LSTM).
- Dense Layer (Output).
- Training: Compilation and fitting.
- Evaluation: Accuracy/Loss plots or metrics.
- Prediction: A function to test new raw strings.
Step-by-Step Implementation Plan:
- Imports:
numpy, pandas, tensorflow/keras, sklearn.
- Data Simulation: Create a small dataframe with 'text' and 'sentiment' (0 or 1) so the code runs immediately without external files.
- Text Cleaning Function: Write a regex-heavy function to clean tweets.
- Tokenization: Use
Tokenizer from Keras.
- Splitting: Train/Test split.
- Model Building:
Sequential
Embedding
LSTM (let's use Bidirectional for better performance as a standard practice).
Dense (Sigmoid for binary classification).
- Training:
model.fit.
- Inference: A helper function to take a string -> clean -> tokenize -> pad -> predict.
Refining the Code:
- Self-contained: It needs to run out of the box. I will use generated data but add comments on how to swap it for a CSV.
- Libraries: Make sure to import
re for regex cleaning.
- Hyperparameters: Define
max_words (vocab size), max_len (sequence length), embedding_dim.
Drafting the Code (Mental Check):
import pandas as pd
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, SpatialDropout1D
from sklearn.model_selection import train_test_split
# 1. Data (Simulated)
data = {'text': ["I love this!", "I hate this.", "Okay day."], 'sentiment': [1, 0, 0]}
df = pd.DataFrame(data)
# 2. Preprocessing
# ... cleaning function ...
# 3. Tokenization
tokenizer = Tokenizer()
tokenizer.fit_on_texts(df['text'].values)
X = tokenizer.texts_to_sequences(df['text'].values)
X = pad_sequences(X, maxlen=100)
# 4. Model
model = Sequential()
model.add(Embedding(vocab_size, 100, input_length=X.shape[1]))
model.add(LSTM(100))
model.add(Dense(1, activation='sigmoid'))
# ...
Addressing Tweet Specifics:
Tweets contain emojis, handles, and URLs.
- Regex:
re.sub(r'http\S+', '', text) (remove URLs).
- Regex:
re.sub(r'@\S+', '', text) (remove mentions).
Final Output Structure:
- Setup/Imports.
- Data preparation (including cleaning logic).
- Tokenization & Padding.
- LSTM Model Definition.
- Training Loop.
- Prediction function.
- Explanation of the steps.
Constraint Check:
The user asked for "Python code". It should be clean, commented, and executable.
Self-Correction during drafting:
The Sentiment140 dataset is huge (1.6M rows). Training on CPU will take a long time. For the example code, I should use a small subset or synthetic data, but explicitly mention that for real results, a large CSV should be loaded. I will stick to synthetic data for the "copy-paste run" experience, but write the code so it scales easily (e.g., using pd.read_csv).
Let's refine the architecture. A simple LSTM is fine, but Bidirectional(LSTM(...)) is standard now. I'll stick to standard LSTM to keep it simple as requested, maybe add dropout to prevent overfitting on small data.
Let's write the code.
Here is a complete Python code example to perform sentiment analysis on tweets using an LSTM (Long Short-Term Memory) model with TensorFlow/Keras.
Prerequisites
You will need to install the following libraries:
pip install tensorflow pandas numpy scikit-learn nltk
The Python Code
This script includes data generation (so you can run it immediately), text preprocessing (cleaning tweets), tokenization, and the LSTM model architecture.
import numpy as np
import pandas as pd
import re
import nltk
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, SpatialDropout1D, Bidirectional
from tensorflow.keras.callbacks import EarlyStopping
# --- 1. Setup & Data Loading ---
# Download NLTK stop words
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))
# NOTE: In a real scenario, load your dataset here.
# For demonstration, we create a dummy dataset.
data = {
'text': [
"I love this new phone! It's amazing and fast. #happy",
"This is the worst service I have ever received. Very sad.",
"The movie was okay, not great but not terrible.",
"Absolutely fantastic performance! Brava!",
"I am so disappointed with the delivery delay. #angry",
"It works as expected. Nothing special.",
"Such a beautiful day outside! enjoying the sun.",
"My computer crashed and I lost all my work. I hate this.",
"Excited about the upcoming concert! #music",
"The food was bland and the waiter was rude."
],
'sentiment': [1, 0, 1, 1, 0, 1, 1, 0, 1, 0] # 1 = Positive, 0 = Negative
}
df = pd.DataFrame(data)
print("Sample Data:")
print(df.head())
print("-" * 50)
# --- 2. Data Preprocessing ---
def clean_tweet(text):
"""
Cleans tweet text by removing:
- URLs
- Mentions (@user)
- Hashtags (keeping the text, removing #)
- Punctuation and numbers
- Stopwords
"""
text = str(text).lower()
# Remove URLs
text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
# Remove user @ references and '#' from hashtags
text = re.sub(r'\@\w+|\#', '', text)
# Remove punctuation and numbers
text = re.sub(r'[^\w\s]', '', text)
text = re.sub(r'\d+', '', text)
# Remove stopwords
text = " ".join([word for word in text.split() if word not in stop_words])
return text
df['clean_text'] = df['text'].apply(clean_tweet)
# --- 3. Tokenization & Padding ---
MAX_NB_WORDS = 5000 # Max size of vocabulary
MAX_SEQUENCE_LENGTH = 250 # Max length of a tweet (padded/truncated)
EMBEDDING_DIM = 100 # Dimension of word embeddings
tokenizer = Tokenizer(num_words=MAX_NB_WORDS, oov_token="<OOV>")
tokenizer.fit_on_texts(df['clean_text'].values)
word_index = tokenizer.word_index
print(f"Found {len(word_index)} unique tokens.")
# Convert text to sequences of integers
X = tokenizer.texts_to_sequences(df['clean_text'].values)
# Pad sequences to ensure uniform length
X = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)
# Labels
y = pd.get_dummies(df['sentiment']).values # Converts to One-Hot Encoding [0, 1] or [1, 0]
print("Shape of data tensor:", X.shape)
# --- 4. Train/Test Split ---
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# --- 5. LSTM Model Construction ---
model = Sequential()
# Embedding Layer: Maps integer indices to dense vectors
model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))
# SpatialDropout1D: Drops entire 1D feature maps (helps prevent overfitting in NLP)
model.add(SpatialDropout1D(0.2))
# LSTM Layer: 100 units
# Bidirectional allows the model to learn context from both past and future
model.add(Bidirectional(LSTM(100, dropout=0.2, recurrent_dropout=0.2)))
# Dense Output Layer
# Softmax is used because we One-Hot Encoded the labels (2 classes)
model.add(Dense(2, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
# --- 6. Training ---
epochs = 5
batch_size = 64
# EarlyStopping stops training if validation loss doesn't improve
es = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
history = model.fit(
X_train, y_train,
epochs=epochs,
batch_size=batch_size,
validation_split=0.1,
callbacks=[es]
)
# --- 7. Evaluation ---
accr = model.evaluate(X_test, y_test)
print(f"Test set\n Loss: {accr[0]}\n Accuracy: {accr[1]}")
# --- 8. Prediction on New Tweets ---
def predict_sentiment(text):
# 1. Clean
cleaned = clean_tweet(text)
# 2. Tokenize and Pad
seq = tokenizer.texts_to_sequences([cleaned])
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
# 3. Predict
pred = model.predict(padded)
# 4. Decode
# Output format: [Prob_Negative, Prob_Positive]
sentiment_classes = ['Negative', 'Positive']
predicted_class_index = np.argmax(pred)
return sentiment_classes[predicted_class_index], pred[0][predicted_class_index]
# Test with custom sentences
new_tweets = [
"The update ruined everything, I can't log in anymore.",
"What a wonderful surprise, thank you so much!"
]
print("\n--- Predictions ---")
for tweet in new_tweets:
sentiment, confidence = predict_sentiment(tweet)
print(f"Tweet: '{tweet}'")
print(f"Predicted: {sentiment} (Confidence: {confidence:.4f})\n")
Key Steps in the Code
- Preprocessing (
clean_tweet):
- Tweets are noisy. This function removes URLs, mentions (
@user), and hashtags.
- It converts everything to lowercase to reduce vocabulary size.
- Stop words (common words like "and", "the", "is") are removed because they usually don't carry sentiment weight.
- Tokenization:
- The
Tokenizer assigns a unique integer ID to every word in the dataset.
texts_to_sequences converts sentences into lists of these integers.
- Padding:
- LSTMs require inputs of a fixed length.
pad_sequences adds zeros to short sentences or cuts off long ones so every input vector is the same size (MAX_SEQUENCE_LENGTH).
- Model Architecture:
- Embedding Layer: Transforms integer IDs into dense vectors of fixed size (100 dimensions). This captures semantic meaning (e.g., "good" and "great" will have similar vectors).
- Bidirectional LSTM: This reads the text forwards and backwards. This is powerful in NLP because the context of a word depends on both the words before it and after it.
- Dense Layer: The final output layer uses
softmax activation to output a probability distribution across the classes (Positive vs Negative).
- Training:
- Uses
categorical_crossentropy loss because this is a classification problem.
EarlyStopping is used to prevent the model from overfitting (memorizing the training data).
How to use Real Data
To use real data (e.g., a CSV file):
- Replace the dummy
data dictionary creation with:
df = pd.read_csv('path/to/your/tweets.csv')
- Ensure your CSV has a text column (rename it to
text or change the code) and a label column (rename to sentiment).