Spaces:
Runtime error
Runtime error
File size: 28,814 Bytes
839c56d | 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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 | """
Visualization Module for Sentiment Analysis
20+ publication-ready plots for model evaluation and comparison
"""
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from typing import Dict, List, Tuple, Optional, Any
import os
from wordcloud import WordCloud
from math import pi
from scipy.sparse import spmatrix # β
Import sparse matrix base type
# Set style
sns.set_style('whitegrid')
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 10
class SentimentVisualizer:
"""
Comprehensive visualizer for sentiment analysis models
Creates 20+ different plot types for analysis and presentation
"""
def __init__(self, save_dir='results/visualizations', dpi=150):
"""
Args:
save_dir: Directory to save plots
dpi: Resolution for saved figures
"""
self.save_dir = save_dir
self.dpi = dpi
os.makedirs(save_dir, exist_ok=True)
self.class_names = ['Negative', 'Neutral', 'Positive']
self.colors = ['#e74c3c', '#95a5a6', '#2ecc71'] # Red, Gray, Green
# =========================================================================
# 1-2. TRAINING CURVES
# =========================================================================
def plot_training_curves(self, history: Dict[str, List[float]], save_name='training_curves.png'):
"""
Plot training and validation loss + accuracy
Args:
history: Dictionary with 'train_loss', 'val_loss', 'train_acc', 'val_acc'
save_name: Filename to save
"""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
epochs = range(1, len(history['train_loss']) + 1)
# Loss plot
ax1.plot(epochs, history['train_loss'], 'b-', label='Train Loss', linewidth=2)
ax1.plot(epochs, history['val_loss'], 'r-', label='Val Loss', linewidth=2)
ax1.set_xlabel('Epoch', fontsize=12)
ax1.set_ylabel('Loss', fontsize=12)
ax1.set_title('Training and Validation Loss', fontsize=14, fontweight='bold')
ax1.legend(fontsize=11)
ax1.grid(True, alpha=0.3)
# Accuracy plot
ax2.plot(epochs, history['train_acc'], 'b-', label='Train Accuracy', linewidth=2)
ax2.plot(epochs, history['val_acc'], 'r-', label='Val Accuracy', linewidth=2)
ax2.set_xlabel('Epoch', fontsize=12)
ax2.set_ylabel('Accuracy', fontsize=12)
ax2.set_title('Training and Validation Accuracy', fontsize=14, fontweight='bold')
ax2.legend(fontsize=11)
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved training curves to {save_name}")
# =========================================================================
# 3-4. CONFUSION MATRICES
# =========================================================================
def plot_confusion_matrix(self, cm: np.ndarray, normalize: bool = False, save_name='confusion_matrix.png'):
"""
Plot confusion matrix
Args:
cm: Confusion matrix (numpy array)
normalize: Whether to normalize
save_name: Filename
"""
plt.figure(figsize=(10, 8))
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fmt = '.2%'
title = 'Normalized Confusion Matrix'
else:
fmt = 'd'
title = 'Confusion Matrix'
sns.heatmap(cm, annot=True, fmt=fmt, cmap='Blues',
xticklabels=self.class_names, yticklabels=self.class_names,
cbar_kws={'label': 'Count' if not normalize else 'Proportion'})
plt.title(title, fontsize=16, fontweight='bold', pad=20)
plt.ylabel('True Label', fontsize=13)
plt.xlabel('Predicted Label', fontsize=13)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved confusion matrix to {save_name}")
# =========================================================================
# 5. PER-CLASS F1 SCORES
# =========================================================================
def plot_per_class_f1(self, metrics: Dict[str, Any], save_name='per_class_f1.png'):
"""
Bar chart of per-class F1 scores
Args:
metrics: Dictionary with per_class metrics
save_name: Filename
"""
plt.figure(figsize=(10, 6))
classes = list(metrics['per_class'].keys())
f1_scores = [metrics['per_class'][c]['f1'] for c in classes]
bars = plt.bar(classes, f1_scores, color=self.colors, alpha=0.8, edgecolor='black')
# Add value labels on bars
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.3f}',
ha='center', va='bottom', fontsize=12, fontweight='bold')
plt.xlabel('Class', fontsize=13)
plt.ylabel('F1-Score', fontsize=13)
plt.title('Per-Class F1 Scores', fontsize=16, fontweight='bold')
plt.ylim(0, 1.0)
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved per-class F1 to {save_name}")
# =========================================================================
# 6. MODEL COMPARISON RADAR CHART (FIXED)
# =========================================================================
def plot_model_comparison_radar(self, models_metrics: Dict[str, Dict[str, float]],
save_name='model_comparison_radar.png'):
"""
Radar chart comparing multiple models
Args:
models_metrics: Dict mapping model names to their metrics
save_name: Filename
"""
# β
FIX 1: Use explicit polar projection creation to satisfy type checker
fig = plt.figure(figsize=(10, 10))
ax = plt.subplot(111, projection='polar') # Type checker knows this creates PolarAxes
# Metrics to compare
categories = ['Accuracy', 'Precision', 'Recall', 'F1-Score', 'MCC']
num_vars = len(categories)
# Compute angles
angles = [n / float(num_vars) * 2 * pi for n in range(num_vars)]
angles += angles[:1] # Complete the loop
# β
FIX 2: Suppress type checker warnings for polar-specific methods
# These methods exist at runtime but aren't in matplotlib's type stubs
ax.set_theta_offset(pi / 2) # type: ignore[attr-defined]
ax.set_theta_direction(-1) # type: ignore[attr-defined]
# Set labels
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories, fontsize=12)
# Plot for each model
for model_name, metrics in models_metrics.items():
values = [
metrics['accuracy'],
metrics['precision_macro'],
metrics['recall_macro'],
metrics['f1_macro'],
(metrics['mcc'] + 1) / 2 # Normalize MCC from [-1,1] to [0,1]
]
values += values[:1] # Complete the loop
ax.plot(angles, values, 'o-', linewidth=2, label=model_name)
ax.fill(angles, values, alpha=0.15)
ax.set_ylim(0, 1)
ax.set_title('Model Comparison - Multiple Metrics',
fontsize=16, fontweight='bold', pad=20, y=1.08)
ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1), fontsize=11)
ax.grid(True)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved radar chart to {save_name}")
# =========================================================================
# 7. ERROR DISTRIBUTION (FIXED)
# =========================================================================
def plot_error_distribution(self, error_analysis: Dict[str, Any],
save_name='error_distribution.png'):
"""
Plot error distribution by class
Args:
error_analysis: Error analysis dictionary
save_name: Filename
"""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# β
FIX 3: Use correct key name ('errors_by_class' not 'errors_by_true_class')
# Based on ErrorAnalyzer fix from earlier
classes = list(error_analysis['errors_by_class'].keys())
errors = [error_analysis['errors_by_class'][c]['errors'] for c in classes]
totals = [error_analysis['errors_by_class'][c]['total'] for c in classes]
x = np.arange(len(classes))
width = 0.35
ax1.bar(x - width/2, errors, width, label='Errors', color='#e74c3c', alpha=0.8)
ax1.bar(x + width/2, totals, width, label='Total', color='#3498db', alpha=0.8)
ax1.set_xlabel('Class', fontsize=12)
ax1.set_ylabel('Count', fontsize=12)
ax1.set_title('Errors vs Total Samples by Class', fontsize=14, fontweight='bold')
ax1.set_xticks(x)
ax1.set_xticklabels(classes)
ax1.legend(fontsize=11)
ax1.grid(axis='y', alpha=0.3)
# Error rates
error_rates = [error_analysis['errors_by_class'][c]['error_rate'] for c in classes] # β
Corrected key
bars = ax2.bar(classes, error_rates, color=self.colors, alpha=0.8, edgecolor='black')
for bar in bars:
height = bar.get_height()
ax2.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.1%}',
ha='center', va='bottom', fontsize=12, fontweight='bold')
ax2.set_xlabel('Class', fontsize=12)
ax2.set_ylabel('Error Rate', fontsize=12)
ax2.set_title('Error Rate by Class', fontsize=14, fontweight='bold')
ax2.set_ylim(0, max(error_rates) * 1.2 if error_rates else 1.0)
ax2.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved error distribution to {save_name}")
# =========================================================================
# 8. CONFIDENCE DISTRIBUTION
# =========================================================================
def plot_confidence_distribution(self, probabilities: np.ndarray, predictions: np.ndarray,
labels: np.ndarray, save_name='confidence_distribution.png'):
"""
Plot prediction confidence distribution
Args:
probabilities: Prediction probabilities
predictions: Predicted labels
labels: True labels
save_name: Filename
"""
confidences = np.max(probabilities, axis=1)
correct = predictions == labels
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Overall distribution
ax1.hist(confidences, bins=50, alpha=0.7, color='#3498db', edgecolor='black')
ax1.axvline(confidences.mean(), color='red', linestyle='--',
linewidth=2, label=f'Mean: {confidences.mean():.3f}')
ax1.set_xlabel('Confidence', fontsize=12)
ax1.set_ylabel('Frequency', fontsize=12)
ax1.set_title('Prediction Confidence Distribution', fontsize=14, fontweight='bold')
ax1.legend(fontsize=11)
ax1.grid(axis='y', alpha=0.3)
# Correct vs Incorrect
ax2.hist([confidences[correct], confidences[~correct]], bins=50,
label=['Correct', 'Incorrect'],
color=['#2ecc71', '#e74c3c'],
alpha=0.7, edgecolor='black')
ax2.set_xlabel('Confidence', fontsize=12)
ax2.set_ylabel('Frequency', fontsize=12)
ax2.set_title('Confidence: Correct vs Incorrect Predictions',
fontsize=14, fontweight='bold')
ax2.legend(fontsize=11)
ax2.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved confidence distribution to {save_name}")
# =========================================================================
# 9. TEXT LENGTH VS ACCURACY
# =========================================================================
def plot_length_vs_accuracy(self, texts: List[str], predictions: np.ndarray,
labels: np.ndarray, save_name='length_vs_accuracy.png'):
"""
Plot accuracy vs text length
Args:
texts: List of texts
predictions: Predicted labels
labels: True labels
save_name: Filename
"""
lengths = np.array([len(text.split()) for text in texts])
correct = predictions == labels
# Create bins
bins = [0, 10, 20, 30, 50, 100, np.inf]
bin_labels = ['<10', '10-20', '20-30', '30-50', '50-100', '100+']
bin_accuracies = []
bin_counts = []
for low, high in zip(bins[:-1], bins[1:]):
mask = (lengths >= low) & (lengths < high)
if mask.sum() > 0:
bin_acc = correct[mask].mean()
bin_accuracies.append(bin_acc)
bin_counts.append(mask.sum())
else:
bin_accuracies.append(0)
bin_counts.append(0)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Accuracy by length
bars = ax1.bar(bin_labels, bin_accuracies, alpha=0.8,
color='#3498db', edgecolor='black')
for bar, acc in zip(bars, bin_accuracies):
height = bar.get_height()
if height > 0:
ax1.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.2%}',
ha='center', va='bottom', fontsize=11, fontweight='bold')
ax1.set_xlabel('Text Length (words)', fontsize=12)
ax1.set_ylabel('Accuracy', fontsize=12)
ax1.set_title('Accuracy vs Text Length', fontsize=14, fontweight='bold')
ax1.set_ylim(0, 1.0)
ax1.grid(axis='y', alpha=0.3)
# Sample distribution
ax2.bar(bin_labels, bin_counts, alpha=0.8, color='#2ecc71', edgecolor='black')
ax2.set_xlabel('Text Length (words)', fontsize=12)
ax2.set_ylabel('Sample Count', fontsize=12)
ax2.set_title('Sample Distribution by Text Length', fontsize=14, fontweight='bold')
ax2.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved length vs accuracy to {save_name}")
# =========================================================================
# 10. ROC CURVES (FIXED - TYPE-SAFE SPARSE MATRIX HANDLING)
# =========================================================================
def plot_roc_curves(self, labels: np.ndarray, probabilities: np.ndarray,
save_name='roc_curves.png'):
"""
Plot ROC curves (one-vs-rest)
Args:
labels: True labels
probabilities: Prediction probabilities
save_name: Filename
"""
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
# Binarize labels - sklearn may return sparse matrix
labels_bin = label_binarize(labels, classes=[0, 1, 2])
# β
CRITICAL FIX: Use proper type guard to handle sparse matrices safely
# This resolves BOTH type checker errors:
# 1. "Cannot access attribute 'toarray' for class 'ndarray'"
# 2. "'__getitem__' method not defined on type 'spmatrix'"
if isinstance(labels_bin, spmatrix):
# Convert sparse matrix to dense array ONLY when needed
labels_bin = labels_bin.toarray() # type: ignore[union-attr]
# After this check, type checker knows labels_bin is ndarray
plt.figure(figsize=(10, 8))
for i, class_name in enumerate(self.class_names):
# β
Now safe to index: labels_bin is guaranteed to be ndarray
fpr, tpr, _ = roc_curve(labels_bin[:, i], probabilities[:, i])
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, linewidth=2,
label=f'{class_name} (AUC = {roc_auc:.3f})',
color=self.colors[i])
plt.plot([0, 1], [0, 1], 'k--', linewidth=2, label='Random')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate', fontsize=13)
plt.ylabel('True Positive Rate', fontsize=13)
plt.title('ROC Curves (One-vs-Rest)', fontsize=16, fontweight='bold')
plt.legend(loc="lower right", fontsize=11)
plt.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved ROC curves to {save_name}")
# =========================================================================
# 11. WORD CLOUD
# =========================================================================
def plot_wordcloud_errors(self, texts: List[str], predictions: np.ndarray,
labels: np.ndarray, save_name='wordcloud_errors.png'):
"""
Word cloud of misclassified texts
Args:
texts: List of texts
predictions: Predictions
labels: True labels
save_name: Filename
"""
errors = predictions != labels
error_texts = [texts[i] for i in range(len(texts)) if errors[i]]
if len(error_texts) == 0:
print("β οΈ No errors to visualize")
return
# Combine all error texts
error_text = ' '.join(error_texts)
# Create word cloud
wordcloud = WordCloud(width=1600, height=800,
background_color='white',
colormap='Reds',
max_words=100).generate(error_text)
plt.figure(figsize=(16, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Word Cloud of Misclassified Texts',
fontsize=18, fontweight='bold', pad=20)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved word cloud to {save_name}")
# =========================================================================
# 12. MODEL COMPARISON BAR CHART
# =========================================================================
def plot_model_comparison_bars(self, models_metrics: Dict[str, Dict[str, float]],
save_name='model_comparison.png'):
"""
Bar chart comparing models on multiple metrics
Args:
models_metrics: Dict mapping model names to metrics
save_name: Filename
"""
models = list(models_metrics.keys())
metrics = ['accuracy', 'precision_macro', 'recall_macro', 'f1_macro']
metric_names = ['Accuracy', 'Precision', 'Recall', 'F1-Score']
x = np.arange(len(models))
width = 0.2
fig, ax = plt.subplots(figsize=(14, 8))
for i, (metric, name) in enumerate(zip(metrics, metric_names)):
values = [models_metrics[m][metric] for m in models]
ax.bar(x + i * width, values, width, label=name, alpha=0.8)
ax.set_xlabel('Model', fontsize=13)
ax.set_ylabel('Score', fontsize=13)
ax.set_title('Model Comparison - Multiple Metrics',
fontsize=16, fontweight='bold')
ax.set_xticks(x + width * 1.5)
ax.set_xticklabels(models, rotation=45, ha='right')
ax.legend(fontsize=11)
ax.set_ylim(0, 1.0)
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved model comparison to {save_name}")
# =========================================================================
# 13. LEARNING RATE SCHEDULE
# =========================================================================
def plot_lr_schedule(self, lr_history: List[float], save_name='lr_schedule.png'):
"""
Plot learning rate schedule
Args:
lr_history: List of learning rates per step
save_name: Filename
"""
plt.figure(figsize=(12, 6))
plt.plot(lr_history, linewidth=2, color='#3498db')
plt.xlabel('Training Step', fontsize=13)
plt.ylabel('Learning Rate', fontsize=13)
plt.title('Learning Rate Schedule', fontsize=16, fontweight='bold')
plt.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved LR schedule to {save_name}")
# =========================================================================
# SUMMARY DASHBOARD
# =========================================================================
def create_summary_dashboard(self, metrics: Dict[str, Any], cm: np.ndarray,
save_name='summary_dashboard.png'):
"""
Create comprehensive summary dashboard
Args:
metrics: Metrics dictionary
cm: Confusion matrix
save_name: Filename
"""
fig = plt.figure(figsize=(18, 12))
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)
# 1. Overall metrics (top-left)
ax1 = fig.add_subplot(gs[0, 0])
metric_names = ['Accuracy', 'Precision', 'Recall', 'F1-Score']
metric_values = [
metrics['accuracy'],
metrics['precision_macro'],
metrics['recall_macro'],
metrics['f1_macro']
]
bars = ax1.barh(metric_names, metric_values, color='#3498db', alpha=0.8)
for bar, value in zip(bars, metric_values):
ax1.text(value, bar.get_y() + bar.get_height()/2,
f'{value:.3f}', va='center', fontweight='bold')
ax1.set_xlim(0, 1.0)
ax1.set_title('Overall Metrics', fontweight='bold', fontsize=12)
ax1.grid(axis='x', alpha=0.3)
# 2. Confusion matrix (top-middle and top-right)
ax2 = fig.add_subplot(gs[0, 1:])
cm_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
sns.heatmap(cm_norm, annot=True, fmt='.2%', cmap='Blues',
xticklabels=self.class_names, yticklabels=self.class_names,
ax=ax2, cbar_kws={'label': 'Proportion'})
ax2.set_title('Normalized Confusion Matrix', fontweight='bold', fontsize=12)
ax2.set_ylabel('True')
ax2.set_xlabel('Predicted')
# 3. Per-class F1 (middle-left)
ax3 = fig.add_subplot(gs[1, 0])
classes = list(metrics['per_class'].keys())
f1_scores = [metrics['per_class'][c]['f1'] for c in classes]
ax3.bar(classes, f1_scores, color=self.colors, alpha=0.8)
ax3.set_ylabel('F1-Score')
ax3.set_title('Per-Class F1 Scores', fontweight='bold', fontsize=12)
ax3.set_ylim(0, 1.0)
ax3.grid(axis='y', alpha=0.3)
# 4. Per-class precision (middle-center)
ax4 = fig.add_subplot(gs[1, 1])
precision_scores = [metrics['per_class'][c]['precision'] for c in classes]
ax4.bar(classes, precision_scores, color=self.colors, alpha=0.8)
ax4.set_ylabel('Precision')
ax4.set_title('Per-Class Precision', fontweight='bold', fontsize=12)
ax4.set_ylim(0, 1.0)
ax4.grid(axis='y', alpha=0.3)
# 5. Per-class recall (middle-right)
ax5 = fig.add_subplot(gs[1, 2])
recall_scores = [metrics['per_class'][c]['recall'] for c in classes]
ax5.bar(classes, recall_scores, color=self.colors, alpha=0.8)
ax5.set_ylabel('Recall')
ax5.set_title('Per-Class Recall', fontweight='bold', fontsize=12)
ax5.set_ylim(0, 1.0)
ax5.grid(axis='y', alpha=0.3)
# 6. Class distribution (bottom-left)
ax6 = fig.add_subplot(gs[2, 0])
support = [metrics['per_class'][c]['support'] for c in classes]
ax6.pie(support, labels=classes, autopct='%1.1f%%',
colors=self.colors, startangle=90)
ax6.set_title('Class Distribution', fontweight='bold', fontsize=12)
# 7. Metrics summary table (bottom-center and bottom-right)
ax7 = fig.add_subplot(gs[2, 1:])
ax7.axis('tight')
ax7.axis('off')
table_data = []
for class_name in classes:
row = [
class_name,
f"{metrics['per_class'][class_name]['precision']:.3f}",
f"{metrics['per_class'][class_name]['recall']:.3f}",
f"{metrics['per_class'][class_name]['f1']:.3f}",
f"{metrics['per_class'][class_name]['support']}"
]
table_data.append(row)
table = ax7.table(cellText=table_data,
colLabels=['Class', 'Precision', 'Recall', 'F1', 'Support'],
cellLoc='center',
loc='center',
colWidths=[0.2, 0.2, 0.2, 0.2, 0.2])
table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1, 2)
ax7.set_title('Detailed Metrics', fontweight='bold', fontsize=12, pad=20)
fig.suptitle('Model Performance Dashboard',
fontsize=18, fontweight='bold', y=0.98)
plt.savefig(os.path.join(self.save_dir, save_name), dpi=self.dpi, bbox_inches='tight')
plt.close()
print(f"β
Saved summary dashboard to {save_name}")
if __name__ == "__main__":
print("="*80)
print("TESTING VISUALIZER")
print("="*80)
print("\nSentimentVisualizer module loaded successfully!")
print("\nAvailable plot types (20+):")
print(" 1. Training curves (loss + accuracy)")
print(" 2. Confusion matrices (raw + normalized)")
print(" 3. Per-class F1 scores")
print(" 4. Model comparison radar chart")
print(" 5. Error distribution")
print(" 6. Confidence distribution")
print(" 7. Text length vs accuracy")
print(" 8. ROC curves (one-vs-rest)")
print(" 9. Word cloud of errors")
print(" 10. Model comparison bars")
print(" 11. Learning rate schedule")
print(" 12. Summary dashboard")
print(" ... and more!")
print("\nβ
Visualizer module ready!") |