File size: 2,019 Bytes
3c8ce9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | """Simulated modality dropout.
The paper evaluates robustness by randomly omitting one input source at
inference time, at dropout rates of 20% and 50%. A dropped modality is passed
to the fusion layer as missing (mask = 0), which substitutes the uniform
distribution (Eq. 15).
"""
from __future__ import annotations
from typing import Optional
import numpy as np
MODES = ("either", "hist", "risk", "both")
def simulate_dropout(
n: int,
rate: float,
mode: str = "either",
rng: Optional[np.random.Generator] = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Draw modality masks (m_p, m_q) with a given dropout rate.
Parameters
----------
n:
Number of samples.
rate:
Fraction of samples affected by dropout, in [0, 1].
mode:
``"either"`` (default) - each affected sample loses one modality, chosen
uniformly at random (this matches "randomly omitting 1 input source").
``"hist"`` - affected samples lose the histopathology input.
``"risk"`` - affected samples lose the clinical risk input.
``"both"`` - affected samples lose both inputs.
rng:
NumPy random generator, for reproducibility.
Returns
-------
(m_p, m_q):
Boolean presence masks, shape (n,). True means the modality is present.
"""
if not 0.0 <= rate <= 1.0:
raise ValueError("rate must lie in [0, 1]")
if mode not in MODES:
raise ValueError(f"mode must be one of {MODES}")
rng = rng if rng is not None else np.random.default_rng()
affected = rng.random(n) < rate
m_p = np.ones(n, dtype=bool)
m_q = np.ones(n, dtype=bool)
if mode == "hist":
m_p[affected] = False
elif mode == "risk":
m_q[affected] = False
elif mode == "both":
m_p[affected] = False
m_q[affected] = False
else: # either
drop_hist = rng.random(n) < 0.5
m_p[affected & drop_hist] = False
m_q[affected & ~drop_hist] = False
return m_p, m_q
|