import numpy as np
import pandas as pd
import re
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, Dropout, SpatialDropout1D
from sklearn.model_selection import train_test_split
# ==========================================
# 1. Data Preparation
# ==========================================
# FOR REAL USE: Uncomment the lines below to load your own CSV
# df = pd.read_csv('tweets.csv')
# df = df[['text', 'sentiment']] # Ensure you have specific columns
# FOR DEMONSTRATION: creating a dummy dataset
data = {
'text': [
"I love this product, it's amazing!",
"Simply the best experience ever.",
"This is terrible, I hate it.",
"Worst customer service I have ever received.",
"I am very happy with the purchase.",
"Totally disappointed, will not buy again.",
"The movie was fantastic and thrilling.",
"Boring and waste of time.",
"Feeling great about today!",
"I am so sad and depressed."
],
'sentiment': [1, 1, 0, 0, 1, 0, 1, 0, 1, 0] # 1 is Positive, 0 is Negative
}
df = pd.DataFrame(data)
print(f"Dataset sample:\n{df.head()}\n")
# ==========================================
# 2. Text Preprocessing (Cleaning)
# ==========================================
def clean_tweet(text):
"""
Removes URLs, Mentions (@user), and non-alphanumeric characters.
"""
text = text.lower()
text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE) # Remove URLs
text = re.sub(r'@\w+', '', text) # Remove mentions
text = re.sub(r'[^a-zA-Z\s]', '', text) # Remove punctuation/numbers
return text
df['cleaned_text'] = df['text'].apply(clean_tweet)
# ==========================================
# 3. Tokenization and Padding
# ==========================================
# Hyperparameters
MAX_NB_WORDS = 5000 # Most frequent words to keep
MAX_SEQUENCE_LENGTH = 50 # Max length of a tweet (truncate or pad to this)
EMBEDDING_DIM = 100 # Dimensions of the vector representation
tokenizer = Tokenizer(num_words=MAX_NB_WORDS, filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~', lower=True)
tokenizer.fit_on_texts(df['cleaned_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['cleaned_text'].values)
# Pad sequences so they are all the same length for the LSTM
X = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)
# Labels
Y = df['sentiment'].values
# Split train and test data
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# ==========================================
# 4. Building the LSTM Model
# ==========================================
model = Sequential()
# 1. Embedding Layer: Converts integer sequences to dense vectors
model.add(Embedding(MAX_NB_WORDS, EMBEDDING_DIM, input_length=X.shape[1]))
# 2. SpatialDropout1D: Helps reduce overfitting by dropping entire 1D feature maps
model.add(SpatialDropout1D(0.2))
# 3. LSTM Layer: The memory layer
model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2))
# 4. Output Layer: Single neuron with sigmoid for binary classification (0 to 1)
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
# ==========================================
# 5. Training
# ==========================================
# Increase epochs for real data (e.g., 5-10)
epochs = 10
batch_size = 2 # Small batch size because our dummy data is tiny
history = model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, validation_data=(X_test, Y_test))
# ==========================================
# 6. Evaluation and Prediction
# ==========================================
accr = model.evaluate(X_test, Y_test)
print(f'Test set\n Loss: {accr[0]:0.3f}\n Accuracy: {accr[1]:0.3f}')
def predict_sentiment(text):
cleaned = clean_tweet(text)
seq = tokenizer.texts_to_sequences([cleaned])
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
pred = model.predict(padded)
label = "POSITIVE" if pred > 0.5 else "NEGATIVE"
print(f"\nInput: '{text}'")
print(f"Sentiment: {label} (Confidence: {pred[0][0]:.4f})")
# Test on new sentences
predict_sentiment("I absolutely loved the service!")
predict_sentiment("This was a complete disaster.")