Download src/otfusion/fusion.py from BioinstLab/bnet-ot-fusion: direct link, hf CLI and curl.
- Browser
- Download file 8.46 kB
-
https://huggingface.co/BioinstLab/bnet-ot-fusion/resolve/main/src/otfusion/fusion.py
- Command line
-
hf download hf://BioinstLab/bnet-ot-fusion/src/otfusion/fusion.py
-
curl -L -o fusion.py https://huggingface.co/BioinstLab/bnet-ot-fusion/resolve/main/src/otfusion/fusion.py
8.46 kB
| """Sinkhorn-based optimal transport late fusion (Eqs. 13-19 of the paper). | |
| Notation follows the paper: | |
| * ``p`` - probability vector from the histopathology model, in the simplex Delta^2 (Eq. 13) | |
| * ``q`` - probability vector from the clinical risk model, in Delta^2 | |
| * class index 0 = benign / low risk, class index 1 = malignant / high risk | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import Optional, Union | |
| import numpy as np | |
| from .sinkhorn import sinkhorn_log | |
| UNIFORM = np.array([0.5, 0.5]) | |
| class FusionConfig: | |
| """Hyperparameters of the fusion layer. | |
| Defaults are the values reported in the paper. | |
| Attributes | |
| ---------- | |
| fp_weight: | |
| ``w_p`` in Eq. 17, the semantic cost on the (0, 1) entry. Paper value: 1.8. | |
| fn_weight: | |
| ``w_n`` in Eq. 17, the semantic cost on the (1, 0) entry. Paper value: 1.2. | |
| alpha: | |
| Blending factor between divergence cost and semantic cost in Eq. 17. | |
| A float uses that fixed value for every sample (paper value: 0.1). | |
| The string ``"dynamic"`` computes it per sample from model confidence (Eq. 16). | |
| reg: | |
| Entropic regularisation of the OT problem (Eq. 18). Paper value: 0.15. | |
| max_iter: | |
| Maximum Sinkhorn iterations. Paper value: 5000. | |
| stop_thr: | |
| Sinkhorn convergence threshold. Paper value: 1e-9. | |
| fallback_tol: | |
| If the final marginal violation exceeds this, the plan is replaced by the | |
| outer product p (x) q (the fallback described after Eq. 19). | |
| eps: | |
| Small constant for numerical stability in Eq. 16. | |
| """ | |
| fp_weight: float = 1.8 | |
| fn_weight: float = 1.2 | |
| alpha: Union[float, str] = 0.1 | |
| reg: float = 0.15 | |
| max_iter: int = 5000 | |
| stop_thr: float = 1e-9 | |
| fallback_tol: float = 1e-6 | |
| eps: float = 1e-8 | |
| def __post_init__(self) -> None: | |
| if isinstance(self.alpha, str): | |
| if self.alpha != "dynamic": | |
| raise ValueError('alpha must be a float in [0, 1] or "dynamic"') | |
| elif not 0.0 <= float(self.alpha) <= 1.0: | |
| raise ValueError("alpha must lie in [0, 1]") | |
| if self.reg <= 0: | |
| raise ValueError("reg must be positive") | |
| class FusionResult: | |
| """Output of :func:`sinkhorn_fusion`. | |
| Attributes | |
| ---------- | |
| fused: | |
| Fused probability vectors z (Eq. 19), shape (N, 2). | |
| plans: | |
| Transport plans T* (after any fallback), shape (N, 2, 2). | |
| costs: | |
| Cost matrices C (Eq. 17), shape (N, 2, 2). | |
| alpha: | |
| Blending factor used for each sample, shape (N,). | |
| p, q: | |
| Modality-aware inputs after uniform substitution (Eq. 15), shape (N, 2). | |
| errors: | |
| Final Sinkhorn marginal violation per sample, shape (N,). | |
| fallback: | |
| True where the outer-product fallback plan was used, shape (N,). | |
| """ | |
| fused: np.ndarray | |
| plans: np.ndarray | |
| costs: np.ndarray | |
| alpha: np.ndarray | |
| p: np.ndarray | |
| q: np.ndarray | |
| errors: np.ndarray | |
| fallback: np.ndarray | |
| def prob_positive(self) -> np.ndarray: | |
| """Fused probability of the positive (malignant) class, shape (N,).""" | |
| return self.fused[:, 1] | |
| # --------------------------------------------------------------------------- | |
| # Input handling | |
| # --------------------------------------------------------------------------- | |
| def to_distribution(probs: np.ndarray) -> np.ndarray: | |
| """Convert model output to probability vectors in Delta^2 (Eq. 13). | |
| Accepts positive-class probabilities of shape (N,) or (N, 1), or full | |
| two-class vectors of shape (N, 2). NaN entries are preserved so that they | |
| can be treated as a missing modality. | |
| """ | |
| probs = np.asarray(probs, dtype=np.float64) | |
| if probs.ndim == 2 and probs.shape[1] == 2: | |
| return probs.copy() | |
| if probs.ndim == 2 and probs.shape[1] == 1: | |
| probs = probs[:, 0] | |
| if probs.ndim != 1: | |
| raise ValueError("expected shape (N,), (N, 1) or (N, 2)") | |
| return np.column_stack([1.0 - probs, probs]) | |
| def modality_mask(p: np.ndarray, q: np.ndarray) -> tuple[np.ndarray, np.ndarray]: | |
| """Binary modality mask m = [m_p, m_q] (Eq. 14), inferred from NaNs. | |
| A modality is considered present for a sample when its probability vector | |
| contains no NaN. | |
| """ | |
| m_p = ~np.isnan(p).any(axis=1) | |
| m_q = ~np.isnan(q).any(axis=1) | |
| return m_p, m_q | |
| def substitute_missing( | |
| p: np.ndarray, q: np.ndarray, m_p: np.ndarray, m_q: np.ndarray | |
| ) -> tuple[np.ndarray, np.ndarray]: | |
| """Replace missing modalities with the uniform distribution u = [0.5, 0.5] (Eq. 15).""" | |
| m_p = np.asarray(m_p, dtype=bool)[:, None] | |
| m_q = np.asarray(m_q, dtype=bool)[:, None] | |
| p_tilde = np.where(m_p, np.nan_to_num(p), UNIFORM) | |
| q_tilde = np.where(m_q, np.nan_to_num(q), UNIFORM) | |
| return p_tilde, q_tilde | |
| # --------------------------------------------------------------------------- | |
| # Eqs. 16-17 | |
| # --------------------------------------------------------------------------- | |
| def dynamic_alpha(p: np.ndarray, q: np.ndarray, eps: float = 1e-8) -> np.ndarray: | |
| """Confidence-weighted fusion factor (Eq. 16). | |
| alpha = 2|p_1 - 0.5| / (2|p_1 - 0.5| + 2|q_1 - 0.5| + eps) | |
| Higher alpha means the histopathology prediction is the more confident one. | |
| """ | |
| conf_p = 2.0 * np.abs(p[:, 1] - 0.5) | |
| conf_q = 2.0 * np.abs(q[:, 1] - 0.5) | |
| return conf_p / (conf_p + conf_q + eps) | |
| def semantic_cost(fp_weight: float, fn_weight: float) -> np.ndarray: | |
| """Clinical penalty matrix C_semantic = [[0, w_p], [w_n, 0]] (Eq. 17).""" | |
| return np.array([[0.0, fp_weight], [fn_weight, 0.0]]) | |
| def cost_matrix( | |
| p: np.ndarray, q: np.ndarray, alpha: np.ndarray, fp_weight: float, fn_weight: float | |
| ) -> np.ndarray: | |
| """Per-sample cost matrix (Eq. 17). | |
| C_ij = alpha * (p_i - q_j)^2 + (1 - alpha) * C_semantic_ij | |
| """ | |
| divergence = (p[:, :, None] - q[:, None, :]) ** 2 | |
| a = np.asarray(alpha, dtype=np.float64)[:, None, None] | |
| return a * divergence + (1.0 - a) * semantic_cost(fp_weight, fn_weight)[None, :, :] | |
| # --------------------------------------------------------------------------- | |
| # Full fusion | |
| # --------------------------------------------------------------------------- | |
| def sinkhorn_fusion( | |
| p_hist: np.ndarray, | |
| p_risk: np.ndarray, | |
| config: Optional[FusionConfig] = None, | |
| m_p: Optional[np.ndarray] = None, | |
| m_q: Optional[np.ndarray] = None, | |
| ) -> FusionResult: | |
| """Fuse histopathology and clinical-risk predictions (Eqs. 13-19). | |
| Parameters | |
| ---------- | |
| p_hist, p_risk: | |
| Model outputs, shape (N,), (N, 1) or (N, 2). NaN marks a missing modality. | |
| config: | |
| Fusion hyperparameters. Defaults to the values reported in the paper. | |
| m_p, m_q: | |
| Optional explicit modality masks (Eq. 14). If omitted they are inferred | |
| from NaNs. When given, they are combined with the NaN mask, so a NaN | |
| input is always treated as missing. | |
| Returns | |
| ------- | |
| FusionResult | |
| """ | |
| cfg = config or FusionConfig() | |
| p = to_distribution(p_hist) | |
| q = to_distribution(p_risk) | |
| if p.shape != q.shape: | |
| raise ValueError("p_hist and p_risk must contain the same number of samples") | |
| nan_p, nan_q = modality_mask(p, q) | |
| m_p = nan_p if m_p is None else (np.asarray(m_p, dtype=bool) & nan_p) | |
| m_q = nan_q if m_q is None else (np.asarray(m_q, dtype=bool) & nan_q) | |
| p_tilde, q_tilde = substitute_missing(p, q, m_p, m_q) | |
| if cfg.alpha == "dynamic": | |
| alpha = dynamic_alpha(p_tilde, q_tilde, cfg.eps) | |
| else: | |
| alpha = np.full(p_tilde.shape[0], float(cfg.alpha)) | |
| costs = cost_matrix(p_tilde, q_tilde, alpha, cfg.fp_weight, cfg.fn_weight) | |
| result = sinkhorn_log( | |
| p_tilde, q_tilde, costs, reg=cfg.reg, max_iter=cfg.max_iter, stop_thr=cfg.stop_thr | |
| ) | |
| plans = result.plans.copy() | |
| fallback = ~np.isfinite(plans).all(axis=(1, 2)) | (result.errors > cfg.fallback_tol) | |
| if fallback.any(): | |
| plans[fallback] = p_tilde[fallback, :, None] * q_tilde[fallback, None, :] | |
| # Eq. 19: row marginal of the plan, normalised to the simplex | |
| row = plans.sum(axis=2) | |
| fused = row / row.sum(axis=1, keepdims=True) | |
| return FusionResult( | |
| fused=fused, | |
| plans=plans, | |
| costs=costs, | |
| alpha=alpha, | |
| p=p_tilde, | |
| q=q_tilde, | |
| errors=result.errors, | |
| fallback=fallback, | |
| ) | |