Spaces:
Paused
Paused
File size: 17,091 Bytes
f6ea7de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | import pickle
import yaml
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from collections import Counter
from wordcloud import WordCloud
from pathlib import Path
from loguru import logger
from email_spam_classifier.config import PROCESSED_DATA_DIR, FIGURES_DIR
class ExploratoryDataAnalysis:
"""
Class responsible for performing EDA on the dataset.
"""
def __init__(self, data, params):
self.data = data
self.params = params
self.figures_dir = Path(params['visualization']['figures_dir'])
self.figures_dir.mkdir(parents=True, exist_ok=True)
def save_figure(self, filename):
"""Save figure to the figures directory"""
filepath = self.figures_dir / filename
plt.savefig(filepath, bbox_inches='tight', dpi=300)
logger.info(f"Figure saved to {filepath}")
plt.close()
def show_class_distribution(self, target_column='target',
figsize=None, labels=None, autopct="%0.2f%%"):
"""Plot class distribution as a pie chart"""
logger.info("Plotting class distribution")
if figsize is None:
figsize = tuple(self.params['visualization']['class_distribution']['figsize'])
plt.figure(figsize=figsize)
plt.pie(self.data[target_column].value_counts(),
labels=labels or ['ham', 'spam'],
autopct=autopct)
plt.title("Class Distribution")
self.save_figure('class_distribution.png')
return self
def describe_features_by_class(self, target_column='target', features=None):
"""Generate descriptive statistics by class"""
logger.info("Generating descriptive statistics by class")
if features is None:
features = ['num_characters', 'num_words', 'num_sentences']
# Overall stats
print("Overall Statistics:")
print(self.data[features].describe())
# By class
for class_val in sorted(self.data[target_column].unique()):
print(f"\nClass {class_val} Statistics:")
print(self.data[self.data[target_column] == class_val][features].describe())
return self
def plot_feature_distributions(self, target_column='target', features=None):
"""Plot histograms of features by class"""
logger.info("Plotting feature distributions")
if features is None:
features = ['num_characters', 'num_words', 'num_sentences']
classes = sorted(self.data[target_column].unique())
colors = ['blue', 'red']
class_names = ['Ham', 'Spam']
figsize = tuple(self.params['visualization']['feature_distributions']['figsize'])
for feature in features:
plt.figure(figsize=figsize)
for i, (class_val, color, name) in enumerate(zip(classes, colors, class_names)):
sns.histplot(data=self.data[self.data[target_column] == class_val],
x=feature, kde=False, label=name, color=color)
plt.title(f"Distribution of {feature} by class")
plt.legend()
self.save_figure(f'distribution_{feature}.png')
return self
def plot_pairplot(self, target_column='target'):
"""Plot pairplot of numeric features"""
logger.info("Plotting pairplot")
# Get numeric columns but exclude the target column
numeric_cols = [col for col in self.data.select_dtypes(include=np.number).columns
if col != target_column and col in self.data.columns]
# Create a DataFrame with only numeric columns plus the target column
plot_df = self.data[numeric_cols + [target_column]]
# Now create the pairplot
sns.pairplot(plot_df, hue=target_column)
self.save_figure('pairplot.png')
return self
def generate_word_clouds(self, text_column='transformed_text', target_column='target',
figsize=(15, 6), classes=None):
"""Generate word clouds for each class"""
logger.info("Generating word clouds")
if classes is None:
classes = sorted(self.data[target_column].unique())
class_names = ['Ham', 'Spam']
wc_params = self.params['visualization']['word_cloud']
wc = WordCloud(
width=wc_params['width'],
height=wc_params['height'],
min_font_size=wc_params['min_font_size'],
background_color=wc_params['background_color']
)
for class_val, name in zip(classes, class_names):
text = self.data[self.data[target_column] == class_val][text_column].str.cat(sep=" ")
word_cloud = wc.generate(text)
plt.figure(figsize=figsize)
plt.imshow(word_cloud)
plt.axis('off')
plt.title(f"Word Cloud for {name} Messages")
self.save_figure(f'wordcloud_{name.lower()}.png')
return self
def plot_common_words(self, text_column='transformed_text', target_column='target',
top_n=None, figsize=None):
"""Plot most common words for each class"""
if top_n is None:
top_n = self.params['visualization']['common_words']['top_n']
if figsize is None:
figsize = tuple(self.params['visualization']['common_words']['figsize'])
logger.info(f"Plotting top {top_n} most common words")
classes = sorted(self.data[target_column].unique())
class_names = ['Ham', 'Spam']
for class_val, name in zip(classes, class_names):
corpus = []
for msg in self.data[self.data[target_column] == class_val][text_column].tolist():
for word in msg.split():
corpus.append(word)
# Convert Counter to DataFrame
common_words = pd.DataFrame(Counter(corpus).most_common(top_n),
columns=['Word', 'Count'])
plt.figure(figsize=figsize)
sns.barplot(x='Word', y='Count', data=common_words)
plt.xticks(rotation='vertical')
plt.title(f"Top {top_n} Words in {name} Messages")
plt.tight_layout()
self.save_figure(f'common_words_{name.lower()}.png')
return self
def main():
"""Main function to generate visualizations"""
# Load parameters
with open('params.yaml') as f:
params = yaml.safe_load(f)
# Load processed data
processed_data_path = PROCESSED_DATA_DIR / 'processed_data.pkl'
with open(processed_data_path, 'rb') as f:
processed_data = pickle.load(f)
# Create EDA instance and generate visualizations
eda = ExploratoryDataAnalysis(processed_data, params)
eda.show_class_distribution(target_column=params['preprocessing']['target_column']) \
.describe_features_by_class(target_column=params['preprocessing']['target_column']) \
.plot_feature_distributions(target_column=params['preprocessing']['target_column']) \
.plot_pairplot(target_column=params['preprocessing']['target_column']) \
.generate_word_clouds(
text_column='transformed_text',
target_column=params['preprocessing']['target_column']
) \
.plot_common_words(
text_column='transformed_text',
target_column=params['preprocessing']['target_column']
)
logger.success("Visualization generation complete.")
if __name__ == "__main__":
main()
"""Visualization utilities for spam classification."""
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix, roc_curve, precision_recall_curve, auc
from pathlib import Path
def plot_confusion_matrix(y_true, y_pred, save_path=None, figsize=(10, 8), title="Confusion Matrix"):
"""Plot confusion matrix with percentages."""
plt.figure(figsize=figsize)
# Create confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Calculate percentages
cm_percent = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100
# Create a DataFrame for better visualization
labels = ["Ham", "Spam"]
cm_df = pd.DataFrame(cm, index=labels, columns=labels)
cm_percent_df = pd.DataFrame(cm_percent, index=labels, columns=labels)
# Plot heatmap with annotations
ax = sns.heatmap(cm_df, annot=True, fmt="d", cmap="Blues", cbar=False)
# Add percentage annotations
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j + 0.5, i + 0.7, f"({cm_percent_df.iloc[i, j]:.1f}%)",
ha="center", va="center", fontsize=10)
plt.title(title, fontsize=15)
plt.ylabel("True Label", fontsize=12)
plt.xlabel("Predicted Label", fontsize=12)
if save_path:
plt.savefig(save_path, bbox_inches="tight", dpi=300)
return plt
def plot_roc_pr_curves(y_true, y_proba, save_path=None, figsize=(15, 6)):
"""Plot ROC and Precision-Recall curves side by side."""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
# ROC Curve
fpr, tpr, _ = roc_curve(y_true, y_proba)
roc_auc = auc(fpr, tpr)
ax1.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.3f})')
ax1.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
ax1.set_xlim([0.0, 1.0])
ax1.set_ylim([0.0, 1.05])
ax1.set_xlabel('False Positive Rate')
ax1.set_ylabel('True Positive Rate')
ax1.set_title('Receiver Operating Characteristic')
ax1.legend(loc="lower right")
# Precision-Recall Curve
precision, recall, _ = precision_recall_curve(y_true, y_proba)
pr_auc = auc(recall, precision)
ax2.plot(recall, precision, color='green', lw=2, label=f'PR curve (AUC = {pr_auc:.3f})')
ax2.set_xlim([0.0, 1.0])
ax2.set_ylim([0.0, 1.05])
ax2.set_xlabel('Recall')
ax2.set_ylabel('Precision')
ax2.set_title('Precision-Recall Curve')
ax2.legend(loc="lower left")
plt.tight_layout()
if save_path:
plt.savefig(save_path, bbox_inches="tight", dpi=300)
return plt
def plot_threshold_analysis(y_true, y_proba, save_path=None, figsize=(12, 8)):
"""Plot precision, recall, and F1 score at different threshold values."""
thresholds = np.linspace(0.01, 0.99, 100)
precision_scores = []
recall_scores = []
f1_scores = []
for threshold in thresholds:
y_pred = (y_proba >= threshold).astype(int)
# Handle division by zero
tp = ((y_true == 1) & (y_pred == 1)).sum()
fp = ((y_true == 0) & (y_pred == 1)).sum()
fn = ((y_true == 1) & (y_pred == 0)).sum()
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
precision_scores.append(precision)
recall_scores.append(recall)
f1_scores.append(f1)
plt.figure(figsize=figsize)
plt.plot(thresholds, precision_scores, 'b--', label='Precision')
plt.plot(thresholds, recall_scores, 'g-', label='Recall')
plt.plot(thresholds, f1_scores, 'r-.', label='F1 Score')
# Find optimal threshold based on F1 score
optimal_idx = np.argmax(f1_scores)
optimal_threshold = thresholds[optimal_idx]
optimal_f1 = f1_scores[optimal_idx]
plt.axvline(x=optimal_threshold, color='k', linestyle=':',
label=f'Optimal Threshold: {optimal_threshold:.2f} (F1: {optimal_f1:.3f})')
plt.axvline(x=0.5, color='gray', linestyle='--',
label='Default Threshold: 0.5')
plt.xlabel('Threshold')
plt.ylabel('Score')
plt.title('Precision, Recall, and F1 Score vs. Threshold')
plt.legend()
plt.grid(True, alpha=0.3)
if save_path:
plt.savefig(save_path, bbox_inches="tight", dpi=300)
return plt, optimal_threshold, optimal_f1
def plot_feature_importance(model, feature_names, top_n=20, save_path=None, figsize=(12, 10)):
"""
Plot feature importance for models that support feature extraction.
Works with Pipeline objects containing TF-IDF or CountVectorizer.
"""
plt.figure(figsize=figsize)
try:
# Try to extract feature importance from the model
if hasattr(model, 'named_steps'):
# Handle pipeline
if hasattr(model['classifier'], 'feature_log_prob_'):
# For Naive Bayes models
vectorizer = model['vectorizer']
classifier = model['classifier']
# Get feature names from vectorizer
if hasattr(vectorizer, 'get_feature_names_out'):
feature_names = vectorizer.get_feature_names_out()
else:
feature_names = vectorizer.get_feature_names()
# Calculate feature importance as log probability difference between spam and ham
feature_importance = classifier.feature_log_prob_[1] - classifier.feature_log_prob_[0]
# Create a DataFrame with feature names and importance
importance_df = pd.DataFrame({
'Feature': feature_names,
'Importance': feature_importance
})
# Sort by importance and get top features
importance_df = importance_df.sort_values('Importance', ascending=False)
# Plot top N spam indicators
top_spam = importance_df.head(top_n)
plt.figure(figsize=figsize)
plt.barh(top_spam['Feature'][::-1], top_spam['Importance'][::-1], color='red', alpha=0.7)
plt.xlabel('Log Probability Difference (Spam - Ham)')
plt.title(f'Top {top_n} Spam Indicators')
plt.tight_layout()
if save_path:
spam_path = Path(save_path).with_stem(Path(save_path).stem + "_spam_indicators")
plt.savefig(spam_path, bbox_inches="tight", dpi=300)
# Plot top N ham indicators
plt.figure(figsize=figsize)
top_ham = importance_df.tail(top_n).iloc[::-1]
plt.barh(top_ham['Feature'], top_ham['Importance'], color='green', alpha=0.7)
plt.xlabel('Log Probability Difference (Spam - Ham)')
plt.title(f'Top {top_n} Ham Indicators')
plt.tight_layout()
if save_path:
ham_path = Path(save_path).with_stem(Path(save_path).stem + "_ham_indicators")
plt.savefig(ham_path, bbox_inches="tight", dpi=300)
return plt
except Exception as e:
print(f"Could not extract feature importance: {e}")
return None
def analyze_misclassifications(texts, y_true, y_pred, y_proba, save_path=None):
"""
Analyze misclassified examples.
Returns a DataFrame with misclassified examples and their probabilities.
"""
# Create a DataFrame with all examples
results_df = pd.DataFrame({
'text': texts,
'true_label': y_true,
'predicted': y_pred,
'probability': y_proba,
'misclassified': y_true != y_pred
})
# Separate by misclassification type
false_positives = results_df[(results_df['true_label'] == 0) & (results_df['predicted'] == 1)]
false_negatives = results_df[(results_df['true_label'] == 1) & (results_df['predicted'] == 0)]
# Print summary
print(f"Total samples: {len(results_df)}")
print(f"Correctly classified: {len(results_df) - len(results_df[results_df['misclassified']])}")
print(f"Misclassified: {len(results_df[results_df['misclassified']])}")
print(f"False positives (Ham classified as Spam): {len(false_positives)}")
print(f"False negatives (Spam classified as Ham): {len(false_negatives)}")
# Save to CSV if path provided
if save_path:
false_positives_path = Path(save_path).with_stem(Path(save_path).stem + "_false_positives")
false_negatives_path = Path(save_path).with_stem(Path(save_path).stem + "_false_negatives")
false_positives.to_csv(false_positives_path, index=False)
false_negatives.to_csv(false_negatives_path, index=False)
print(f"False positives saved to: {false_positives_path}")
print(f"False negatives saved to: {false_negatives_path}")
return false_positives, false_negatives
|