Download evaluate.py from crashn/FloraFind: direct link, hf CLI and curl.
- Browser
- Download file 9.85 kB
-
https://huggingface.co/spaces/crashn/FloraFind/resolve/main/evaluate.py
- Command line
-
hf download hf://spaces/crashn/FloraFind/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/spaces/crashn/FloraFind/resolve/main/evaluate.py
9.85 kB
| """Evaluate every trained model on the unseen test split and time single-image predictions. | |
| Usage: | |
| python evaluate.py (after train.py) | |
| Metrics, the per-class report, the most frequent mistakes, timings, the model comparison, and plots are saved | |
| to outputs/evaluation/. | |
| """ | |
| from copy import deepcopy | |
| from functools import partial | |
| from pathlib import Path | |
| import matplotlib.pyplot as plt | |
| import pandas as pd | |
| import torch | |
| from sklearn.metrics import classification_report, precision_recall_fscore_support | |
| from torch.utils.data import DataLoader | |
| from data_setup import BASELINE_TEST_TRANSFORM, BATCH_SIZE, RANDOM_SEED, TEST_TRANSFORM, load_split | |
| from engine import get_device, predict_labels, predict_single_image | |
| from model_builder import create_efficientnet_b0, create_tinyvgg | |
| PROJECT_DIR = Path(__file__).resolve().parent | |
| TRAINING_SUMMARY_PATH = PROJECT_DIR / "outputs" / "training" / "training_summary.csv" | |
| OUTPUT_DIR = PROJECT_DIR / "outputs" / "evaluation" | |
| TIMING_IMAGES = 50 | |
| # Rebuild each architecture without downloading pretrained weights, then load the trained checkpoint | |
| ARCHITECTURES = { | |
| "TinyVGG": (create_tinyvgg, BASELINE_TEST_TRANSFORM), | |
| "EfficientNet-B0": (partial(create_efficientnet_b0, pretrained=False), TEST_TRANSFORM) | |
| } | |
| def main(): | |
| device = get_device() | |
| OUTPUT_DIR.mkdir(parents=True, exist_ok=True) | |
| training_summary = pd.read_csv(TRAINING_SUMMARY_PATH, index_col="model") | |
| final_model_name = training_summary.index[training_summary["final_model"]][0] | |
| test_data = load_split("test") | |
| class_names = test_data.classes | |
| num_classes = len(class_names) | |
| test_targets = torch.tensor(test_data._labels) | |
| trained_models = {} | |
| for name, row in training_summary.iterrows(): | |
| create_model, test_transform = ARCHITECTURES[row["architecture"]] | |
| model = create_model(num_classes) | |
| model.load_state_dict(torch.load(PROJECT_DIR / row["checkpoint"], map_location="cpu", weights_only=True)) | |
| trained_models[name] = (model.to(device), test_transform) | |
| # Predict all test images with each model and report standard classification metrics | |
| model_predictions = {} | |
| metric_rows = [] | |
| for name, (model, test_transform) in trained_models.items(): | |
| test_loader = DataLoader(load_split("test", test_transform), batch_size=BATCH_SIZE, shuffle=False) | |
| predictions = predict_labels(model, test_loader, device) | |
| model_predictions[name] = predictions | |
| macro = precision_recall_fscore_support(test_targets, predictions, average="macro", zero_division=0) | |
| weighted = precision_recall_fscore_support(test_targets, predictions, average="weighted", zero_division=0) | |
| metric_rows.append({ | |
| "model": name, | |
| "accuracy (%)": 100 * (predictions == test_targets).float().mean().item(), | |
| "macro precision (%)": 100 * macro[0], | |
| "macro recall (%)": 100 * macro[1], | |
| "macro F1 (%)": 100 * macro[2], | |
| "weighted F1 (%)": 100 * weighted[2] | |
| }) | |
| test_metrics = pd.DataFrame(metric_rows).set_index("model").round(2) | |
| test_metrics.to_csv(OUTPUT_DIR / "test_metrics.csv") | |
| print(f"Test metrics ({len(test_data):,} unseen photos):") | |
| print(test_metrics.to_string(), "\n") | |
| # Build the final model's per-class report and show its ten weakest classes | |
| final_predictions = model_predictions[final_model_name] | |
| class_report = pd.DataFrame(classification_report( | |
| test_targets, final_predictions, labels=list(range(num_classes)), | |
| target_names=class_names, output_dict=True, zero_division=0 | |
| )).T.iloc[:num_classes] | |
| class_report["support"] = class_report["support"].astype(int) | |
| class_report.round(3).to_csv(OUTPUT_DIR / "class_report.csv", index_label="class") | |
| print(f"{final_model_name} per-class results:") | |
| print(f"Classes with perfect F1: {(class_report['f1-score'] == 1).sum()} of {num_classes}") | |
| print(f"Classes with F1 below 0.80: {(class_report['f1-score'] < 0.8).sum()}") | |
| print(class_report.sort_values("f1-score").head(10).round(3).to_string(), "\n") | |
| # Plot the row-normalized confusion matrix, since test classes contain different numbers of images | |
| confusion_matrix = torch.bincount( | |
| test_targets * num_classes + final_predictions, | |
| minlength=num_classes ** 2 | |
| ).reshape(num_classes, num_classes) | |
| confusion_rates = confusion_matrix / confusion_matrix.sum(dim=1, keepdim=True) | |
| fig, ax = plt.subplots(figsize=(11, 10)) | |
| heatmap = ax.imshow(confusion_rates.numpy(), cmap="Blues") | |
| fig.colorbar(heatmap, ax=ax, label="Share of true class predicted") | |
| ax.set_xlabel("Predicted label") | |
| ax.set_ylabel("True label") | |
| ax.set_title(f"{final_model_name} test confusion matrix (row-normalized)") | |
| fig.tight_layout() | |
| fig.savefig(OUTPUT_DIR / "confusion_matrix.png", dpi=100) | |
| plt.close(fig) | |
| # List the most frequent mistakes (true class -> predicted class) | |
| error_counts = confusion_matrix.clone() | |
| error_counts.fill_diagonal_(0) | |
| counts, pair_indices = error_counts.flatten().topk(8) | |
| class_sizes = confusion_matrix.sum(dim=1) | |
| top_mistakes = pd.DataFrame({ | |
| "true class": [class_names[index // num_classes] for index in pair_indices.tolist()], | |
| "predicted class": [class_names[index % num_classes] for index in pair_indices.tolist()], | |
| "count": counts.tolist(), | |
| "true-class test images": [class_sizes[index // num_classes].item() for index in pair_indices.tolist()] | |
| }) | |
| top_mistakes.to_csv(OUTPUT_DIR / "top_mistakes.csv", index=False) | |
| print(f"Correct predictions: {confusion_matrix.diag().sum().item():,}/{confusion_matrix.sum().item():,}") | |
| print("Most frequent mistakes:") | |
| print(top_mistakes.to_string(index=False), "\n") | |
| # Plot nine reproducible mistakes with the predicted and correct labels | |
| wrong_indices = torch.where(final_predictions != test_targets)[0] | |
| wrong_order = torch.randperm( | |
| len(wrong_indices), generator=torch.Generator().manual_seed(RANDOM_SEED) | |
| ) | |
| fig, axes = plt.subplots(3, 3, figsize=(12, 12)) | |
| for ax, index in zip(axes.flat, wrong_indices[wrong_order[:9]].tolist()): | |
| image, target = test_data[index] | |
| ax.imshow(image) | |
| ax.set_title( | |
| f"Pred: {class_names[final_predictions[index]]}\nTarget: {class_names[target]}", | |
| color="red", fontsize=10 | |
| ) | |
| ax.axis("off") | |
| fig.tight_layout() | |
| fig.savefig(OUTPUT_DIR / "mistakes.png", dpi=80) | |
| plt.close(fig) | |
| # Time each model on the CPU with one thread, as the web app runs (fastest for single images on an M1 Pro) | |
| torch.set_num_threads(1) | |
| image_index = torch.randint( | |
| len(test_data), (1,), generator=torch.Generator().manual_seed(RANDOM_SEED) | |
| ).item() | |
| image, target = test_data[image_index] | |
| single_image_seconds = {} | |
| for name, (model, test_transform) in trained_models.items(): | |
| cpu_model = deepcopy(model).to("cpu") | |
| # Run once untimed so the timer excludes first-call setup | |
| predict_single_image(cpu_model, image, test_transform, "cpu") | |
| pred_probs, seconds = predict_single_image(cpu_model, image, test_transform, "cpu") | |
| single_image_seconds[name] = seconds | |
| prediction = pred_probs.argmax().item() | |
| print( | |
| f"{name} | Pred: {class_names[prediction]} ({pred_probs[prediction]:.2%}) | " | |
| f"Target: {class_names[target]} | Prediction time: {seconds:.4f} seconds" | |
| ) | |
| # Time the final model on the training device too | |
| final_model, _ = trained_models[final_model_name] | |
| predict_single_image(final_model, image, TEST_TRANSFORM, device) | |
| final_probs, device_seconds = predict_single_image(final_model, image, TEST_TRANSFORM, device) | |
| print(f"{final_model_name} on {device}: {device_seconds:.4f} seconds\n") | |
| fig, ax = plt.subplots(figsize=(6, 6)) | |
| ax.imshow(image) | |
| ax.set_title( | |
| f"Pred: {class_names[final_probs.argmax()]} ({final_probs.max():.2%}) | Target: {class_names[target]}\n" | |
| f"CPU prediction time: {single_image_seconds[final_model_name]:.4f} seconds" | |
| ) | |
| ax.axis("off") | |
| fig.tight_layout() | |
| fig.savefig(OUTPUT_DIR / "single_prediction.png", dpi=80) | |
| plt.close(fig) | |
| # Repeat the CPU timer on 50 test photos to check that the single-image time is typical | |
| timing_indices = torch.randperm( | |
| len(test_data), generator=torch.Generator().manual_seed(RANDOM_SEED) | |
| )[:TIMING_IMAGES].tolist() | |
| final_cpu_model = deepcopy(final_model).to("cpu") | |
| timing_seconds = pd.Series([ | |
| predict_single_image(final_cpu_model, test_data[index][0], TEST_TRANSFORM, "cpu")[1] | |
| for index in timing_indices | |
| ], name="seconds") | |
| timing_seconds.to_csv(OUTPUT_DIR / "cpu_timing.csv", index_label="photo") | |
| print(f"{final_model_name} CPU time over {TIMING_IMAGES} test photos:") | |
| print(timing_seconds.describe().round(4).to_string(), "\n") | |
| # Organize test metrics, model size, training time, and inference time in one output | |
| model_comparison = test_metrics.copy() | |
| model_comparison["validation loss"] = training_summary["val_loss"].round(4) | |
| model_comparison["total parameters"] = training_summary["total_parameters"] | |
| model_comparison["trainable parameters"] = training_summary["trainable_parameters"] | |
| model_comparison["restored epoch"] = training_summary["restored_epoch"] | |
| model_comparison["training seconds"] = training_summary["training_seconds"].round(1) | |
| model_comparison["CPU seconds per image"] = pd.Series(single_image_seconds).round(4) | |
| model_comparison.to_csv(OUTPUT_DIR / "model_comparison.csv") | |
| print("Model comparison:") | |
| print(model_comparison.astype(object).T.to_string()) | |
| print(f"\nSaved tables and plots to {OUTPUT_DIR}") | |
| if __name__ == "__main__": | |
| main() | |