Spaces:
Running
Running
Download workflow/utils/analyse_perclass.py from lauransotomayor/hyperFVC: direct link, hf CLI and curl.
- Browser
- Download file 26 kB
-
https://huggingface.co/spaces/lauransotomayor/hyperFVC/resolve/main/workflow/utils/analyse_perclass.py
- Command line
-
hf download hf://spaces/lauransotomayor/hyperFVC/workflow/utils/analyse_perclass.py
-
curl -L -o analyse_perclass.py https://huggingface.co/spaces/lauransotomayor/hyperFVC/resolve/main/workflow/utils/analyse_perclass.py
26 kB
| import os | |
| import re | |
| import json | |
| import math | |
| import glob | |
| import pandas as pd | |
| output_base = "/media/laura/8402326D023263F8/calperumResearch/site1_1_DD0001/outputs_ecosystems/medium" | |
| report_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "analyse_perclass_exports") | |
| os.makedirs(report_dir, exist_ok=True) | |
| sensors = ["FX10", "FX17", "FX10_FX17", "MICA"] | |
| variants = ["", "_aug", "_aug_spectral", "_aug_spectral_weights", "_aug_spec_transformer", "_aug_spec_transformer_weights"] | |
| scales = ["", "_s224", "_s304"] | |
| CLASS_NAMES = {0: "BE", 1: "NPV", 2: "PV"} | |
| def average_metric_dicts(metric_dicts): | |
| if not metric_dicts: | |
| return {} | |
| keys = sorted({key for metrics in metric_dicts for key in metrics.keys()}) | |
| averaged = {} | |
| for key in keys: | |
| values = [metrics[key] for metrics in metric_dicts if key in metrics] | |
| if values: | |
| averaged[key] = sum(values) / len(values) | |
| return averaged | |
| def get_best_block(dir_path): | |
| """Returns the block number with the lowest validation loss.""" | |
| fpath = os.path.join(dir_path, "best_model_paths_and_validation_losses.txt") | |
| if not os.path.exists(fpath): | |
| return None | |
| best_block, best_loss = None, float("inf") | |
| with open(fpath) as f: | |
| for line in f: | |
| m = re.search(r"Block (\d+).*validation loss: ([0-9.]+)", line) | |
| if m: | |
| block, loss = int(m.group(1)), float(m.group(2)) | |
| if loss < best_loss: | |
| best_loss, best_block = loss, block | |
| return best_block | |
| def parse_best_metrics(dir_path, block): | |
| """Parses per-class IoU and F1 from the best_model_metrics_block_{N}.txt.""" | |
| fpath = os.path.join(dir_path, f"best_model_metrics_block_{block}.txt") | |
| metrics = {} | |
| if not os.path.exists(fpath): | |
| return metrics | |
| with open(fpath) as f: | |
| for line in f: | |
| if line.startswith("Accuracy:"): | |
| metrics["Accuracy"] = float(line.split(":")[1].strip()) | |
| elif line.startswith("MIoU:"): | |
| metrics["MIoU"] = float(line.split(":")[1].strip()) | |
| elif line.startswith("IoU:"): | |
| vals = [float(v.strip()) for v in line.split(":")[1].split(",")] | |
| for i, v in enumerate(vals): | |
| metrics[f"IoU_{CLASS_NAMES.get(i, i)}"] = v | |
| elif line.startswith("F1 Score:"): | |
| vals = [float(v.strip()) for v in line.split(":")[1].split(",")] | |
| for i, v in enumerate(vals): | |
| metrics[f"F1_{CLASS_NAMES.get(i, i)}"] = v | |
| return metrics | |
| def parse_best_validation_metrics(dir_path, block): | |
| """Parses per-class IoU and F1 from block_{N}_best_val_metrics.json.""" | |
| fpath = os.path.join(dir_path, f"block_{block}_best_val_metrics.json") | |
| metrics = {} | |
| if not os.path.exists(fpath): | |
| return metrics | |
| with open(fpath) as f: | |
| raw = json.load(f) | |
| if "accuracy" in raw: | |
| metrics["Val_Accuracy"] = float(raw["accuracy"]) | |
| if "miou" in raw: | |
| metrics["Val_MIoU"] = float(raw["miou"]) | |
| iou_vals = raw.get("iou", []) | |
| for i, value in enumerate(iou_vals): | |
| metrics[f"Val_IoU_{CLASS_NAMES.get(i, i)}"] = float(value) | |
| f1_vals = raw.get("f1", []) | |
| for i, value in enumerate(f1_vals): | |
| metrics[f"Val_F1_{CLASS_NAMES.get(i, i)}"] = float(value) | |
| return metrics | |
| def find_available_blocks(dir_path): | |
| blocks = set() | |
| if not os.path.isdir(dir_path): | |
| return [] | |
| for name in os.listdir(dir_path): | |
| match = re.match(r"best_model_metrics_block_(\d+)\.txt$", name) | |
| if match: | |
| blocks.add(int(match.group(1))) | |
| continue | |
| match = re.match(r"block_(\d+)_best_val_metrics\.json$", name) | |
| if match: | |
| blocks.add(int(match.group(1))) | |
| return sorted(blocks) | |
| def parse_average_test_metrics(dir_path): | |
| all_metrics = [] | |
| for block in find_available_blocks(dir_path): | |
| metrics = parse_best_metrics(dir_path, block) | |
| if metrics: | |
| all_metrics.append(metrics) | |
| averaged = average_metric_dicts(all_metrics) | |
| return {f"Avg_{key}": value for key, value in averaged.items()} | |
| def parse_average_validation_metrics(dir_path): | |
| all_metrics = [] | |
| for block in find_available_blocks(dir_path): | |
| metrics = parse_best_validation_metrics(dir_path, block) | |
| if metrics: | |
| all_metrics.append(metrics) | |
| averaged = average_metric_dicts(all_metrics) | |
| return {f"Avg_{key}": value for key, value in averaged.items()} | |
| def parse_senescence_summary(dir_path): | |
| csv_path = os.path.join(dir_path, "senescence_analysis_all_blocks_summary.csv") | |
| if not os.path.exists(csv_path): | |
| return {} | |
| try: | |
| df = pd.read_csv(csv_path) | |
| except Exception: | |
| return {} | |
| if df.empty: | |
| return {} | |
| metrics = {} | |
| if "transition_fraction" in df.columns: | |
| metrics["Sen_Transition_Fraction_Mean"] = float(df["transition_fraction"].mean()) | |
| for trait in ["NDVI", "NDRE", "PSRI", "PWI_900_970", "NDWI_860_1240", "MSI_1600_817", "ANMB1450"]: | |
| npv_minus_pv = f"{trait}_NPV_minus_PV" | |
| npv_minus_be = f"{trait}_NPV_minus_BE" | |
| if npv_minus_pv in df.columns: | |
| metrics[f"Sen_{npv_minus_pv}_Mean"] = float(df[npv_minus_pv].mean()) | |
| if npv_minus_be in df.columns: | |
| metrics[f"Sen_{npv_minus_be}_Mean"] = float(df[npv_minus_be].mean()) | |
| return metrics | |
| def parse_model_driven_senescence_summary(dir_path): | |
| block_metrics = [] | |
| block_dirs = sorted(glob.glob(os.path.join(dir_path, "senescence_analysis_block_*"))) | |
| for block_dir in block_dirs: | |
| block_summary = {} | |
| sensitivity_path = os.path.join(block_dir, "senescence_sensitivity_per_band.csv") | |
| if os.path.exists(sensitivity_path): | |
| sensitivity_df = pd.read_csv(sensitivity_path) | |
| if "sensitivity" in sensitivity_df.columns: | |
| values = pd.to_numeric(sensitivity_df["sensitivity"], errors="coerce").dropna() | |
| if not values.empty: | |
| top_n = max(5, int(math.ceil(len(values) * 0.05))) | |
| abs_values = values.abs() | |
| block_summary["ModelSen_AbsSensitivityMean"] = float(abs_values.mean()) | |
| block_summary["ModelSen_AbsSensitivityTopMean"] = float(abs_values.nlargest(top_n).mean()) | |
| block_summary["ModelSen_NPVFavorFraction"] = float((values > 0).mean()) | |
| importance_path = os.path.join(block_dir, "senescence_band_importance_per_band.csv") | |
| if os.path.exists(importance_path): | |
| importance_df = pd.read_csv(importance_path) | |
| required_cols = {"pv_masked_logit_sensitivity", "npv_masked_logit_sensitivity"} | |
| if required_cols.issubset(importance_df.columns): | |
| pv_vals = pd.to_numeric(importance_df["pv_masked_logit_sensitivity"], errors="coerce") | |
| npv_vals = pd.to_numeric(importance_df["npv_masked_logit_sensitivity"], errors="coerce") | |
| response = ((pv_vals.abs() + npv_vals.abs()) / 2.0).dropna() | |
| if not response.empty: | |
| top_n = max(5, int(math.ceil(len(response) * 0.05))) | |
| block_summary["ModelSen_ClassResponseMean"] = float(response.mean()) | |
| block_summary["ModelSen_ClassResponseTopMean"] = float(response.nlargest(top_n).mean()) | |
| gate_path = os.path.join(block_dir, "senescence_band_importance_grouped.csv") | |
| if os.path.exists(gate_path): | |
| gate_df = pd.read_csv(gate_path) | |
| if "global_gate_mean" in gate_df.columns: | |
| gate_vals = pd.to_numeric(gate_df["global_gate_mean"], errors="coerce").dropna() | |
| if not gate_vals.empty: | |
| top_n = max(3, int(math.ceil(len(gate_vals) * 0.10))) | |
| gate_mean = float(gate_vals.mean()) | |
| gate_top_mean = float(gate_vals.nlargest(top_n).mean()) | |
| block_summary["ModelSen_GateMean"] = gate_mean | |
| block_summary["ModelSen_GateTopMean"] = gate_top_mean | |
| block_summary["ModelSen_GateSelectivity"] = float(gate_top_mean / gate_mean) if gate_mean else 0.0 | |
| if block_summary: | |
| block_metrics.append(block_summary) | |
| averaged = average_metric_dicts(block_metrics) | |
| if averaged: | |
| averaged["ModelSen_BlockCount"] = len(block_metrics) | |
| return averaged | |
| def normalize_series(series, inverse=False): | |
| numeric = pd.to_numeric(series, errors="coerce") | |
| if numeric.isna().all(): | |
| return pd.Series(0.0, index=series.index) | |
| minimum = numeric.min() | |
| maximum = numeric.max() | |
| if pd.isna(minimum) or pd.isna(maximum) or maximum == minimum: | |
| return pd.Series(0.0, index=series.index) | |
| scaled = (numeric - minimum) / (maximum - minimum) | |
| if inverse: | |
| scaled = 1.0 - scaled | |
| return scaled.fillna(0.0) | |
| def build_overall_model_ranking(df): | |
| required = {"Avg_IoU_NPV", "Avg_Val_IoU_NPV", "Avg_MIoU", "Avg_Val_MIoU"} | |
| if not required.issubset(df.columns): | |
| return pd.DataFrame() | |
| ranked = df.copy() | |
| ranked["Score_Avg_IoU_NPV"] = normalize_series(ranked["Avg_IoU_NPV"]) | |
| ranked["Score_Avg_Val_IoU_NPV"] = normalize_series(ranked["Avg_Val_IoU_NPV"]) | |
| ranked["Score_Avg_MIoU"] = normalize_series(ranked["Avg_MIoU"]) | |
| ranked["Score_Avg_Val_MIoU"] = normalize_series(ranked["Avg_Val_MIoU"]) | |
| if "Sen_Transition_Fraction_Mean" in ranked.columns: | |
| ranked["Score_Low_Transition"] = normalize_series(ranked["Sen_Transition_Fraction_Mean"], inverse=True) | |
| else: | |
| ranked["Score_Low_Transition"] = 0.0 | |
| ranked["Overall_Score"] = ( | |
| 0.35 * ranked["Score_Avg_IoU_NPV"] | |
| + 0.35 * ranked["Score_Avg_Val_IoU_NPV"] | |
| + 0.15 * ranked["Score_Avg_MIoU"] | |
| + 0.10 * ranked["Score_Avg_Val_MIoU"] | |
| + 0.05 * ranked["Score_Low_Transition"] | |
| ) | |
| ranked = ranked.sort_values( | |
| by=["Overall_Score", "Avg_IoU_NPV", "Avg_Val_IoU_NPV", "Avg_MIoU"], | |
| ascending=False, | |
| ).reset_index(drop=True) | |
| ranked.insert(0, "Rank", ranked.index + 1) | |
| return ranked | |
| def build_model_driven_senescence_ranking(df): | |
| required = { | |
| "ModelSen_AbsSensitivityMean", | |
| "ModelSen_AbsSensitivityTopMean", | |
| "ModelSen_ClassResponseTopMean", | |
| "ModelSen_GateSelectivity", | |
| } | |
| if not required.issubset(df.columns): | |
| return pd.DataFrame() | |
| ranked = df.copy() | |
| ranked["Score_ModelSen_AbsSensitivityMean"] = normalize_series(ranked["ModelSen_AbsSensitivityMean"]) | |
| ranked["Score_ModelSen_AbsSensitivityTopMean"] = normalize_series(ranked["ModelSen_AbsSensitivityTopMean"]) | |
| ranked["Score_ModelSen_ClassResponseTopMean"] = normalize_series(ranked["ModelSen_ClassResponseTopMean"]) | |
| ranked["Score_ModelSen_GateSelectivity"] = normalize_series(ranked["ModelSen_GateSelectivity"]) | |
| if "Sen_Transition_Fraction_Mean" in ranked.columns: | |
| ranked["Score_ModelSen_LowTransition"] = normalize_series(ranked["Sen_Transition_Fraction_Mean"], inverse=True) | |
| else: | |
| ranked["Score_ModelSen_LowTransition"] = 0.0 | |
| ranked["ModelDriven_Senescence_Score"] = ( | |
| 0.35 * ranked["Score_ModelSen_AbsSensitivityTopMean"] | |
| + 0.25 * ranked["Score_ModelSen_AbsSensitivityMean"] | |
| + 0.20 * ranked["Score_ModelSen_ClassResponseTopMean"] | |
| + 0.15 * ranked["Score_ModelSen_GateSelectivity"] | |
| + 0.05 * ranked["Score_ModelSen_LowTransition"] | |
| ) | |
| ranked = ranked.sort_values( | |
| by=["ModelDriven_Senescence_Score", "ModelSen_AbsSensitivityTopMean", "ModelSen_GateSelectivity"], | |
| ascending=False, | |
| ).reset_index(drop=True) | |
| ranked.insert(0, "Rank", ranked.index + 1) | |
| return ranked | |
| def export_table(df, filename): | |
| if df.empty: | |
| return None | |
| output_path = os.path.join(report_dir, filename) | |
| df.to_csv(output_path, index=False) | |
| return output_path | |
| def print_model_driven_table(df): | |
| sci_cols = { | |
| "ModelSen_AbsSensitivityMean", | |
| "ModelSen_AbsSensitivityTopMean", | |
| "ModelSen_ClassResponseMean", | |
| "ModelSen_ClassResponseTopMean", | |
| } | |
| fixed_cols = { | |
| "ModelSen_GateSelectivity", | |
| "Sen_Transition_Fraction_Mean", | |
| "ModelDriven_Senescence_Score", | |
| } | |
| formatters = {} | |
| for col in df.columns: | |
| if col in sci_cols: | |
| formatters[col] = lambda value: "" if pd.isna(value) else f"{value:.6e}" | |
| elif col in fixed_cols: | |
| formatters[col] = lambda value: "" if pd.isna(value) else f"{value:.4f}" | |
| print(df.to_string(index=False, formatters=formatters)) | |
| def build_baseline_delta_summary(df): | |
| required_cols = { | |
| "Sensor", | |
| "Variant", | |
| "Scale", | |
| "Avg_IoU_NPV", | |
| "Avg_MIoU", | |
| "Avg_Val_IoU_NPV", | |
| "Avg_Val_MIoU", | |
| } | |
| if not required_cols.issubset(df.columns): | |
| return pd.DataFrame() | |
| summary_rows = [] | |
| for sensor in sorted(df["Sensor"].unique()): | |
| sensor_df = df[df["Sensor"] == sensor].copy() | |
| baseline_by_scale = sensor_df[sensor_df["Variant"] == "baseline"].set_index("Scale") | |
| candidate_rows = [] | |
| for _, row in sensor_df[sensor_df["Variant"] != "baseline"].iterrows(): | |
| scale = row["Scale"] | |
| if scale not in baseline_by_scale.index: | |
| continue | |
| baseline = baseline_by_scale.loc[scale] | |
| candidate_rows.append({ | |
| "Sensor": sensor, | |
| "Recommended": row["Variant"], | |
| "Scale": scale, | |
| "Baseline_Avg_IoU_NPV": baseline["Avg_IoU_NPV"], | |
| "Avg_IoU_NPV": row["Avg_IoU_NPV"], | |
| "Delta_Avg_IoU_NPV": row["Avg_IoU_NPV"] - baseline["Avg_IoU_NPV"], | |
| "Baseline_Avg_MIoU": baseline["Avg_MIoU"], | |
| "Avg_MIoU": row["Avg_MIoU"], | |
| "Delta_Avg_MIoU": row["Avg_MIoU"] - baseline["Avg_MIoU"], | |
| "Baseline_Avg_Val_IoU_NPV": baseline["Avg_Val_IoU_NPV"], | |
| "Avg_Val_IoU_NPV": row["Avg_Val_IoU_NPV"], | |
| "Delta_Avg_Val_IoU_NPV": row["Avg_Val_IoU_NPV"] - baseline["Avg_Val_IoU_NPV"], | |
| "Avg_Val_MIoU": row["Avg_Val_MIoU"], | |
| "Delta_Avg_Val_MIoU": row["Avg_Val_MIoU"] - baseline["Avg_Val_MIoU"], | |
| }) | |
| if not candidate_rows: | |
| continue | |
| candidate_df = pd.DataFrame(candidate_rows).sort_values( | |
| by=["Delta_Avg_IoU_NPV", "Delta_Avg_Val_IoU_NPV", "Delta_Avg_MIoU"], | |
| ascending=False, | |
| ) | |
| summary_rows.append(candidate_df.iloc[0].to_dict()) | |
| if not summary_rows: | |
| return pd.DataFrame() | |
| summary_df = pd.DataFrame(summary_rows).sort_values( | |
| by=["Delta_Avg_IoU_NPV", "Delta_Avg_Val_IoU_NPV", "Delta_Avg_MIoU"], | |
| ascending=False, | |
| ).reset_index(drop=True) | |
| summary_df.insert(0, "Rank", summary_df.index + 1) | |
| return summary_df | |
| data = [] | |
| scale_labels = { | |
| "": "native", | |
| "_s224": "224px", | |
| "_s304": "304px", | |
| } | |
| for sensor in sensors: | |
| for variant in variants: | |
| for scale in scales: | |
| dir_name = f"{sensor}{variant}{scale}" | |
| dir_path = os.path.join(output_base, dir_name) | |
| best_block = get_best_block(dir_path) | |
| if best_block is None: | |
| continue | |
| metrics = parse_best_metrics(dir_path, best_block) | |
| val_metrics = parse_best_validation_metrics(dir_path, best_block) | |
| avg_test_metrics = parse_average_test_metrics(dir_path) | |
| avg_val_metrics = parse_average_validation_metrics(dir_path) | |
| if metrics or val_metrics or avg_test_metrics or avg_val_metrics: | |
| row = { | |
| "Sensor": sensor, | |
| "Variant": variant if variant else "baseline", | |
| "Scale": scale_labels.get(scale, scale), | |
| "Best_Block": best_block, | |
| "Directory": dir_name, | |
| } | |
| row.update(metrics) | |
| row.update(val_metrics) | |
| row.update(avg_test_metrics) | |
| row.update(avg_val_metrics) | |
| row.update(parse_senescence_summary(dir_path)) | |
| row.update(parse_model_driven_senescence_summary(dir_path)) | |
| data.append(row) | |
| if data: | |
| df = pd.DataFrame(data) | |
| sort_cols = ["Variant", "Sensor", "Scale"] | |
| df = df.sort_values(by=sort_cols) | |
| test_cols = [ | |
| "Sensor", "Variant", "Scale", "Best_Block", | |
| "Accuracy", "MIoU", | |
| "IoU_BE", "IoU_NPV", "IoU_PV", | |
| "F1_BE", "F1_NPV", "F1_PV", | |
| ] | |
| test_cols = [c for c in test_cols if c in df.columns] | |
| val_cols = [ | |
| "Sensor", "Variant", "Scale", "Best_Block", | |
| "Val_Accuracy", "Val_MIoU", | |
| "Val_IoU_BE", "Val_IoU_NPV", "Val_IoU_PV", | |
| "Val_F1_BE", "Val_F1_NPV", "Val_F1_PV", | |
| ] | |
| val_cols = [c for c in val_cols if c in df.columns] | |
| avg_test_cols = [ | |
| "Sensor", "Variant", "Scale", | |
| "Avg_Accuracy", "Avg_MIoU", | |
| "Avg_IoU_BE", "Avg_IoU_NPV", "Avg_IoU_PV", | |
| "Avg_F1_BE", "Avg_F1_NPV", "Avg_F1_PV", | |
| ] | |
| avg_test_cols = [c for c in avg_test_cols if c in df.columns] | |
| avg_val_cols = [ | |
| "Sensor", "Variant", "Scale", | |
| "Avg_Val_Accuracy", "Avg_Val_MIoU", | |
| "Avg_Val_IoU_BE", "Avg_Val_IoU_NPV", "Avg_Val_IoU_PV", | |
| "Avg_Val_F1_BE", "Avg_Val_F1_NPV", "Avg_Val_F1_PV", | |
| ] | |
| avg_val_cols = [c for c in avg_val_cols if c in df.columns] | |
| print("\n=== Best Block Test Metrics (BE / NPV / PV) ===") | |
| pd.set_option("display.float_format", "{:.4f}".format) | |
| pd.set_option("display.max_columns", None) | |
| pd.set_option("display.width", 200) | |
| if test_cols: | |
| print(df[test_cols].to_string(index=False)) | |
| else: | |
| print("No best-model test metrics found.") | |
| print("\n=== Best Block Validation Metrics (BE / NPV / PV) ===") | |
| if val_cols: | |
| print(df[val_cols].to_string(index=False)) | |
| else: | |
| print("No best-model validation metrics found.") | |
| print("\n=== Average Test Metrics Across Blocks (BE / NPV / PV) ===") | |
| if avg_test_cols: | |
| print(df[avg_test_cols].to_string(index=False)) | |
| else: | |
| print("No average test metrics found.") | |
| print("\n=== Average Validation Metrics Across Blocks (BE / NPV / PV) ===") | |
| if avg_val_cols: | |
| print(df[avg_val_cols].to_string(index=False)) | |
| else: | |
| print("No average validation metrics found.") | |
| print("\n=== Ranked by Test IoU_NPV (hardest class) ===") | |
| if "IoU_NPV" in df.columns: | |
| print(df.sort_values("IoU_NPV", ascending=False)[ | |
| ["Sensor", "Variant", "Scale", "IoU_BE", "IoU_NPV", "IoU_PV", "MIoU"] | |
| ].to_string(index=False)) | |
| else: | |
| print("No best-model test IoU_NPV found.") | |
| print("\n=== Ranked by Validation IoU_NPV (hardest class) ===") | |
| if "Val_IoU_NPV" in df.columns: | |
| print(df.sort_values("Val_IoU_NPV", ascending=False)[ | |
| ["Sensor", "Variant", "Scale", "Val_IoU_BE", "Val_IoU_NPV", "Val_IoU_PV", "Val_MIoU"] | |
| ].to_string(index=False)) | |
| else: | |
| print("No best-model validation IoU_NPV found.") | |
| print("\n=== Ranked by Average Test IoU_NPV Across Blocks ===") | |
| if "Avg_IoU_NPV" in df.columns: | |
| print(df.sort_values("Avg_IoU_NPV", ascending=False)[ | |
| ["Sensor", "Variant", "Scale", "Avg_IoU_BE", "Avg_IoU_NPV", "Avg_IoU_PV", "Avg_MIoU"] | |
| ].to_string(index=False)) | |
| else: | |
| print("No average test IoU_NPV found.") | |
| print("\n=== Ranked by Average Validation IoU_NPV Across Blocks ===") | |
| if "Avg_Val_IoU_NPV" in df.columns: | |
| print(df.sort_values("Avg_Val_IoU_NPV", ascending=False)[ | |
| ["Sensor", "Variant", "Scale", "Avg_Val_IoU_BE", "Avg_Val_IoU_NPV", "Avg_Val_IoU_PV", "Avg_Val_MIoU"] | |
| ].to_string(index=False)) | |
| else: | |
| print("No average validation IoU_NPV found.") | |
| print("\n=== Recommended Variant Per Sensor (Delta vs Baseline at Same Scale) ===") | |
| summary_df = build_baseline_delta_summary(df) | |
| if not summary_df.empty: | |
| print(summary_df[[ | |
| "Rank", | |
| "Sensor", | |
| "Recommended", | |
| "Scale", | |
| "Baseline_Avg_IoU_NPV", | |
| "Avg_IoU_NPV", | |
| "Delta_Avg_IoU_NPV", | |
| "Baseline_Avg_MIoU", | |
| "Avg_MIoU", | |
| "Delta_Avg_MIoU", | |
| "Baseline_Avg_Val_IoU_NPV", | |
| "Avg_Val_IoU_NPV", | |
| "Delta_Avg_Val_IoU_NPV", | |
| ]].to_string(index=False)) | |
| else: | |
| print("No baseline delta summary available.") | |
| print("\n=== Overall Model Ranking (metrics-first, lower transition as tie-breaker) ===") | |
| overall_df = build_overall_model_ranking(df) | |
| if not overall_df.empty: | |
| ranking_cols = [ | |
| "Rank", | |
| "Sensor", | |
| "Variant", | |
| "Scale", | |
| "Directory", | |
| "Avg_IoU_NPV", | |
| "Avg_Val_IoU_NPV", | |
| "Avg_MIoU", | |
| "Avg_Val_MIoU", | |
| "Sen_Transition_Fraction_Mean", | |
| "Overall_Score", | |
| ] | |
| ranking_cols = [col for col in ranking_cols if col in overall_df.columns] | |
| print(overall_df[ranking_cols].to_string(index=False)) | |
| export_path = export_table(overall_df[ranking_cols], "overall_model_ranking.csv") | |
| if export_path: | |
| print(f"Exported overall model ranking CSV: {export_path}") | |
| else: | |
| print("No overall ranking available.") | |
| print("\n=== FX10_FX17 Ranking (metrics-first, lower transition as tie-breaker) ===") | |
| fx10_fx17_df = build_overall_model_ranking(df[df["Sensor"] == "FX10_FX17"].copy()) | |
| if not fx10_fx17_df.empty: | |
| ranking_cols = [ | |
| "Rank", | |
| "Variant", | |
| "Scale", | |
| "Directory", | |
| "Avg_IoU_NPV", | |
| "Avg_Val_IoU_NPV", | |
| "Avg_MIoU", | |
| "Avg_Val_MIoU", | |
| "Sen_Transition_Fraction_Mean", | |
| "Overall_Score", | |
| "Sen_NDRE_NPV_minus_PV_Mean", | |
| "Sen_PSRI_NPV_minus_PV_Mean", | |
| "Sen_NDWI_860_1240_NPV_minus_PV_Mean", | |
| "Sen_ANMB1450_NPV_minus_PV_Mean", | |
| ] | |
| ranking_cols = [col for col in ranking_cols if col in fx10_fx17_df.columns] | |
| print(fx10_fx17_df[ranking_cols].to_string(index=False)) | |
| export_path = export_table(fx10_fx17_df[ranking_cols], "fx10_fx17_ranking.csv") | |
| if export_path: | |
| print(f"Exported FX10_FX17 ranking CSV: {export_path}") | |
| else: | |
| print("No FX10_FX17 ranking available.") | |
| print("\n=== FX10_FX17 Extensions-Only Ranking (metrics-first, excludes baseline) ===") | |
| fx10_fx17_extensions_df = build_overall_model_ranking( | |
| df[(df["Sensor"] == "FX10_FX17") & (df["Variant"] != "baseline")].copy() | |
| ) | |
| if not fx10_fx17_extensions_df.empty: | |
| ranking_cols = [ | |
| "Rank", | |
| "Variant", | |
| "Scale", | |
| "Directory", | |
| "Avg_IoU_NPV", | |
| "Avg_Val_IoU_NPV", | |
| "Avg_MIoU", | |
| "Avg_Val_MIoU", | |
| "Sen_Transition_Fraction_Mean", | |
| "Overall_Score", | |
| ] | |
| ranking_cols = [col for col in ranking_cols if col in fx10_fx17_extensions_df.columns] | |
| print(fx10_fx17_extensions_df[ranking_cols].to_string(index=False)) | |
| export_path = export_table(fx10_fx17_extensions_df[ranking_cols], "fx10_fx17_extensions_only_ranking.csv") | |
| if export_path: | |
| print(f"Exported FX10_FX17 extensions-only ranking CSV: {export_path}") | |
| else: | |
| print("No FX10_FX17 extensions-only ranking available.") | |
| print("\n=== Model-Driven Senescence Ranking (gradient/gate-based) ===") | |
| model_driven_df = build_model_driven_senescence_ranking(df) | |
| if not model_driven_df.empty: | |
| ranking_cols = [ | |
| "Rank", | |
| "Sensor", | |
| "Variant", | |
| "Scale", | |
| "Directory", | |
| "ModelSen_AbsSensitivityMean", | |
| "ModelSen_AbsSensitivityTopMean", | |
| "ModelSen_ClassResponseTopMean", | |
| "ModelSen_GateSelectivity", | |
| "Sen_Transition_Fraction_Mean", | |
| "ModelDriven_Senescence_Score", | |
| ] | |
| ranking_cols = [col for col in ranking_cols if col in model_driven_df.columns] | |
| print_model_driven_table(model_driven_df[ranking_cols]) | |
| export_path = export_table(model_driven_df[ranking_cols], "model_driven_senescence_ranking.csv") | |
| if export_path: | |
| print(f"Exported model-driven senescence ranking CSV: {export_path}") | |
| else: | |
| print("No model-driven senescence ranking available.") | |
| print("\n=== FX10_FX17 Extensions-Only Model-Driven Senescence Ranking ===") | |
| fx10_fx17_model_driven_df = build_model_driven_senescence_ranking( | |
| df[(df["Sensor"] == "FX10_FX17") & (df["Variant"] != "baseline")].copy() | |
| ) | |
| if not fx10_fx17_model_driven_df.empty: | |
| ranking_cols = [ | |
| "Rank", | |
| "Variant", | |
| "Scale", | |
| "Directory", | |
| "ModelSen_AbsSensitivityMean", | |
| "ModelSen_AbsSensitivityTopMean", | |
| "ModelSen_ClassResponseTopMean", | |
| "ModelSen_GateSelectivity", | |
| "Sen_Transition_Fraction_Mean", | |
| "ModelDriven_Senescence_Score", | |
| ] | |
| ranking_cols = [col for col in ranking_cols if col in fx10_fx17_model_driven_df.columns] | |
| print_model_driven_table(fx10_fx17_model_driven_df[ranking_cols]) | |
| export_path = export_table( | |
| fx10_fx17_model_driven_df[ranking_cols], | |
| "fx10_fx17_extensions_only_model_driven_senescence_ranking.csv", | |
| ) | |
| if export_path: | |
| print(f"Exported FX10_FX17 extensions-only model-driven ranking CSV: {export_path}") | |
| else: | |
| print("No FX10_FX17 extensions-only model-driven ranking available.") | |
| else: | |
| print("No data found.") | |