|
| 1 | +import json |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import torch |
| 5 | +from jsonargparse import CLI |
| 6 | +from sklearn.metrics import multilabel_confusion_matrix |
| 7 | + |
| 8 | +from chebai.preprocessing.datasets.base import XYBaseDataModule |
| 9 | +from chebai.result.utils import ( |
| 10 | + load_data_instance, |
| 11 | + load_model_for_inference, |
| 12 | + parse_config_file, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +class ClassesPropertiesGenerator: |
| 17 | + """ |
| 18 | + Computes PPV (Positive Predictive Value) and NPV (Negative Predictive Value) |
| 19 | + for each class in a multi-label classification problem using a PyTorch Lightning model. |
| 20 | + """ |
| 21 | + |
| 22 | + @staticmethod |
| 23 | + def load_class_labels(path: Path) -> list[str]: |
| 24 | + """ |
| 25 | + Load a list of class names from a .json or .txt file. |
| 26 | +
|
| 27 | + Args: |
| 28 | + path: Path to the class labels file (txt or json). |
| 29 | +
|
| 30 | + Returns: |
| 31 | + A list of class names, one per line. |
| 32 | + """ |
| 33 | + path = Path(path) |
| 34 | + with path.open() as f: |
| 35 | + return [line.strip() for line in f if line.strip()] |
| 36 | + |
| 37 | + @staticmethod |
| 38 | + def compute_tpv_npv( |
| 39 | + y_true: list[torch.Tensor], |
| 40 | + y_pred: list[torch.Tensor], |
| 41 | + class_names: list[str], |
| 42 | + ) -> dict[str, dict[str, float]]: |
| 43 | + """ |
| 44 | + Compute TPV (precision) and NPV for each class in a multi-label setting. |
| 45 | +
|
| 46 | + Args: |
| 47 | + y_true: List of binary ground-truth label tensors, one tensor per sample. |
| 48 | + y_pred: List of binary prediction tensors, one tensor per sample. |
| 49 | + class_names: Ordered list of class names corresponding to class indices. |
| 50 | +
|
| 51 | + Returns: |
| 52 | + Dictionary mapping each class name to its TPV and NPV metrics: |
| 53 | + { |
| 54 | + "class_name": {"PPV": float, "NPV": float}, |
| 55 | + ... |
| 56 | + } |
| 57 | + """ |
| 58 | + # Stack per-sample tensors into (n_samples, n_classes) numpy arrays |
| 59 | + true_np = torch.stack(y_true).cpu().numpy().astype(int) |
| 60 | + pred_np = torch.stack(y_pred).cpu().numpy().astype(int) |
| 61 | + |
| 62 | + # Compute confusion matrix for each class |
| 63 | + cm = multilabel_confusion_matrix(true_np, pred_np) |
| 64 | + |
| 65 | + results: dict[str, dict[str, float]] = {} |
| 66 | + for idx, cls_name in enumerate(class_names): |
| 67 | + tn, fp, fn, tp = cm[idx].ravel() |
| 68 | + tpv = tp / (tp + fp) if (tp + fp) > 0 else 0.0 |
| 69 | + npv = tn / (tn + fn) if (tn + fn) > 0 else 0.0 |
| 70 | + results[cls_name] = { |
| 71 | + "PPV": round(tpv, 4), |
| 72 | + "NPV": round(npv, 4), |
| 73 | + "TN": int(tn), |
| 74 | + "FP": int(fp), |
| 75 | + "FN": int(fn), |
| 76 | + "TP": int(tp), |
| 77 | + } |
| 78 | + return results |
| 79 | + |
| 80 | + def generate_props( |
| 81 | + self, |
| 82 | + model_ckpt_path: str, |
| 83 | + model_config_file_path: str, |
| 84 | + data_config_file_path: str, |
| 85 | + output_path: str | None = None, |
| 86 | + ) -> None: |
| 87 | + """ |
| 88 | + Run inference on validation set, compute TPV/NPV per class, and save to JSON. |
| 89 | +
|
| 90 | + Args: |
| 91 | + model_ckpt_path: Path to the PyTorch Lightning checkpoint file. |
| 92 | + model_config_file_path: Path to yaml config file of the model. |
| 93 | + data_config_file_path: Path to yaml config file of the data. |
| 94 | + output_path: Optional path where to write the JSON metrics file. |
| 95 | + Defaults to '<processed_dir_main>/classes.json'. |
| 96 | + """ |
| 97 | + print("Extracting validation data for computation...") |
| 98 | + |
| 99 | + data_cls_path, data_cls_kwargs = parse_config_file(data_config_file_path) |
| 100 | + data_module: XYBaseDataModule = load_data_instance( |
| 101 | + data_cls_path, data_cls_kwargs |
| 102 | + ) |
| 103 | + |
| 104 | + splits_file_path = Path(data_module.processed_dir_main, "splits.csv") |
| 105 | + if data_module.splits_file_path is None: |
| 106 | + if not splits_file_path.exists(): |
| 107 | + raise RuntimeError( |
| 108 | + "Either the data module should be initialized with a `splits_file_path`, " |
| 109 | + f"or the file `{splits_file_path}` must exists.\n" |
| 110 | + "This is to prevent the data module from dynamically generating the splits." |
| 111 | + ) |
| 112 | + |
| 113 | + print( |
| 114 | + f"`splits_file_path` is not provided as an initialization parameter to the data module\n" |
| 115 | + f"Using splits from the file {splits_file_path}" |
| 116 | + ) |
| 117 | + data_module.splits_file_path = splits_file_path |
| 118 | + |
| 119 | + model_class_path, model_kwargs = parse_config_file(model_config_file_path) |
| 120 | + model = load_model_for_inference( |
| 121 | + model_ckpt_path, model_class_path, model_kwargs |
| 122 | + ) |
| 123 | + |
| 124 | + val_loader = data_module.val_dataloader() |
| 125 | + print("Running inference on validation data...") |
| 126 | + |
| 127 | + y_true, y_pred = [], [] |
| 128 | + for batch_idx, batch in enumerate(val_loader): |
| 129 | + data = model._process_batch( # pylint: disable=W0212 |
| 130 | + batch, batch_idx=batch_idx |
| 131 | + ) |
| 132 | + labels = data["labels"] |
| 133 | + outputs = model(data, **data.get("model_kwargs", {})) |
| 134 | + logits = outputs["logits"] if isinstance(outputs, dict) else outputs |
| 135 | + preds = torch.sigmoid(logits) > 0.5 |
| 136 | + y_pred.extend(preds) |
| 137 | + y_true.extend(labels) |
| 138 | + |
| 139 | + print("Computing TPV and NPV metrics...") |
| 140 | + classes_file = Path(data_module.processed_dir_main) / "classes.txt" |
| 141 | + if output_path is None: |
| 142 | + output_file = Path(data_module.processed_dir_main) / "classes.json" |
| 143 | + else: |
| 144 | + output_file = Path(output_path) |
| 145 | + |
| 146 | + class_names = self.load_class_labels(classes_file) |
| 147 | + metrics = self.compute_tpv_npv(y_true, y_pred, class_names) |
| 148 | + |
| 149 | + with output_file.open("w") as f: |
| 150 | + json.dump(metrics, f, indent=2) |
| 151 | + print(f"Saved TPV/NPV metrics to {output_file}") |
| 152 | + |
| 153 | + |
| 154 | +class Main: |
| 155 | + """ |
| 156 | + CLI wrapper for ClassesPropertiesGenerator. |
| 157 | + """ |
| 158 | + |
| 159 | + def generate( |
| 160 | + self, |
| 161 | + model_ckpt_path: str, |
| 162 | + model_config_file_path: str, |
| 163 | + data_config_file_path: str, |
| 164 | + output_path: str | None = None, |
| 165 | + ) -> None: |
| 166 | + """ |
| 167 | + CLI command to generate TPV/NPV JSON. |
| 168 | +
|
| 169 | + Args: |
| 170 | + model_ckpt_path: Path to the PyTorch Lightning checkpoint file. |
| 171 | + model_config_file_path: Path to yaml config file of the model. |
| 172 | + data_config_file_path: Path to yaml config file of the data. |
| 173 | + output_path: Optional path where to write the JSON metrics file. |
| 174 | + Defaults to '<processed_dir_main>/classes.json'. |
| 175 | + """ |
| 176 | + generator = ClassesPropertiesGenerator() |
| 177 | + generator.generate_props( |
| 178 | + model_ckpt_path, |
| 179 | + model_config_file_path, |
| 180 | + data_config_file_path, |
| 181 | + output_path, |
| 182 | + ) |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + # _generate_classes_props_json.py generate \ |
| 187 | + # --model_ckpt_path "model/ckpt/path" \ |
| 188 | + # --model_config_file_path "model/config/file/path" \ |
| 189 | + # --data_config_file_path "data/config/file/path" \ |
| 190 | + # --output_path "output/file/path" # Optional |
| 191 | + CLI(Main, as_positional=False) |
0 commit comments