Spaces:
Sleeping
Sleeping
File size: 16,347 Bytes
7e825f9 | 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 | """
Model Evaluator Module
======================
Provides comprehensive model evaluation with visualization
support for confusion matrices, learning curves, and metrics.
"""
import os
# Set environment variables before transformers import
os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '3')
os.environ.setdefault('TRANSFORMERS_NO_TF', '1')
import json
import logging
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass
import numpy as np
import torch
from sklearn.metrics import (
accuracy_score,
precision_recall_fscore_support,
confusion_matrix,
classification_report,
roc_curve,
auc,
precision_recall_curve
)
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg') # Non-interactive backend for server use
import seaborn as sns
logger = logging.getLogger(__name__)
@dataclass
class EvaluationResults:
"""Container for evaluation results."""
accuracy: float = 0.0
precision: float = 0.0
recall: float = 0.0
f1: float = 0.0
support: int = 0
confusion_matrix: Optional[np.ndarray] = None
classification_report: str = ""
predictions: Optional[List[int]] = None
probabilities: Optional[List[float]] = None
true_labels: Optional[List[int]] = None
def to_dict(self) -> dict:
return {
"accuracy": self.accuracy,
"precision": self.precision,
"recall": self.recall,
"f1": self.f1,
"support": self.support,
"classification_report": self.classification_report
}
class ModelEvaluator:
"""
Comprehensive model evaluation with visualization support.
"""
def __init__(self, model=None, tokenizer=None, label_names: List[str] = None):
"""
Initialize evaluator.
Args:
model: Trained model (optional, can be loaded later)
tokenizer: Tokenizer (optional, can be loaded later)
label_names: List of label names for display
"""
self.model = model
self.tokenizer = tokenizer
self.label_names = label_names or ["Class 0", "Class 1"]
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def load_model(self, model_path: str) -> bool:
"""
Load model and tokenizer from path.
Args:
model_path: Path to saved model directory
Returns:
True if successful, False otherwise
"""
try:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
self.model = AutoModelForSequenceClassification.from_pretrained(model_path)
self.model.to(self.device)
self.model.eval()
logger.info(f"Model loaded from {model_path}")
return True
except Exception as e:
logger.error(f"Failed to load model: {str(e)}")
return False
def predict(self, texts: List[str], batch_size: int = 16,
max_length: int = 256) -> Tuple[List[int], List[float]]:
"""
Make predictions on a list of texts.
Args:
texts: List of texts to predict
batch_size: Batch size for inference
max_length: Maximum sequence length
Returns:
Tuple of (predictions, probabilities)
"""
if self.model is None or self.tokenizer is None:
raise ValueError("Model and tokenizer must be loaded first")
self.model.eval()
all_predictions = []
all_probabilities = []
with torch.no_grad():
for i in range(0, len(texts), batch_size):
batch_texts = texts[i:i + batch_size]
encodings = self.tokenizer(
batch_texts,
truncation=True,
padding=True,
max_length=max_length,
return_tensors="pt"
)
encodings = {k: v.to(self.device) for k, v in encodings.items()}
outputs = self.model(**encodings)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
preds = torch.argmax(probs, dim=-1)
all_predictions.extend(preds.cpu().numpy().tolist())
# Get probability of positive class (class 1)
all_probabilities.extend(probs[:, 1].cpu().numpy().tolist())
return all_predictions, all_probabilities
def evaluate(self, texts: List[str], true_labels: List[int],
batch_size: int = 16) -> EvaluationResults:
"""
Evaluate model on a dataset.
Args:
texts: List of texts
true_labels: True labels
batch_size: Batch size for inference
Returns:
EvaluationResults object
"""
predictions, probabilities = self.predict(texts, batch_size)
# Calculate metrics
accuracy = accuracy_score(true_labels, predictions)
precision, recall, f1, support = precision_recall_fscore_support(
true_labels, predictions, average='weighted', zero_division=0
)
cm = confusion_matrix(true_labels, predictions)
report = classification_report(
true_labels, predictions,
target_names=self.label_names,
zero_division=0
)
results = EvaluationResults(
accuracy=accuracy,
precision=precision,
recall=recall,
f1=f1,
support=len(true_labels),
confusion_matrix=cm,
classification_report=report,
predictions=predictions,
probabilities=probabilities,
true_labels=true_labels
)
return results
def plot_confusion_matrix(self, results: EvaluationResults,
figsize: Tuple[int, int] = (8, 6),
cmap: str = "Blues") -> plt.Figure:
"""
Plot confusion matrix.
Args:
results: EvaluationResults object
figsize: Figure size
cmap: Color map
Returns:
Matplotlib figure
"""
fig, ax = plt.subplots(figsize=figsize)
sns.heatmap(
results.confusion_matrix,
annot=True,
fmt='d',
cmap=cmap,
xticklabels=self.label_names,
yticklabels=self.label_names,
ax=ax
)
ax.set_xlabel('Predicted Label', fontsize=12)
ax.set_ylabel('True Label', fontsize=12)
ax.set_title('Confusion Matrix', fontsize=14)
plt.tight_layout()
return fig
def plot_roc_curve(self, results: EvaluationResults,
figsize: Tuple[int, int] = (8, 6)) -> plt.Figure:
"""
Plot ROC curve for binary classification.
Args:
results: EvaluationResults object
figsize: Figure size
Returns:
Matplotlib figure
"""
if results.probabilities is None or results.true_labels is None:
raise ValueError("Probabilities and true labels required for ROC curve")
fpr, tpr, thresholds = roc_curve(results.true_labels, results.probabilities)
roc_auc = auc(fpr, tpr)
fig, ax = plt.subplots(figsize=figsize)
ax.plot(fpr, tpr, color='darkorange', lw=2,
label=f'ROC curve (AUC = {roc_auc:.3f})')
ax.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--',
label='Random classifier')
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('False Positive Rate', fontsize=12)
ax.set_ylabel('True Positive Rate', fontsize=12)
ax.set_title('Receiver Operating Characteristic (ROC) Curve', fontsize=14)
ax.legend(loc='lower right')
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_precision_recall_curve(self, results: EvaluationResults,
figsize: Tuple[int, int] = (8, 6)) -> plt.Figure:
"""
Plot precision-recall curve.
Args:
results: EvaluationResults object
figsize: Figure size
Returns:
Matplotlib figure
"""
if results.probabilities is None or results.true_labels is None:
raise ValueError("Probabilities and true labels required")
precision, recall, thresholds = precision_recall_curve(
results.true_labels, results.probabilities
)
fig, ax = plt.subplots(figsize=figsize)
ax.plot(recall, precision, color='blue', lw=2)
ax.fill_between(recall, precision, alpha=0.2, color='blue')
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('Recall', fontsize=12)
ax.set_ylabel('Precision', fontsize=12)
ax.set_title('Precision-Recall Curve', fontsize=14)
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_training_history(self, metrics_history: List[Dict],
figsize: Tuple[int, int] = (12, 4)) -> plt.Figure:
"""
Plot training history (loss and metrics over epochs).
Args:
metrics_history: List of metric dictionaries
figsize: Figure size
Returns:
Matplotlib figure
"""
if not metrics_history:
raise ValueError("No metrics history to plot")
fig, axes = plt.subplots(1, 3, figsize=figsize)
# Extract data
epochs = [m.get('epoch', i) for i, m in enumerate(metrics_history)]
train_loss = [m.get('train_loss', 0) for m in metrics_history]
eval_loss = [m.get('eval_loss', 0) for m in metrics_history]
accuracy = [m.get('accuracy', 0) for m in metrics_history]
f1 = [m.get('f1', 0) for m in metrics_history]
# Loss plot
if any(train_loss):
axes[0].plot(epochs, train_loss, 'b-', label='Train Loss', marker='o')
if any(eval_loss):
axes[0].plot(epochs, eval_loss, 'r-', label='Eval Loss', marker='s')
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('Loss')
axes[0].set_title('Training & Validation Loss')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# Accuracy plot
if any(accuracy):
axes[1].plot(epochs, accuracy, 'g-', marker='o')
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('Accuracy')
axes[1].set_title('Accuracy over Training')
axes[1].grid(True, alpha=0.3)
# F1 score plot
if any(f1):
axes[2].plot(epochs, f1, 'm-', marker='o')
axes[2].set_xlabel('Epoch')
axes[2].set_ylabel('F1 Score')
axes[2].set_title('F1 Score over Training')
axes[2].grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_class_distribution(self, labels: List[int],
figsize: Tuple[int, int] = (8, 5)) -> plt.Figure:
"""
Plot class distribution in dataset.
Args:
labels: List of labels
figsize: Figure size
Returns:
Matplotlib figure
"""
unique, counts = np.unique(labels, return_counts=True)
fig, ax = plt.subplots(figsize=figsize)
colors = plt.cm.Set3(np.linspace(0, 1, len(unique)))
bars = ax.bar(
[self.label_names[i] if i < len(self.label_names) else f"Class {i}"
for i in unique],
counts,
color=colors
)
# Add value labels on bars
for bar, count in zip(bars, counts):
height = bar.get_height()
ax.annotate(f'{count}',
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 3),
textcoords="offset points",
ha='center', va='bottom',
fontsize=12, fontweight='bold')
ax.set_xlabel('Class', fontsize=12)
ax.set_ylabel('Count', fontsize=12)
ax.set_title('Class Distribution', fontsize=14)
ax.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
return fig
def generate_report(self, results: EvaluationResults,
output_path: Optional[str] = None) -> str:
"""
Generate a text report of evaluation results.
Args:
results: EvaluationResults object
output_path: Optional path to save the report
Returns:
Report string
"""
report = []
report.append("=" * 60)
report.append("MODEL EVALUATION REPORT")
report.append("=" * 60)
report.append("")
report.append("OVERALL METRICS:")
report.append(f" Accuracy: {results.accuracy:.4f} ({results.accuracy*100:.2f}%)")
report.append(f" Precision: {results.precision:.4f}")
report.append(f" Recall: {results.recall:.4f}")
report.append(f" F1 Score: {results.f1:.4f}")
report.append(f" Samples: {results.support}")
report.append("")
report.append("CLASSIFICATION REPORT:")
report.append(results.classification_report)
report.append("")
report.append("CONFUSION MATRIX:")
if results.confusion_matrix is not None:
report.append(str(results.confusion_matrix))
report.append("")
report.append("=" * 60)
report_str = "\n".join(report)
if output_path:
with open(output_path, 'w', encoding='utf-8') as f:
f.write(report_str)
logger.info(f"Report saved to {output_path}")
return report_str
def save_results(self, results: EvaluationResults, output_dir: str):
"""
Save evaluation results to files.
Args:
results: EvaluationResults object
output_dir: Output directory
"""
os.makedirs(output_dir, exist_ok=True)
# Save metrics as JSON
metrics_path = os.path.join(output_dir, "evaluation_metrics.json")
with open(metrics_path, 'w', encoding='utf-8') as f:
json.dump(results.to_dict(), f, indent=2, ensure_ascii=False)
# Save confusion matrix as image
try:
fig = self.plot_confusion_matrix(results)
fig.savefig(os.path.join(output_dir, "confusion_matrix.png"), dpi=150)
plt.close(fig)
except Exception as e:
logger.warning(f"Could not save confusion matrix: {e}")
# Save text report
report_path = os.path.join(output_dir, "evaluation_report.txt")
self.generate_report(results, report_path)
logger.info(f"Results saved to {output_dir}")
def create_evaluator(label_names: List[str] = None) -> ModelEvaluator:
"""Factory function to create a ModelEvaluator instance."""
return ModelEvaluator(label_names=label_names)
|