Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
187 changes: 85 additions & 102 deletions README.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions assets/mmcplus_overview.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ dependencies:
- param==1.9.3
- pillow==8.2.0
- plotly==5.3.1
- pot==0.9.5
- pytorch-lightning==1.4.7
- scikit-image==0.17.2
- scikit-learn==0.24.2
Expand Down
42 changes: 42 additions & 0 deletions src/model_drift/data/mgb_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import datetime



TRAIN_DATE_END = datetime.datetime(year=2019, month=10, day=1)
VAL_DATE_END = datetime.datetime(year=2020, month=1, day=1)
# shorter timeframe to speed up validation during training, measeurements start (year=2019, month=7, day=3)
#VAL_DATE_END = datetime.datetime(year=2019, month=10, day=21)

RAW_LABELS = [
'No Finding',
'Enlarged Cardiomediastinum',
'Cardiomegaly',
'Lung Lesion',
'Lung Opacity',
'Edema',
'Consolidation',
'Pneumonia',
'Atelectasis',
'Pneumothorax',
'Pleural Effusion',
'Pleural Other',
'Fracture',
'Support Devices',
]

LABEL_GROUPINGS = {
'Atelectasis': ['Atelectasis'],
'Cardiomegaly': ['Cardiomegaly'],
#'Consolidation': ['Consolidation'],
'Edema': ['Edema'],
#'Lung Lesion': ['Lung Lesion'],
# 'No Finding': ['No Finding'],
'Lung Opacity': ['Lung Opacity', 'Pneumonia', 'Consolidation', 'Lung Lesion', 'Atelectasis', 'Edema'],
'Pleural Other': ['Pleural Other'],
'Pleural Effusion': ['Pleural Effusion'],
'Pneumonia': ['Pneumonia'],
'Pneumothorax': ['Pneumothorax'],
'Support Devices': ['Support Devices'],
#'Enlarged Cardiomediastinum': ['Enlarged Cardiomediastinum', 'Cardiomegaly'],
#'Fracture': ['Fracture'],
}
6 changes: 3 additions & 3 deletions src/model_drift/drift/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ------------------------------------------------------------------------------------------
from .base import BaseDriftCalculator # noqa
from .categorical import ChiSqDriftCalculator # noqa
from .categorical import ChiSqDriftCalculator, ChiSqDriftCalculatorJackKnife, HellingerDriftCalculatorJackKnife # noqa
from .histogram import HistIntersectionCalculator, KdeHistPlotCalculator # noqa
from .collection import DriftCollectionCalculator # noqa
from .numeric import KSDriftCalculator, BasicDriftCalculator # noqa
from .numeric import KSDriftCalculator, BasicDriftCalculator, KSDriftCalculatorJackKnife, EMDDriftCalculatorJackKnife_1D, EMDDriftCalculatorJackKnife_woRef # noqa
from .performance import AUROCCalculator, ClassificationReportCalculator # noqa
from .sampler import Sampler # noqa
from .tabular import TabularDriftCalculator # noqa
from .tabular import TabularDriftCalculator # noqa
126 changes: 125 additions & 1 deletion src/model_drift/drift/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,25 @@
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ------------------------------------------------------------------------------------------
from collections import Counter
import math

import numpy as np
from scipy.stats import chi2_contingency, chi2

from model_drift.drift.base import BaseDriftCalculator


def merge_freqs(ref_counts, sample):
sample_counts = Counter(sample)
keys = set().union(ref_counts, sample_counts)
exp = np.array([ref_counts.get(k, 0) for k in keys])
obs = np.array([sample_counts.get(k, 0) for k in keys])
return exp, keys, obs

def hellinger_distance(p, q):
"""Hellinger distance between two discrete distributions.
"""
return math.sqrt(sum([ (math.sqrt(p_i) - math.sqrt(q_i))**2 for p_i, q_i in zip(p, q) ]) / 2)


class ChiSqDriftCalculator(BaseDriftCalculator):
name = "chi2"
Expand Down Expand Up @@ -53,3 +58,122 @@ def _predict(self, sample):
out['critical_diff'] = out['distance'] - out['critical_value']

return out



class ChiSqDriftCalculatorJackKnife(BaseDriftCalculator):
name = "chi2_jackknife"

def __init__(self, q_val=0.1, correction=True, lambda_=None, use_freq=False, include_critical_values=False,
**kwargs):
super().__init__(**kwargs)
self.q_val = q_val
self.correction = correction
self.lambda_ = lambda_
self.use_freq = use_freq
self.include_critical_values = include_critical_values

def convert(self, arg):
return arg.apply(str)

def prepare(self, ref, **kwargs):
self._ref_counts = Counter(ref)
super().prepare(ref)

def _predict(self, sample):

nref = len(self._ref)
nobs = len(sample)

ref1 = np.random.choice(self._ref, nobs)
ref2 = np.random.choice(self._ref, nobs)

ref1_counts = Counter(ref1)
ref2_counts = Counter(ref2)

exp_ref1_sam, keys, obs_ref1_sam = merge_freqs(ref1_counts, sample)

exp_ref1_ref2, keys, obs_ref1_ref2 = merge_freqs(ref1_counts, ref2_counts)

if self.use_freq:
exp_ref1_sam = exp_ref1_sam / exp_ref1_sam.sum()
obs_ref1_sam = obs_ref1_sam / obs_ref1_sam.sum()

