|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Leave-one-feature-out analysis for the semi-supervised filter. |
| 3 | +
|
| 4 | +This script reuses the `Filter.semiSupRandomForest` training loop and reruns it |
| 5 | +multiple times while removing one feature at a time. The difference in the |
| 6 | +final out-of-bag (OOB) error provides an intuitive importance score: if dropping |
| 7 | +an evidence track increases the OOB error, that feature contributes useful |
| 8 | +signal to the classifier. |
| 9 | +
|
| 10 | +Example: |
| 11 | + python bin/filter_feature_importance.py FILTER/data.tsv results/busco/run.tsv \ |
| 12 | + --output-table FILTER/feature_importance.tsv |
| 13 | +""" |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import argparse |
| 17 | +import json |
| 18 | +import math |
| 19 | +import os |
| 20 | +from typing import Dict, List |
| 21 | + |
| 22 | +import pandas as pd |
| 23 | + |
| 24 | +from Filter import semiSupRandomForest |
| 25 | + |
| 26 | + |
| 27 | +def parse_args() -> argparse.Namespace: |
| 28 | + parser = argparse.ArgumentParser( |
| 29 | + description="Leave-one-feature-out analysis for the Sylvan filter" |
| 30 | + ) |
| 31 | + parser.add_argument( |
| 32 | + "data", |
| 33 | + help="Path to the TSV created by Filter.filter_genes (e.g. FILTER/data.tsv)", |
| 34 | + ) |
| 35 | + parser.add_argument( |
| 36 | + "busco", |
| 37 | + help=( |
| 38 | + "Path to the BUSCO table used for monitoring (same input passed to " |
| 39 | + "Filter.py)." |
| 40 | + ), |
| 41 | + ) |
| 42 | + parser.add_argument( |
| 43 | + "--features", |
| 44 | + nargs="*", |
| 45 | + default=None, |
| 46 | + help=( |
| 47 | + "Explicit list of feature columns to evaluate. The default uses all " |
| 48 | + "columns except transcript_id/label and anything listed via --ignore." |
| 49 | + ), |
| 50 | + ) |
| 51 | + parser.add_argument( |
| 52 | + "--ignore", |
| 53 | + nargs="*", |
| 54 | + default=[], |
| 55 | + help="Columns in the data TSV that should never be used as model features.", |
| 56 | + ) |
| 57 | + parser.add_argument( |
| 58 | + "--trees", |
| 59 | + type=int, |
| 60 | + default=100, |
| 61 | + help="Number of trees per random forest run (default: 100)", |
| 62 | + ) |
| 63 | + parser.add_argument( |
| 64 | + "--predictors", |
| 65 | + type=int, |
| 66 | + default=6, |
| 67 | + help="max_features hyperparameter for RandomForestClassifier (default: 6)", |
| 68 | + ) |
| 69 | + parser.add_argument( |
| 70 | + "--max-iter", |
| 71 | + type=int, |
| 72 | + default=5, |
| 73 | + help=( |
| 74 | + "Maximum number of recycling iterations used by the semi-supervised " |
| 75 | + "training loop (default: 5)" |
| 76 | + ), |
| 77 | + ) |
| 78 | + parser.add_argument( |
| 79 | + "--recycle", |
| 80 | + type=float, |
| 81 | + default=0.95, |
| 82 | + help=( |
| 83 | + "Prediction probability threshold required to recycle unlabeled " |
| 84 | + "examples (default: 0.95)" |
| 85 | + ), |
| 86 | + ) |
| 87 | + parser.add_argument( |
| 88 | + "--seed", |
| 89 | + type=int, |
| 90 | + default=123, |
| 91 | + help="Random seed passed to RandomForestClassifier (default: 123)", |
| 92 | + ) |
| 93 | + parser.add_argument( |
| 94 | + "--output-table", |
| 95 | + default=None, |
| 96 | + help=( |
| 97 | + "Output TSV summarizing the baseline run and each leave-one-feature-out " |
| 98 | + "experiment (default: <data_dir>/feature_importance.tsv)" |
| 99 | + ), |
| 100 | + ) |
| 101 | + parser.add_argument( |
| 102 | + "--output-json", |
| 103 | + default=None, |
| 104 | + help=( |
| 105 | + "Optional JSON file capturing the same summary (default: " |
| 106 | + "<data_dir>/feature_importance.json)" |
| 107 | + ), |
| 108 | + ) |
| 109 | + return parser.parse_args() |
| 110 | + |
| 111 | + |
| 112 | +def resolve_feature_list(df: pd.DataFrame, include: List[str] | None, ignore: List[str]) -> List[str]: |
| 113 | + """Return the ordered feature list used for training/ablation.""" |
| 114 | + metadata_cols = {"transcript_id", "label"} |
| 115 | + metadata_cols.update(ignore or []) |
| 116 | + default_features = [c for c in df.columns if c not in metadata_cols] |
| 117 | + |
| 118 | + if include: |
| 119 | + missing = sorted(set(include) - set(default_features)) |
| 120 | + if missing: |
| 121 | + raise ValueError( |
| 122 | + f"Requested feature(s) not found in data columns: {', '.join(missing)}" |
| 123 | + ) |
| 124 | + return include |
| 125 | + |
| 126 | + return default_features |
| 127 | + |
| 128 | + |
| 129 | +def summarize_process(process: Dict[str, List[float]]) -> Dict[str, float]: |
| 130 | + """Extract final iteration statistics from the training process log.""" |
| 131 | + def last(seq: List[float]) -> float: |
| 132 | + if not seq: |
| 133 | + return float("nan") |
| 134 | + return seq[-1] |
| 135 | + |
| 136 | + return { |
| 137 | + "iterations": len(process.get("kept", [])), |
| 138 | + "final_kept": last(process.get("kept", [])), |
| 139 | + "final_discarded": last(process.get("discarded", [])), |
| 140 | + "final_kept_buscos": last(process.get("kept_buscos", [])), |
| 141 | + "final_discarded_buscos": last(process.get("discarded_buscos", [])), |
| 142 | + "final_oob_error": last(process.get("OOB", [])), |
| 143 | + } |
| 144 | + |
| 145 | + |
| 146 | +def run_filter( |
| 147 | + data: pd.DataFrame, |
| 148 | + features: List[str], |
| 149 | + busco_path: str, |
| 150 | + args: argparse.Namespace, |
| 151 | +) -> Dict[str, float]: |
| 152 | + subset_cols = ["transcript_id", "label"] + features |
| 153 | + subset = data.loc[:, subset_cols].copy() |
| 154 | + _, process = semiSupRandomForest( |
| 155 | + subset, |
| 156 | + args.predictors, |
| 157 | + busco_path, |
| 158 | + args.trees, |
| 159 | + seed=args.seed, |
| 160 | + recycle_prob=args.recycle, |
| 161 | + maxiter=args.max_iter, |
| 162 | + ) |
| 163 | + return summarize_process(process) |
| 164 | + |
| 165 | + |
| 166 | +def format_delta(value: float) -> str: |
| 167 | + if value is None or math.isnan(value): |
| 168 | + return "nan" |
| 169 | + return f"{value:+.4f}" |
| 170 | + |
| 171 | + |
| 172 | +def main() -> None: |
| 173 | + args = parse_args() |
| 174 | + data = pd.read_csv(args.data, sep="\t") |
| 175 | + |
| 176 | + feature_list = resolve_feature_list(data, args.features, args.ignore) |
| 177 | + if not feature_list: |
| 178 | + raise ValueError("No usable features detected in data TSV.") |
| 179 | + |
| 180 | + out_dir = os.path.dirname(os.path.abspath(args.data)) |
| 181 | + table_path = args.output_table or os.path.join(out_dir, "feature_importance.tsv") |
| 182 | + json_path = args.output_json or os.path.join(out_dir, "feature_importance.json") |
| 183 | + |
| 184 | + print(f"Running baseline model with {len(feature_list)} features...") |
| 185 | + baseline = run_filter(data, feature_list, args.busco, args) |
| 186 | + baseline_row = { |
| 187 | + "feature_removed": "(none)", |
| 188 | + "num_features": len(feature_list), |
| 189 | + "oob_delta": 0.0, |
| 190 | + **baseline, |
| 191 | + } |
| 192 | + |
| 193 | + results = [baseline_row] |
| 194 | + for feature in feature_list: |
| 195 | + reduced = [f for f in feature_list if f != feature] |
| 196 | + if not reduced: |
| 197 | + continue |
| 198 | + print(f"Dropping '{feature}' ({len(reduced)} features remaining)...") |
| 199 | + summary = run_filter(data, reduced, args.busco, args) |
| 200 | + summary_row = { |
| 201 | + "feature_removed": feature, |
| 202 | + "num_features": len(reduced), |
| 203 | + "oob_delta": summary["final_oob_error"] - baseline["final_oob_error"], |
| 204 | + **summary, |
| 205 | + } |
| 206 | + results.append(summary_row) |
| 207 | + delta_str = format_delta(summary_row["oob_delta"]) |
| 208 | + print( |
| 209 | + f" -> final OOB error: {summary_row['final_oob_error']:.4f} " |
| 210 | + f"(delta {delta_str})" |
| 211 | + ) |
| 212 | + |
| 213 | + df = pd.DataFrame(results) |
| 214 | + df.to_csv(table_path, sep="\t", index=False) |
| 215 | + print(f"\nSummary written to {table_path}") |
| 216 | + |
| 217 | + if json_path: |
| 218 | + json_ready = [] |
| 219 | + for row in results: |
| 220 | + json_ready.append( |
| 221 | + { |
| 222 | + k: (None if isinstance(v, float) and math.isnan(v) else v) |
| 223 | + for k, v in row.items() |
| 224 | + } |
| 225 | + ) |
| 226 | + with open(json_path, "w", encoding="utf-8") as fh: |
| 227 | + json.dump({"runs": json_ready}, fh, indent=2) |
| 228 | + print(f"JSON summary written to {json_path}") |
| 229 | + |
| 230 | + |
| 231 | +if __name__ == "__main__": |
| 232 | + main() |
0 commit comments