Datasets:
File size: 9,687 Bytes
998413b 4a15f9d 998413b 4a15f9d 998413b 4a15f9d 998413b 4a15f9d 998413b dfb6aea 998413b 7cc32bc 74a80d2 998413b 8e6c4da 998413b 4a15f9d 998413b 4a15f9d 998413b 4a15f9d 998413b 4a15f9d 998413b 4a15f9d 998413b 4a15f9d 998413b 4a15f9d 998413b 74a80d2 998413b 4a15f9d | 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | #!/usr/bin/env python3
"""Reproducible multilabel BDFD9 v3 training/evaluation pipeline for GPU notebooks."""
from pathlib import Path
import argparse,csv,json,random,time
import numpy as np
from PIL import Image,ImageOps
import torch
from torch import nn
from torch.utils.data import Dataset,DataLoader
from torchvision import models,transforms
ROOT=Path(__file__).resolve().parents[1]
CLASSES=[x.strip().split(" ",1)[1] if " " in x.strip() else x.strip() for x in (ROOT/"classes.txt").read_text().splitlines() if x.strip()]
def seed_all(seed):
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed);torch.cuda.manual_seed_all(seed);torch.backends.cudnn.deterministic=True;torch.backends.cudnn.benchmark=False
class FabricDataset(Dataset):
def __init__(self,split,size,augment,exclude_filenames=None):
self.rows=[]
exclude_filenames=set(exclude_filenames or [])
meta=list(csv.DictReader(open(ROOT/"dataset_metadata.csv",newline="",encoding="utf-8-sig")))
for row in meta:
if row["split"]!=split or row["filename"] in exclude_filenames:continue
p=ROOT/split/"images"/row["filename"];lab=ROOT/split/"labels"/(p.stem+".txt")
y=np.zeros(len(CLASSES),dtype=np.float32)
if lab.exists():
for line in lab.read_text().splitlines():
if line.strip():y[int(line.split()[0])]=1.
self.rows.append((p,y))
ops=[transforms.Lambda(lambda im: ImageOps.pad(im,(size,size),method=Image.Resampling.LANCZOS,color=(0,0,0)))]
if augment:ops += [transforms.RandomHorizontalFlip(.5),transforms.RandomVerticalFlip(.5),transforms.ColorJitter(brightness=.12,contrast=.12,saturation=.06,hue=.015)]
ops += [transforms.ToTensor(),transforms.Normalize([.485,.456,.406],[.229,.224,.225])]
self.transform=transforms.Compose(ops)
def __len__(self):return len(self.rows)
def __getitem__(self,i):
p,y=self.rows[i]
with Image.open(p) as im:im=ImageOps.exif_transpose(im).convert("RGB")
return self.transform(im),torch.tensor(y,dtype=torch.float32),p.name
def make_model(name,k,pretrained=True):
if name=="small_cnn":
class CNN(nn.Module):
def __init__(self):
super().__init__();self.features=nn.Sequential(nn.Conv2d(3,32,3,padding=1),nn.BatchNorm2d(32),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(32,64,3,padding=1),nn.BatchNorm2d(64),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(64,128,3,padding=1),nn.BatchNorm2d(128),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(128,192,3,padding=1),nn.BatchNorm2d(192),nn.ReLU(),nn.AdaptiveAvgPool2d(1));self.classifier=nn.Linear(192,k)
def forward(self,x):return self.classifier(self.features(x).flatten(1))
return CNN()
if name=="resnet18":
m=models.resnet18(weights=models.ResNet18_Weights.DEFAULT if pretrained else None);m.fc=nn.Linear(m.fc.in_features,k);return m
if name=="mobilenet_v3_small":
m=models.mobilenet_v3_small(weights=models.MobileNet_V3_Small_Weights.DEFAULT if pretrained else None);m.classifier[-1]=nn.Linear(m.classifier[-1].in_features,k);return m
if name=="efficientnet_b0":
m=models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT if pretrained else None);m.classifier[-1]=nn.Linear(m.classifier[-1].in_features,k);return m
if name=="shufflenet_v2":
m=models.shufflenet_v2_x1_0(weights=models.ShuffleNet_V2_X1_0_Weights.DEFAULT if pretrained else None);m.fc=nn.Linear(m.fc.in_features,k);return m
raise ValueError("unsupported model: "+name)
def scores(y,p,t):
y=np.asarray(y).astype(bool);pred=np.asarray(p)>=np.asarray(t);tp=(pred&y).sum(0);fp=(pred&~y).sum(0);fn=(~pred&y).sum(0)
pr=tp/(tp+fp+1e-9);re=tp/(tp+fn+1e-9);f=2*pr*re/(pr+re+1e-9)
support=y.sum(0);return {"macro_f1":float(f.mean()),"macro_f1_supported_classes":float(f[support>0].mean()) if np.any(support>0) else 0.0,"n_supported_classes":int((support>0).sum()),"micro_f1":float(2*tp.sum()/(2*tp.sum()+fp.sum()+fn.sum()+1e-9)),"hamming_loss":float((pred!=y).mean()),"subset_accuracy":float((pred==y).all(1).mean()),"per_class":{CLASSES[i]:{"precision":float(pr[i]),"recall":float(re[i]),"f1":float(f[i]),"support":int(y[:,i].sum())} for i in range(len(CLASSES))}}
def scores_by_fabric_type(y,p,t,names):
meta={r["filename"]:r.get("fabric_type","") for r in csv.DictReader(open(ROOT/"dataset_metadata.csv",newline="",encoding="utf-8-sig"))}
out={}
for fabric in ("knit","woven"):
idx=[i for i,n in enumerate(names) if meta.get(n)==fabric]
if idx:out[fabric]={"n":len(idx),**scores(y[idx],p[idx],t)}
return out
def tune_thresholds(y,p):
y=np.asarray(y,dtype=bool)
t=[]
for c in range(len(CLASSES)):
bestf=-1;bestt=.5
for x in np.linspace(.1,.9,17):
z=p[:,c]>=x;tp=(z&y[:,c]).sum();fp=(z&~y[:,c]).sum();fn=(~z&y[:,c]).sum();f=2*tp/(2*tp+fp+fn+1e-9)
if f>bestf:bestf,bestt=float(f),float(x)
t.append(bestt)
return np.asarray(t,dtype=np.float32)
def collect(model,loader,device):
model.eval();ys=[];ps=[];names=[]
with torch.no_grad():
for x,y,n in loader:
x=x.to(device,non_blocking=True);ps.append(torch.sigmoid(model(x)).cpu().numpy());ys.append(y.numpy());names+=list(n)
return np.concatenate(ys),np.concatenate(ps),names
def main():
ap=argparse.ArgumentParser();ap.add_argument("--model",choices=["small_cnn","resnet18","mobilenet_v3_small","efficientnet_b0","shufflenet_v2"],default="mobilenet_v3_small");ap.add_argument("--epochs",type=int,default=30);ap.add_argument("--batch-size",type=int,default=32);ap.add_argument("--size",type=int,default=224);ap.add_argument("--seed",type=int,default=2026);ap.add_argument("--workers",type=int,default=4);ap.add_argument("--lr",type=float,default=3e-4);ap.add_argument("--pretrained",action=argparse.BooleanOptionalAction,default=True);ap.add_argument("--run-name",default="");ap.add_argument("--exclude-csv",default="")
args=ap.parse_args();seed_all(args.seed);excluded={"train":set(),"valid":set()}
if args.exclude_csv:
with open(args.exclude_csv,newline="") as f:
for r in csv.DictReader(f):
if r.get("split") in excluded: excluded[r["split"]].add(r["filename"])
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
run=args.run_name or f"{args.model}_seed{args.seed}_{time.strftime('%Y%m%d_%H%M%S')}";out=ROOT/"experiments"/run;out.mkdir(parents=True,exist_ok=True)
tr=FabricDataset("train",args.size,True,excluded["train"]);va=FabricDataset("valid",args.size,False,excluded["valid"]);g=torch.Generator().manual_seed(args.seed)
dlargs={"batch_size":args.batch_size,"num_workers":args.workers,"pin_memory":device.type=="cuda","persistent_workers":args.workers>0}
tl=DataLoader(tr,shuffle=True,generator=g,**dlargs);vl=DataLoader(va,shuffle=False,**dlargs)
yt=np.stack([r[1] for r in tr.rows]);pos=yt.sum(0);neg=len(yt)-pos;pw=torch.tensor(np.clip(neg/np.maximum(pos,1),1,15),dtype=torch.float32,device=device)
effective_pretrained=bool(args.pretrained and args.model!="small_cnn");run_args=vars(args).copy();run_args["pretrained_effective"]=effective_pretrained
model=make_model(args.model,len(CLASSES),effective_pretrained).to(device);lossfn=nn.BCEWithLogitsLoss(pos_weight=pw);opt=torch.optim.AdamW(model.parameters(),lr=args.lr,weight_decay=1e-4);sched=torch.optim.lr_scheduler.CosineAnnealingLR(opt,T_max=args.epochs)
amp=device.type=="cuda";scaler=torch.amp.GradScaler("cuda",enabled=amp);best=-1;history=[];start=time.time()
for ep in range(args.epochs):
model.train();total=0;n=0
for x,y,_ in tl:
x=x.to(device,non_blocking=True);y=y.to(device,non_blocking=True);opt.zero_grad(set_to_none=True)
with torch.autocast(device_type=device.type,enabled=amp):logits=model(x);loss=lossfn(logits,y)
scaler.scale(loss).backward();scaler.step(opt);scaler.update();total+=loss.item()*len(y);n+=len(y)
sched.step();vy,vp,_=collect(model,vl,device);m=scores(vy,vp,np.full(len(CLASSES),.5));row={"epoch":ep+1,"train_loss":total/n,"val_macro_f1_at_05":m["macro_f1"],"val_micro_f1_at_05":m["micro_f1"]};history.append(row);print(json.dumps(row),flush=True)
if m["macro_f1"]>best:best=m["macro_f1"];torch.save({"state_dict":model.state_dict(),"epoch":ep+1,"best_val_macro_f1_05":best,"args":run_args,"classes":CLASSES},out/"best_checkpoint.pt")
ck=torch.load(out/"best_checkpoint.pt",map_location=device,weights_only=False);model.load_state_dict(ck["state_dict"]);vy,vp,vnames=collect(model,vl,device);thresholds=tune_thresholds(vy,vp);valmetrics=scores(vy,vp,thresholds)
# Test data is deliberately not instantiated or accessed during model training.
with open(out/"history.csv","w",newline="") as f:w=csv.DictWriter(f,fieldnames=history[0].keys());w.writeheader();w.writerows(history)
np.savez(out/"validation_predictions.npz",val_y=vy,val_p=vp,thresholds=thresholds)
for split,y,p,names in [("validation",vy,vp,vnames)]:
with open(out/f"{split}_predictions.csv","w",newline="") as f:
w=csv.writer(f);w.writerow(["filename"]+[f"true_{c}" for c in CLASSES]+[f"prob_{c}" for c in CLASSES]);w.writerows([[name]+list(map(int,y[i]))+list(map(float,p[i])) for i,name in enumerate(names)])
result={"model":args.model,"seed":args.seed,"device":str(device),"pretrained":effective_pretrained,"best_checkpoint_epoch":ck["epoch"],"best_validation_macro_f1_at_05":ck["best_val_macro_f1_05"],"validation_metrics_threshold_tuned":valmetrics,"validation_metrics_by_fabric_type":scores_by_fabric_type(vy,vp,thresholds,vnames),"thresholds_from_validation":{c:float(thresholds[i]) for i,c in enumerate(CLASSES)},"test_evaluation":"NOT RUN — reserved for one final selected model only","minutes":round((time.time()-start)/60,2),"excluded_from_train":len(excluded["train"]),"excluded_from_validation":len(excluded["valid"]),"classes":CLASSES,"args":run_args}
(out/"results.json").write_text(json.dumps(result,indent=2));print("RESULTS_JSON",json.dumps(result),flush=True)
if __name__=="__main__":main()
|