exp_ref1_ref2 = exp_ref1_ref2 / exp_ref1_ref2.sum()
obs_ref1_ref2 = obs_ref1_ref2 / obs_ref1_ref2.sum()


out = {}

dist1, _, _, _ = chi2_contingency(np.vstack([exp_ref1_sam, obs_ref1_sam]),
correction=self.correction,
lambda_=self.lambda_)

dist2, _, _, _ = chi2_contingency(np.vstack([exp_ref1_ref2, obs_ref1_ref2]),
correction=self.correction,
lambda_=self.lambda_)

out["distance"] = max(dist1 - dist2, 0.0)
out['pval'] = float("NaN")


if self.include_critical_values:
raise NotImplementedError("Critical value not implemented for jackknife")

return out

class HellingerDriftCalculatorJackKnife(BaseDriftCalculator):
name = "hellinger_jackknife"

def __init__(self, q_val=0.1, correction=True, lambda_=None, use_freq=True, include_critical_values=False,
**kwargs):
super().__init__(**kwargs)
self.q_val = q_val
self.correction = correction
self.lambda_ = lambda_
self.use_freq = use_freq
self.include_critical_values = include_critical_values

def convert(self, arg):
return arg.apply(str)

def prepare(self, ref, **kwargs):
self._ref_counts = Counter(ref)
super().prepare(ref)

def _predict(self, sample):

nref = len(self._ref)
nobs = len(sample)

ref1 = np.random.choice(self._ref, nobs)
ref2 = np.random.choice(self._ref, nobs)

ref1_counts = Counter(ref1)
ref2_counts = Counter(ref2)

exp_ref1_sam, keys, obs_ref1_sam = merge_freqs(ref1_counts, sample)

exp_ref1_ref2, keys, obs_ref1_ref2 = merge_freqs(ref1_counts, ref2_counts)

if self.use_freq:
exp_ref1_sam = exp_ref1_sam / exp_ref1_sam.sum()
obs_ref1_sam = obs_ref1_sam / obs_ref1_sam.sum()

exp_ref1_ref2 = exp_ref1_ref2 / exp_ref1_ref2.sum()
obs_ref1_ref2 = obs_ref1_ref2 / obs_ref1_ref2.sum()

out = {}

dist1 = hellinger_distance(exp_ref1_sam, obs_ref1_sam)
dist2 = hellinger_distance(exp_ref1_ref2, obs_ref1_ref2)


out["distance"] = max(dist1 - dist2, 0.0)
out['pval'] = float("NaN")


if self.include_critical_values:
raise NotImplementedError("Critical value not implemented for jackknife")

return out
44 changes: 44 additions & 0 deletions src/model_drift/drift/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

from model_drift.drift import ChiSqDriftCalculator, KSDriftCalculator, TabularDriftCalculator
from model_drift.drift import HistIntersectionCalculator, KdeHistPlotCalculator
from model_drift.drift import EMDDriftCalculatorJackKnife_1D, EMDDriftCalculatorJackKnife_woRef
from model_drift.drift import HellingerDriftCalculatorJackKnife


def match_keys(keys, regex_list) -> List[str]:
Expand Down Expand Up @@ -119,3 +121,45 @@ def add_metadata_metrics(dwc: TabularDriftCalculator, col: str):
elif col in metadata_cols:
add_metadata_metrics(dwc, col)
return dwc


def mmcplus_config(dataframe, embedding_cols=r"^embedding$", score_cols=r"^activation$",
metadata_float_cols=(), metadata_cat_cols=()):
"""Drift calculators for MMC+.

Each cell of an embedding or score column holds one study's full vector (e.g. the image embedding or the
classifier's output probabilities); these are compared with the multivariate Wasserstein distance. Numeric
metadata uses the 1D Wasserstein distance and categorical metadata the Hellinger distance. The reference
window is resampled inside each calculator, so use with `model_drift.drift.sampler.DummySampler`.
"""
if isinstance(embedding_cols, six.string_types):
embedding_cols = [embedding_cols]

if isinstance(score_cols, six.string_types):
score_cols = [score_cols]

def add_embedding_metrics(dwc: TabularDriftCalculator, col: str):
dwc.add_drift_stat(col, EMDDriftCalculatorJackKnife_woRef(), drilldown=False, group="appearance")

def add_score_metrics(dwc: TabularDriftCalculator, col: str):
dwc.add_drift_stat(col, EMDDriftCalculatorJackKnife_woRef(), drilldown=False, group="ai")

def add_metadata_metrics(dwc: TabularDriftCalculator, col: str):
if col in metadata_float_cols:
dwc.add_drift_stat(col, EMDDriftCalculatorJackKnife_1D(), drilldown=False, group="metadata")
elif col in metadata_cat_cols:
dwc.add_drift_stat(col, HellingerDriftCalculatorJackKnife(), drilldown=False, group="metadata")

score_cols = match_keys(list(dataframe), score_cols)
embedding_cols = match_keys(list(dataframe), embedding_cols)
metadata_cols = list(metadata_float_cols) + list(metadata_cat_cols)

dwc = TabularDriftCalculator()
for col in dataframe.columns:
if col in score_cols:
add_score_metrics(dwc, col)
elif col in embedding_cols:
add_embedding_metrics(dwc, col)
elif col in metadata_cols:
add_metadata_metrics(dwc, col)
return dwc
Loading