Designing tweet preprocessing
I'm thinking about including basic tweet preprocessing steps like removing URLs, mentions, and hashtags—nothing too advanced. For data loading, I'll recommend using pandas and expect 'tweets.csv' with 'text' and 'label' columns.
For preprocessing, I’ll clean text using regular expressions, split the data into train/test sets, and use Keras for tokenization and padding. We'll define hyperparameters like max_features and maxlen, and build an LSTM model with necessary configurations. I need to remind users to install any required libraries as well!Creating a cohesive script
I'm planning to provide a single, cohesive script while including an optional note for customization. I need to make sure the code uses tf.keras. I’ll design it stepwise, assuming a CSV format with 'text' and 'label' columns. For the configuration, I'll set 'max_words' to 20,000 and 'max_len' to 40, along with an 'embedding_dim' of 128.
I’ll include a clean_tweet function to remove URLs, mentions, hashtags, digits, and punctuation—keeping it lowercase without stopwords since they add unnecessary complexity. Using tf.keras.preprocessing.text.Tokenizer and pad_sequences should work well without getting too complicated.Drafting the full script
I’m thinking we won’t directly call from tensorflow.keras.preprocessing.sequence import pad_sequences. I’ll list the necessary imports for the full script:
import re
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout, Bidirectional
from tensorflow.keras.callbacks import EarlyStopping
Next, I’ll define the clean_tweet function, load the data with df = pd.read_csv("tweets.csv"), and comment on the sample structure. I'll set up X and y, apply the clean function, and split the data into training and testing sets. After fitting the Tokenizer and converting to sequences, I’ll build the model and add callbacks for EarlyStopping. Finally, I’ll ensure y is converted to numpy arrays as 'float32' before training and evaluating. Let's finalize this! ```python
"""
Sentiment analysis on tweets using an LSTM model (TensorFlow / Keras).
Assumes you have a CSV file 'tweets.csv' with at least:
text - the tweet string
label - sentiment (e.g. 0 = negative, 1 = positive)
Install dependencies first:
pip install tensorflow pandas scikit-learn
"""
import re
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
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, Bidirectional
from tensorflow.keras.callbacks import EarlyStopping
-----------------------
1. Load and inspect data
-----------------------
Example CSV structure:
text,label
"I love this movie!",1
"This is terrible...",0
df = pd.read_csv("tweets.csv")
Make sure expected columns exist
assert "text" in df.columns and "label" in df.columns,
"CSV must contain 'text' and 'label' columns."
Optional: drop rows with missing values
df = df.dropna(subset=["text", "label"]).reset_index(drop=True)
-----------------------
2. Basic tweet cleaning
-----------------------
def clean_tweet(text: str) -> str:
text = text.lower()
# Remove URLs
text = re.sub(r"http\S+|www\S+|https\S+", "", text)
# Remove mentions and hashtags (keep hashtag text if you want by removing '#')
text = re.sub(r"@\w+", "", text)
text = re.sub(r"#", "", text)
# Remove HTML entities
text = re.sub(r"&\w+;", " ", text)
# Remove numbers and non-letter characters (except basic punctuation)
text = re.sub(r"[^a-zA-Z\s!?']", " ", text)
# Collapse multiple spaces
text = re.sub(r"\s+", " ", text).strip()
return text
df["clean_text"] = df["text"].astype(str).apply(clean_tweet)
X = df["clean_text"].values
y = df["label"].values.astype("float32")
-----------------------
3. Train/validation/test split
-----------------------
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.15, random_state=42, stratify=y
)
X_train, X_val, y_train, y_val = train_test_split(
X_train, y_train, test_size=0.15, random_state=42, stratify=y_train
)
-----------------------
4. Tokenization and padding
-----------------------
max_words = 20000 # size of vocabulary
max_len = 40 # max tweet length in tokens
embedding_dim = 128 # embedding dimension
tokenizer = Tokenizer(num_words=max_words, oov_token="")
tokenizer.fit_on_texts(X_train)
def texts_to_padded_seqs(texts):
seqs = tokenizer.texts_to_sequences(texts)
padded = pad_sequences(seqs, maxlen=max_len, padding="post", truncating="post")
return padded
X_train_seq = texts_to_padded_seqs(X_train)
X_val_seq = texts_to_padded_seqs(X_val)
X_test_seq = texts_to_padded_seqs(X_test)
-----------------------
5. Build LSTM model
-----------------------
model = Sequential([
Embedding(input_dim=max_words,
output_dim=embedding_dim,
input_length=max_len),
Bidirectional(LSTM(64, return_sequences=False, dropout=0.3, recurrent_dropout=0.3)),
Dropout(0.3),
Dense(32, activation="relu"),
Dropout(0.3),
Dense(1, activation="sigmoid") # binary sentiment output
])
model.compile(
loss="binary_crossentropy",
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
metrics=["accuracy"]
)
model.summary()
-----------------------
6. Train
-----------------------
batch_size = 64
epochs = 10
early_stop = EarlyStopping(
monitor="val_loss",
patience=3,
restore_best_weights=True
)
history = model.fit(
X_train_seq,
y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(X_val_seq, y_val),
callbacks=[early_stop],
verbose=1
)
-----------------------
7. Evaluate on test set
-----------------------
test_loss, test_acc = model.evaluate(X_test_seq, y_test, verbose=0)
print(f"Test loss: {test_loss:.4f} | Test accuracy: {test_acc:.4f}")
-----------------------
8. Use model for prediction
-----------------------
def predict_sentiment(texts):
"""
texts: list of raw tweet strings
returns: list of (probability, label) where label is 0 or 1
"""
cleaned = [clean_tweet(t) for t in texts]
seqs = texts_to_padded_seqs(cleaned)
probs = model.predict(seqs).ravel()
labels = (probs >= 0.5).astype(int)
return list(zip(probs, labels))
if name == "main":
sample_tweets = [
"I absolutely love this! Best thing ever.",
"This is the worst experience I've had.",
"It's ok, could be better but not terrible."
]
results = predict_sentiment(sample_tweets)
for tweet, (prob, label) in zip(sample_tweets, results):
sentiment = "positive" if label == 1 else "negative"
print(f"\nTweet: {tweet}")
print(f"Predicted sentiment: {sentiment} (prob={prob:.3f})")