Initialize SPC cars run cars_disef_spc_seed1_20261025
Browse files
finetune_runs/cars_disef_spc/cars_disef_spc_seed1_20261025/source/cars_spc_runner.py
CHANGED
|
@@ -234,23 +234,38 @@ def smoke(root,cfg):
|
|
| 234 |
print(json.dumps(result),flush=True)
|
| 235 |
|
| 236 |
def evaluate_best(root,cfg):
|
|
|
|
|
|
|
| 237 |
x=torch.load(root/'checkpoints/best.pt',map_location='cpu',weights_only=False)
|
| 238 |
assert x['config_fingerprint']==signature(cfg)
|
| 239 |
_,_,_,test_loader=make_loaders(cfg)
|
|
|
|
| 240 |
model,_,_,_=model_setup(cfg);set_peft_model_state_dict(model.model,x['adapter_state_dict']);model.model.eval()
|
|
|
|
|
|
|
| 241 |
with torch.no_grad():
|
| 242 |
-
mu,_=get_mu_and_kappa(model,cfg['dataset']);mu=mu.to('cuda')
|
|
|
|
| 243 |
for images,labels in test_loader:
|
| 244 |
-
emb=SPC['get_image_embedding'](model,images)
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
diag=np.diag(cm).astype(np.float64);row=cm.sum(axis=1);col=cm.sum(axis=0)
|
| 248 |
precision=np.divide(diag,col,out=np.zeros_like(diag),where=col>0)
|
| 249 |
recall=np.divide(diag,row,out=np.zeros_like(diag),where=row>0)
|
| 250 |
f1=np.divide(2*precision*recall,precision+recall,out=np.zeros_like(diag),where=(precision+recall)>0)
|
| 251 |
names=SUBSET_NAMES[cfg['dataset']]
|
| 252 |
confusions=sorted([{'true_class':names[i],'predicted_class':names[j],'count':int(cm[i,j])} for i in range(cfg['class_count']) for j in range(cfg['class_count']) if i!=j and cm[i,j]>0],key=lambda v:v['count'],reverse=True)[:20]
|
| 253 |
-
result={'run_id':cfg['run_id'],'test_accuracy':correct/total,'macro_f1':float(f1.mean()),'test_correct':correct,'test_total':total,'best_epoch':x['epoch'],'best_val_accuracy':x['best_val_accuracy'],'confusion_matrix':cm.tolist(),'per_class_accuracy':{names[i]:float(diag[i]/row[i]) for i in range(cfg['class_count'])},'most_confused_classes':confusions,'evaluated_at':utcnow()}
|
|
|
|
| 254 |
atomic_json(root/'results/final_test.json',result);atomic_json(root/'results/summary.json',{k:v for k,v in result.items() if k not in ['confusion_matrix','per_class_accuracy']})
|
| 255 |
import matplotlib;matplotlib.use('Agg');import matplotlib.pyplot as plt
|
| 256 |
fig,ax=plt.subplots(figsize=(10,9));ax.imshow(cm,cmap='Blues');ax.set(xlabel='Predicted class',ylabel='True class',title=f"{cfg['dataset']} test confusion matrix");fig.tight_layout();fig.savefig(root/'figures/test_confusion_matrix.png',dpi=140);plt.close(fig)
|
|
|
|
| 234 |
print(json.dumps(result),flush=True)
|
| 235 |
|
| 236 |
def evaluate_best(root,cfg):
|
| 237 |
+
# Evaluation extension only: preserves the original prediction rule and best-checkpoint selection.
|
| 238 |
+
t0=time.monotonic()
|
| 239 |
x=torch.load(root/'checkpoints/best.pt',map_location='cpu',weights_only=False)
|
| 240 |
assert x['config_fingerprint']==signature(cfg)
|
| 241 |
_,_,_,test_loader=make_loaders(cfg)
|
| 242 |
+
test_names=load_split(cfg,'test')
|
| 243 |
model,_,_,_=model_setup(cfg);set_peft_model_state_dict(model.model,x['adapter_state_dict']);model.model.eval()
|
| 244 |
+
cm=np.zeros((cfg['class_count'],cfg['class_count']),dtype=np.int64)
|
| 245 |
+
predictions=[];top5_correct=0
|
| 246 |
with torch.no_grad():
|
| 247 |
+
mu,_=get_mu_and_kappa(model,cfg['dataset']);mu=mu.to('cuda')
|
| 248 |
+
offset=0
|
| 249 |
for images,labels in test_loader:
|
| 250 |
+
emb=SPC['get_image_embedding'](model,images)
|
| 251 |
+
scores=cfg['logit_scale']*(emb@mu.T)
|
| 252 |
+
top5=scores.topk(min(5,cfg['class_count']),dim=1).indices.cpu().numpy()
|
| 253 |
+
ys=labels.numpy();pred=top5[:,0]
|
| 254 |
+
for j,(y,p) in enumerate(zip(ys,pred)):
|
| 255 |
+
y=int(y);p=int(p);cm[y,p]+=1
|
| 256 |
+
ranked=[int(v) for v in top5[j].tolist()]
|
| 257 |
+
top5_correct+=int(y in ranked)
|
| 258 |
+
predictions.append({'image_id':test_names[offset+j],'true_class_id':y,'predicted_class_id':p,'top5_class_ids':ranked})
|
| 259 |
+
offset+=len(ys)
|
| 260 |
+
total=int(cm.sum());correct=int(np.trace(cm));assert total==cfg['test_size'] and len(predictions)==total
|
| 261 |
diag=np.diag(cm).astype(np.float64);row=cm.sum(axis=1);col=cm.sum(axis=0)
|
| 262 |
precision=np.divide(diag,col,out=np.zeros_like(diag),where=col>0)
|
| 263 |
recall=np.divide(diag,row,out=np.zeros_like(diag),where=row>0)
|
| 264 |
f1=np.divide(2*precision*recall,precision+recall,out=np.zeros_like(diag),where=(precision+recall)>0)
|
| 265 |
names=SUBSET_NAMES[cfg['dataset']]
|
| 266 |
confusions=sorted([{'true_class':names[i],'predicted_class':names[j],'count':int(cm[i,j])} for i in range(cfg['class_count']) for j in range(cfg['class_count']) if i!=j and cm[i,j]>0],key=lambda v:v['count'],reverse=True)[:20]
|
| 267 |
+
result={'run_id':cfg['run_id'],'test_accuracy':correct/total,'top5_accuracy':top5_correct/total,'macro_f1':float(f1.mean()),'test_correct':correct,'test_total':total,'best_epoch':x['epoch'],'best_val_accuracy':x['best_val_accuracy'],'confusion_matrix':cm.tolist(),'per_class_accuracy':{names[i]:float(diag[i]/row[i]) for i in range(cfg['class_count'])},'most_confused_classes':confusions,'evaluation_seconds':time.monotonic()-t0,'evaluated_at':utcnow()}
|
| 268 |
+
atomic_json(root/'results/final_test_predictions.json',predictions)
|
| 269 |
atomic_json(root/'results/final_test.json',result);atomic_json(root/'results/summary.json',{k:v for k,v in result.items() if k not in ['confusion_matrix','per_class_accuracy']})
|
| 270 |
import matplotlib;matplotlib.use('Agg');import matplotlib.pyplot as plt
|
| 271 |
fig,ax=plt.subplots(figsize=(10,9));ax.imshow(cm,cmap='Blues');ax.set(xlabel='Predicted class',ylabel='True class',title=f"{cfg['dataset']} test confusion matrix");fig.tight_layout();fig.savefig(root/'figures/test_confusion_matrix.png',dpi=140);plt.close(fig)
|