Upload 18 files
Browse files
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
.cache/
|
milk10k_effb2_dermoscopic_metadata/__pycache__/data.cpython-314.pyc
ADDED
|
Binary file (27.8 kB). View file
|
|
|
milk10k_effb2_dermoscopic_metadata/data.py
CHANGED
|
@@ -113,6 +113,10 @@ def synthetic_mask(df: pd.DataFrame) -> np.ndarray:
|
|
| 113 |
return mask
|
| 114 |
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
def create_or_load_split(
|
| 117 |
df: pd.DataFrame, manifest: Path, val_size: float, seed: int,
|
| 118 |
synthetic_train_only: bool = False, fold_index: int = 0, k_folds: int = 1,
|
|
@@ -138,12 +142,18 @@ def create_or_load_split(
|
|
| 138 |
raise ValueError(f"Split manifest has overlapping train/validation IDs: {manifest}")
|
| 139 |
unknown = (train_ids | val_ids) - all_ids
|
| 140 |
missing = all_ids - (train_ids | val_ids)
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
raise ValueError(f"Split manifest does not match dataset (unknown={len(unknown)}, missing={len(missing)}).")
|
| 143 |
else:
|
| 144 |
synthetic = synthetic_mask(df)
|
| 145 |
base = df.loc[~synthetic].copy() if synthetic_train_only else df.copy()
|
| 146 |
-
extra_train_ids = set(df.loc[synthetic, "lesion_id"].astype(str)) if synthetic_train_only else set()
|
| 147 |
folds = []
|
| 148 |
if k_folds == 1:
|
| 149 |
train_rows, val_rows = train_test_split(base, test_size=val_size, stratify=base["label"], random_state=seed)
|
|
@@ -155,9 +165,23 @@ def create_or_load_split(
|
|
| 155 |
splitter = StratifiedKFold(k_folds, shuffle=True, random_state=seed)
|
| 156 |
pairs = [(base.iloc[tr], base.iloc[va]) for tr, va in splitter.split(base, base["label"])]
|
| 157 |
for train_rows, val_rows in pairs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
folds.append({
|
| 159 |
"train_lesion_ids": sorted(set(train_rows["lesion_id"].astype(str)) | extra_train_ids),
|
| 160 |
"val_lesion_ids": sorted(set(val_rows["lesion_id"].astype(str))),
|
|
|
|
| 161 |
})
|
| 162 |
train_ids = set(folds[fold_index]["train_lesion_ids"]); val_ids = set(folds[fold_index]["val_lesion_ids"])
|
| 163 |
manifest.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -180,6 +204,14 @@ def append_augmented_rows(base_df: pd.DataFrame, train_df: pd.DataFrame, args) -
|
|
| 180 |
if args.augmented_data_dir is None: return train_df
|
| 181 |
augmented = load_dermoscopic_dataframe(args.augmented_data_dir)
|
| 182 |
augmented = augmented[~augmented["lesion_id"].astype(str).isin(set(base_df["lesion_id"].astype(str)))].copy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
if args.augmented_classes:
|
| 184 |
allowed = {name.upper() for name in args.augmented_classes}
|
| 185 |
unknown = allowed - {name.upper() for name in base_df["label"].unique()}
|
|
|
|
| 113 |
return mask
|
| 114 |
|
| 115 |
|
| 116 |
+
def source_lesion_id(value: Any) -> str:
|
| 117 |
+
return str(value).split("__sdpair_", 1)[0]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
def create_or_load_split(
|
| 121 |
df: pd.DataFrame, manifest: Path, val_size: float, seed: int,
|
| 122 |
synthetic_train_only: bool = False, fold_index: int = 0, k_folds: int = 1,
|
|
|
|
| 142 |
raise ValueError(f"Split manifest has overlapping train/validation IDs: {manifest}")
|
| 143 |
unknown = (train_ids | val_ids) - all_ids
|
| 144 |
missing = all_ids - (train_ids | val_ids)
|
| 145 |
+
allowed_missing = set()
|
| 146 |
+
if synthetic_train_only:
|
| 147 |
+
allowed_missing = {
|
| 148 |
+
lesion_id for lesion_id in missing
|
| 149 |
+
if "__sdpair_" in lesion_id and source_lesion_id(lesion_id) in val_ids
|
| 150 |
+
}
|
| 151 |
+
unexpected_missing = missing - allowed_missing
|
| 152 |
+
if unknown or unexpected_missing:
|
| 153 |
raise ValueError(f"Split manifest does not match dataset (unknown={len(unknown)}, missing={len(missing)}).")
|
| 154 |
else:
|
| 155 |
synthetic = synthetic_mask(df)
|
| 156 |
base = df.loc[~synthetic].copy() if synthetic_train_only else df.copy()
|
|
|
|
| 157 |
folds = []
|
| 158 |
if k_folds == 1:
|
| 159 |
train_rows, val_rows = train_test_split(base, test_size=val_size, stratify=base["label"], random_state=seed)
|
|
|
|
| 165 |
splitter = StratifiedKFold(k_folds, shuffle=True, random_state=seed)
|
| 166 |
pairs = [(base.iloc[tr], base.iloc[va]) for tr, va in splitter.split(base, base["label"])]
|
| 167 |
for train_rows, val_rows in pairs:
|
| 168 |
+
train_real_ids = set(train_rows["lesion_id"].astype(str))
|
| 169 |
+
val_real_ids = set(val_rows["lesion_id"].astype(str))
|
| 170 |
+
extra_train_ids = set()
|
| 171 |
+
excluded_synthetic_ids = set()
|
| 172 |
+
if synthetic_train_only:
|
| 173 |
+
for lesion_id in df.loc[synthetic, "lesion_id"].astype(str):
|
| 174 |
+
source_id = source_lesion_id(lesion_id)
|
| 175 |
+
if source_id in train_real_ids:
|
| 176 |
+
extra_train_ids.add(lesion_id)
|
| 177 |
+
elif source_id in val_real_ids:
|
| 178 |
+
excluded_synthetic_ids.add(lesion_id)
|
| 179 |
+
else:
|
| 180 |
+
raise ValueError(f"Synthetic lesion has unknown source ID: {lesion_id}")
|
| 181 |
folds.append({
|
| 182 |
"train_lesion_ids": sorted(set(train_rows["lesion_id"].astype(str)) | extra_train_ids),
|
| 183 |
"val_lesion_ids": sorted(set(val_rows["lesion_id"].astype(str))),
|
| 184 |
+
"excluded_synthetic_lesion_ids": sorted(excluded_synthetic_ids),
|
| 185 |
})
|
| 186 |
train_ids = set(folds[fold_index]["train_lesion_ids"]); val_ids = set(folds[fold_index]["val_lesion_ids"])
|
| 187 |
manifest.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 204 |
if args.augmented_data_dir is None: return train_df
|
| 205 |
augmented = load_dermoscopic_dataframe(args.augmented_data_dir)
|
| 206 |
augmented = augmented[~augmented["lesion_id"].astype(str).isin(set(base_df["lesion_id"].astype(str)))].copy()
|
| 207 |
+
train_source_ids = set(train_df["lesion_id"].astype(str).map(source_lesion_id))
|
| 208 |
+
base_source_ids = set(base_df["lesion_id"].astype(str).map(source_lesion_id))
|
| 209 |
+
augmented["source_lesion_id"] = augmented["lesion_id"].astype(str).map(source_lesion_id)
|
| 210 |
+
unknown = ~augmented["source_lesion_id"].isin(base_source_ids)
|
| 211 |
+
if unknown.any():
|
| 212 |
+
examples = augmented.loc[unknown, "lesion_id"].astype(str).head(5).tolist()
|
| 213 |
+
raise ValueError(f"Augmented lesions have unknown source IDs. Examples: {examples}")
|
| 214 |
+
augmented = augmented[augmented["source_lesion_id"].isin(train_source_ids)].copy()
|
| 215 |
if args.augmented_classes:
|
| 216 |
allowed = {name.upper() for name in args.augmented_classes}
|
| 217 |
unknown = allowed - {name.upper() for name in base_df["label"].unique()}
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy
|
| 2 |
+
pandas
|
| 3 |
+
pillow
|
| 4 |
+
scikit-learn
|
| 5 |
+
timm
|
| 6 |
+
torch
|
| 7 |
+
torchvision
|
| 8 |
+
tqdm
|
tests/__pycache__/test_parity.cpython-314.pyc
ADDED
|
Binary file (17.9 kB). View file
|
|
|
tests/test_parity.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import argparse,json,tempfile,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from unittest.mock import patch
|
| 5 |
+
import numpy as np,pandas as pd,torch
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
from milk10k_effb2_dermoscopic_metadata.data import (DermoscopicMetadataDataset,append_augmented_rows,
|
| 10 |
+
create_or_load_split,fit_metadata_spec,metadata_vector,source_lesion_id,synthetic_mask)
|
| 11 |
+
from milk10k_effb2_dermoscopic_metadata.losses import LDAMLoss,build_loss
|
| 12 |
+
from milk10k_effb2_dermoscopic_metadata.model import DermoscopicMetadataClassifier
|
| 13 |
+
from milk10k_effb2_dermoscopic_metadata.training import parse_args,train_split
|
| 14 |
+
from milk10k_effb2_dermoscopic_metadata.inference import parse_args as parse_inference_args,run as run_inference
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FakeEncoder(nn.Module):
|
| 18 |
+
num_features=8
|
| 19 |
+
def forward(self,x):
|
| 20 |
+
pooled=x.mean((2,3));return torch.cat([pooled,pooled,pooled[:,:2]],1)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def rows(root,count=12):
|
| 24 |
+
result=[]
|
| 25 |
+
for i in range(count):
|
| 26 |
+
path=root/f"{i}.jpg";Image.fromarray(np.full((24,24,3),100+i,dtype=np.uint8)).save(path)
|
| 27 |
+
result.append({"lesion_id":f"L{i}","isic_id":f"I{i}","image_path":str(path),"label":"A" if i%2==0 else "B",
|
| 28 |
+
"age_approx":50,"sex":"x","skin_tone_class":2,"site":"arm","MONET_hair":.1,
|
| 29 |
+
"is_augmented":False,"ignore_metadata":False})
|
| 30 |
+
return pd.DataFrame(result)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ParityTests(unittest.TestCase):
|
| 34 |
+
def test_manifest_v2_synthetic_never_in_validation_and_kfold_reuses(self):
|
| 35 |
+
df=pd.DataFrame([{"lesion_id":f"R{i}","label":"A" if i%2==0 else "B"} for i in range(20)]+[
|
| 36 |
+
{"lesion_id":f"R{i}__sdpair_{i}","label":"A" if i%2==0 else "B"} for i in range(4)])
|
| 37 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 38 |
+
path=Path(tmp)/"split.json"
|
| 39 |
+
for fold in range(3):
|
| 40 |
+
tr,va=create_or_load_split(df,path,.2,42,True,fold,3)
|
| 41 |
+
self.assertFalse(synthetic_mask(va).any())
|
| 42 |
+
train_sources=set(tr.loc[~synthetic_mask(tr),"lesion_id"].astype(str))
|
| 43 |
+
val_sources=set(va["lesion_id"].astype(str))
|
| 44 |
+
synthetic_sources={source_lesion_id(x) for x in tr.loc[synthetic_mask(tr),"lesion_id"]}
|
| 45 |
+
self.assertTrue(synthetic_sources <= train_sources)
|
| 46 |
+
self.assertFalse(synthetic_sources & val_sources)
|
| 47 |
+
payload=json.loads(path.read_text());self.assertEqual(payload["schema_version"],2);self.assertEqual(len(payload["folds"]),3)
|
| 48 |
+
|
| 49 |
+
def test_legacy_manifest_with_synthetic_validation_is_rejected(self):
|
| 50 |
+
df=pd.DataFrame([{"lesion_id":"A","label":"X"},{"lesion_id":"B__sdpair_1","label":"X"}])
|
| 51 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 52 |
+
path=Path(tmp)/"split.json";path.write_text(json.dumps({"train_lesion_ids":["A"],"val_lesion_ids":["B__sdpair_1"]}))
|
| 53 |
+
with self.assertRaisesRegex(ValueError,"synthetic validation"):create_or_load_split(df,path,.2,1,True)
|
| 54 |
+
|
| 55 |
+
def test_appended_augmentation_cap_and_zero_metadata(self):
|
| 56 |
+
base=pd.DataFrame([{"lesion_id":"base","label":"A"}]);aug=pd.DataFrame([
|
| 57 |
+
{"lesion_id":f"base__sdpair_{i}","label":"A","age_approx":1} for i in range(4)])
|
| 58 |
+
args=argparse.Namespace(augmented_data_dir=Path("x"),augmented_classes=["A"],augmented_max_per_class=2,seed=1,zero_augmented_metadata=True)
|
| 59 |
+
with patch("milk10k_effb2_dermoscopic_metadata.data.load_dermoscopic_dataframe",return_value=aug):
|
| 60 |
+
result=append_augmented_rows(base,base.copy(),args)
|
| 61 |
+
self.assertEqual(len(result),3);self.assertEqual(sum(bool(x) for x in result.ignore_metadata if pd.notna(x)),2)
|
| 62 |
+
|
| 63 |
+
def test_sampler_power_and_zero_metadata_dataset(self):
|
| 64 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 65 |
+
df=rows(Path(tmp),4);df.loc[0,"ignore_metadata"]=True;spec=fit_metadata_spec(df)
|
| 66 |
+
ds=DermoscopicMetadataDataset(df,{"A":0,"B":1},spec,lambda _:torch.zeros(3,8,8))
|
| 67 |
+
self.assertTrue(torch.all(ds[0]["metadata"]==0))
|
| 68 |
+
|
| 69 |
+
def test_all_losses_and_ldam_epoch_switch(self):
|
| 70 |
+
df=pd.DataFrame({"label":["A","A","B","B"]});mapping={"A":0,"B":1};device=torch.device("cpu")
|
| 71 |
+
base=dict(class_weight=True,focal_gamma=2.,dice_weight=.3,f1_weight=.3,f1_ignore_classes=[],f1_class_weight=[],
|
| 72 |
+
ldam_beta=.9,ldam_max_margin=.5,ldam_drw_start_epoch=2,ldam_alpha_max=10.)
|
| 73 |
+
logits=torch.randn(4,2,requires_grad=True);labels=torch.tensor([0,0,1,1])
|
| 74 |
+
for name in ("ce","focal","ldam","ce_dice","ce_f1"):
|
| 75 |
+
loss=build_loss(df,mapping,argparse.Namespace(loss=name,**base),device);value=loss(logits,labels);self.assertTrue(torch.isfinite(value))
|
| 76 |
+
ldam=build_loss(df,mapping,argparse.Namespace(loss="ldam",**base),device);self.assertIsInstance(ldam,LDAMLoss);ldam.set_epoch(3);self.assertEqual(ldam.current_epoch,3)
|
| 77 |
+
|
| 78 |
+
def test_model_modes_and_old_checkpoint_shape(self):
|
| 79 |
+
with patch("milk10k_effb2_dermoscopic_metadata.model.timm.create_model",return_value=FakeEncoder()):
|
| 80 |
+
for mode in ("none","concat","gated_concat","gated_only"):
|
| 81 |
+
model=DermoscopicMetadataClassifier(2,7,mode,imagenet_pretrained=False,branch_dim=8,metadata_dim=4,classifier_hidden_dim=6,metadata_gate_hidden_dim=3)
|
| 82 |
+
self.assertEqual(tuple(model(torch.rand(2,3,8,8),torch.rand(2,7)).shape),(2,2))
|
| 83 |
+
|
| 84 |
+
def test_training_outputs_checkpoint_v2_and_resume(self):
|
| 85 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 86 |
+
root=Path(tmp);df=rows(root);train=df.iloc[:8].copy();val=df.iloc[8:].copy();out=root/"run"
|
| 87 |
+
args=parse_args(["--data-dir",str(root),"--output-dir",str(out),"--split-manifest",str(root/"split.json"),
|
| 88 |
+
"--metadata-mode","concat","--image-size","16","--batch-size","4","--freeze-epochs","1","--finetune-epochs","0","--patience","0"])
|
| 89 |
+
with patch("milk10k_effb2_dermoscopic_metadata.model.timm.create_model",return_value=FakeEncoder()):
|
| 90 |
+
train_split(df,train,val,["A","B"],{"A":0,"B":1},args,torch.device("cpu"),"timm",out)
|
| 91 |
+
checkpoint=torch.load(out/"last.pt",map_location="cpu",weights_only=False)
|
| 92 |
+
self.assertEqual(checkpoint["schema_version"],2);self.assertIn("scheduler_state",checkpoint);self.assertIn("scaler_state",checkpoint)
|
| 93 |
+
args.resume_checkpoint=out/"last.pt";args.freeze_epochs=2
|
| 94 |
+
with patch("milk10k_effb2_dermoscopic_metadata.model.timm.create_model",return_value=FakeEncoder()):
|
| 95 |
+
train_split(df,train,val,["A","B"],{"A":0,"B":1},args,torch.device("cpu"),"timm",out)
|
| 96 |
+
self.assertEqual(int(pd.read_csv(out/"history.csv").epoch.max()),2)
|
| 97 |
+
for name in ("best.pt","history.csv","metrics.json","data_summary.json","split_summary.md","run_report.md","prediction_summary.json","confusion_analysis.json"):
|
| 98 |
+
self.assertTrue((out/name).exists(),name)
|
| 99 |
+
|
| 100 |
+
def test_inference_old_checkpoint_tta_calibration_and_debug_columns(self):
|
| 101 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 102 |
+
root=Path(tmp);inputs=root/"input";lesion=inputs/"L1";lesion.mkdir(parents=True)
|
| 103 |
+
Image.fromarray(np.full((20,20,3),120,dtype=np.uint8)).save(lesion/"I1.jpg")
|
| 104 |
+
metadata_csv=root/"metadata.csv";pd.DataFrame([{"lesion_id":"L1","isic_id":"I1","image_type":"dermoscopic",
|
| 105 |
+
"age_approx":50,"sex":"x","skin_tone_class":2,"site":"arm","MONET_hair":.1}]).to_csv(metadata_csv,index=False)
|
| 106 |
+
spec={"sex_values":["unknown","x"],"site_values":["arm","unknown"],"monet_columns":["MONET_hair"]}
|
| 107 |
+
with patch("milk10k_effb2_dermoscopic_metadata.model.timm.create_model",return_value=FakeEncoder()):
|
| 108 |
+
model=DermoscopicMetadataClassifier(2,7,"concat",imagenet_pretrained=False,branch_dim=8,metadata_dim=4,classifier_hidden_dim=6)
|
| 109 |
+
checkpoint=root/"old.pt";torch.save({"model_state":model.state_dict(),"class_names":["A","B"],"metadata_spec":spec,
|
| 110 |
+
"args":{"metadata_mode":"concat","backbone":"efficientnet_b2","backbone_backend":"timm","branch_dim":8,"metadata_dim":4,"classifier_hidden_dim":6,"dropout":.3,"image_size":16}},checkpoint)
|
| 111 |
+
calibration=root/"bias.json";calibration.write_text(json.dumps({"class_names":["A","B"],"class_bias":[0,0]}))
|
| 112 |
+
output=root/"pred.csv";args=parse_inference_args(["--checkpoint",str(checkpoint),"--input-dir",str(inputs),"--metadata-csv",str(metadata_csv),
|
| 113 |
+
"--output",str(output),"--tta-flips","--calibration-file",str(calibration),"--include-debug-columns"])
|
| 114 |
+
with patch("milk10k_effb2_dermoscopic_metadata.model.timm.create_model",return_value=FakeEncoder()):run_inference(args)
|
| 115 |
+
columns=pd.read_csv(output).columns.tolist();self.assertIn("predicted_label",columns);self.assertIn("confidence",columns);self.assertIn("isic_id",columns)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__=="__main__":unittest.main()
|