i-badas / scripts /conf_matrix /plot_diagonal_confusions_compact_legends.py
JARAYAM
Modified confusion matrix plot
4ad3533
Raw History Blame Contribute Delete
10.5 kB
#!/usr/bin/env python3
"""Rebuild all 18 configurations from the supplied per_image CSV, using RGB GT.
Generate four PNG figures: two comparisons with two triangle_legend placements.
Requires numpy, pandas, matplotlib. No predictions or thresholds are modified.
Run: python plot_diagonal_confusions_palette_v3.py
"""
from pathlib import Path
import argparse,json,re
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon,Rectangle
from matplotlib.colors import LinearSegmentedColormap,Normalize
from matplotlib.cm import ScalarMappable
NAMES=['Empty\nclean','Empty\ndirty','Non-empty']
MAP={'good':0,'nuisance':1,'residual':2}
KEY=['scene_id','image_number']
BASE_FONT_SIZE=14
VIRIDIS_POINT=0.6
LEGEND_Y_OFFSET = -0.06
ROTATION = 20
def rebuild(path,out):
d=pd.read_csv(path,dtype={'scene':str,'image_id':str})
required=['family','model','variant','scene','image_id','ground_truth_class','predicted_class']
if not set(required)<=set(d): raise ValueError('Missing columns')
d['scene_id']=d.scene.str.extract(r'^(\d+)')[0].astype(int)
d['image_number']=d.image_id.map(lambda s:int(Path(str(s)).stem))
d['variant']=d.variant.replace({'faithful':'unmasked'})
if not d.variant.isin(['masked','unmasked']).all(): raise ValueError('Unknown variant')
d['original_gt']=d.ground_truth_class.map(MAP); d['prediction']=d.predicted_class.map(MAP)
if d[['original_gt','prediction']].isna().any().any(): raise ValueError('Unknown class label')
if d.duplicated(['family','model','variant']+KEY).any(): raise ValueError('Duplicate per_configuration image IDs')
rgb=d[d.family.str.lower().eq('rgb')]
if rgb.empty: raise ValueError('No RGB ground truth')
if rgb.groupby(KEY).original_gt.nunique().gt(1).any(): raise ValueError('RGB ground truth conflicts across configurations')
reference=rgb[KEY+['original_gt']].drop_duplicates(KEY).rename(columns={'original_gt':'rgb_gt'})
reference_set=set(map(tuple,reference[KEY].values))
for config,g in d.groupby(['family','model','variant']):
if set(map(tuple,g[KEY].values))!=reference_set: raise ValueError('Image cohort differs for '+str(config)+'; no silent dropping allowed')
d=d.merge(reference,on=KEY,validate='many_to_one')
assert len(d)==len(pd.read_csv(path,usecols=['model']))
d['gt_changed']=d.original_gt.ne(d.rgb_gt)
assert np.array_equal(d.prediction.values,d.predicted_class.map(MAP).values)
matrices={}; rows=[]; audit=[]
expected=np.bincount(reference.rgb_gt,minlength=3)
for (family,model,var),g in d.groupby(['family','model','variant']):
a=np.zeros((3,3),dtype=np.int64); np.add.at(a,(g.rgb_gt.to_numpy(dtype=int),g.prediction.to_numpy(dtype=int)),1)
assert np.array_equal(a.sum(axis=1),expected)
matrices[(model,var)]=a
audit.append(dict(family=family,model=model,variant=var,ground_truth_reassigned=int(g.gt_changed.sum()),predictions_changed=0))
for r in range(3):
for c in range(3): rows.append(dict(family=family,model=model,variant=var,gt_class=list(MAP)[r],predicted_class=list(MAP)[c],count=int(a[r,c]),row_percent=float(100*a[r,c]/expected[r]) if expected[r] else None))
pd.DataFrame(rows).to_csv(out/'rebuilt_all_18_confusion_counts.csv',index=False)
pd.DataFrame(audit).to_csv(out/'ground_truth_correction_audit.csv',index=False)
d.to_csv(out/'per_image_predictions_rgb_ground_truth.csv',index=False)
report={'configurations':len(matrices),'rgb_class_support':dict(zip(list(MAP),map(int,expected))),'ground_truth_reassignments_by_family':d.groupby('family').gt_changed.sum().astype(int).to_dict(),'prediction_changes':0,'identical_image_cohorts':True}
(out/'validation_report.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2)); print(pd.DataFrame(audit).to_string(index=False))
return matrices
def arrays(a,margins):
n=4 if margins else 3; count=np.full((n,n),np.nan); count[:3,:3]=a; support=a.sum(axis=1)
pct=np.full((n,n),np.nan)
for r in range(3):
if support[r]: pct[r,:3]=a[r]/support[r]
if margins:
count[:3,3]=support-np.diag(a); count[3,:3]=a.sum(axis=0)-np.diag(a)
for r in range(3):
if support[r]: pct[r,3]=count[r,3]/support[r]; pct[3,r]=count[3,r]/support[r]
return count,pct
def panel(ax,a,b,title,args,cmap,scale):
ca,pa=arrays(a,not args.no_margins); cb,pb=arrays(b,not args.no_margins); n=len(ca)
for r in range(n):
for c in range(n):
if r==3 and c==3:
ax.add_patch(Rectangle((c,r),1,1,facecolor='white',edgecolor='#aaaaaa',lw=.6)); continue
for count,pct,vertices,x,y in [(ca,pa,[(c,r),(c+1,r),(c+1,r+1)],c+.74,r+.25),(cb,pb,[(c,r),(c,r+1),(c+1,r+1)],c+.26,r+.75)]:
p=pct[r,c]; ax.add_patch(Polygon(vertices,facecolor=cmap(scale(p)) if np.isfinite(p) else '#eeeeee',edgecolor='none'))
text=f'{p:.2f}' if np.isfinite(p) else 'N/A'
ax.text(x,y,text,ha='center',va='center',fontsize=BASE_FONT_SIZE,color='black',linespacing=1.2)
ax.plot([c,c+1],[r,r+1],color='#777777',lw=.65); ax.add_patch(Rectangle((c,r),1,1,fill=False,edgecolor='#aaaaaa',lw=.65))
if n==4:
ax.plot([3,3],[0,4],color='#555555',lw=1.2); ax.plot([0,4],[3,3],color='#555555',lw=1.2)
ax.set(xlim=(0,n),ylim=(n,0),aspect='equal')
ax.set_xticks(np.arange(n)+.5,NAMES+(['FN'] if n==4 else [])); ax.set_yticks(np.arange(n)+.5,NAMES+(['FP'] if n==4 else []))
ax.set_xlabel('Predicted class',labelpad=10,fontweight='bold')
ax.set_ylabel('True class',labelpad=10,fontweight='bold')
ax.set_title(title,pad=15,fontsize=BASE_FONT_SIZE+3,fontweight='bold')
ax.tick_params(length=0,pad=7,labelsize=BASE_FONT_SIZE-1)
for sp in ax.spines.values(): sp.set_visible(False)
ax.grid(False)
def triangle_key(fig,center,width,labels,cmap,y=.035,height=.115):
key=fig.add_axes([center-width/2,y,width,height])
key.set_xlim(0,6);key.set_ylim(1,0);key.axis('off')
x,y,w,h=2.60,.10,.80,.80
key.add_patch(Polygon([(x,y),(x+w,y),(x+w,y+h)],facecolor='white',edgecolor='none'))
key.add_patch(Polygon([(x,y),(x,y+h),(x+w,y+h)],facecolor='black',edgecolor='none'))
key.add_patch(Rectangle((x,y),w,h,fill=False,edgecolor='black',lw=.8))
key.plot([x,x+w],[y,y+h],color='black',lw=.8)
key.annotate(labels[0],xy=(x+w*.74,y+h*.24),xytext=(3.72,.22),ha='left',va='center',fontsize=BASE_FONT_SIZE-2,arrowprops={'arrowstyle':'-','color':'#555555','lw':.65})
key.annotate(labels[1],xy=(x+w*.26,y+h*.76),xytext=(2.28,.78),ha='right',va='center',fontsize=BASE_FONT_SIZE-2,arrowprops={'arrowstyle':'-','color':'#555555','lw':.65})
return key
def figure(panels,labels,path,args,cmap,scale,legend_location):
fig=plt.figure(figsize=(13,6))
grid=fig.add_gridspec(1,4,width_ratios=[1,0.25,1,.045],left=.075,right=.93,bottom=.16,top=.89,wspace=.10)
axes=[]
for i,(a,b,title) in enumerate(panels):
ax=fig.add_subplot(grid[0,i*2]);panel(ax,a,b,title,args,cmap,scale);axes.append(ax)
names=['empty_clean','empty_dirty','non_empty']
xt=ax.get_xticks();yt=ax.get_yticks()
if len(xt)>=3:
old=[t.get_text() for t in ax.get_xticklabels()]
ax.set_xticks(xt,names+old[3:], rotation=ROTATION, ha='right')
if len(yt)>=3:
old=[t.get_text() for t in ax.get_yticklabels()]
ax.set_yticks(yt,names+old[3:])
cax=fig.add_subplot(grid[0,3])
cb=fig.colorbar(ScalarMappable(norm=scale,cmap=cmap),cax=cax,ticks=np.linspace(0,1,6))
cb.set_label('Standardized Conditional Probability',labelpad=12,fontweight='bold')
cb.ax.set_yticklabels([f'{v:.1f}' for v in np.linspace(0,1,6)])
fig.canvas.draw()
renderer=fig.canvas.get_renderer()
boxes=[ax.get_tightbbox(renderer).transformed(fig.transFigure.inverted()) for ax in axes]
footer_top=min(box.y0 for box in boxes)
left=axes[0].get_position().x0;right=axes[1].get_position().x1
if legend_location=='under-scale':
pos=cax.get_position();center=(pos.x0+pos.x1)/2
key=triangle_key(fig,center,.25,[v.replace(': ',':\n') for v in labels],cmap,y=footer_top+LEGEND_Y_OFFSET,height=.065)
else:
center=(left+right)/2
key=triangle_key(fig,center,.46,labels,cmap,y=footer_top+LEGEND_Y_OFFSET,height=.065)
assert len(fig.axes)==4
assert abs((key.get_position().x0+key.get_position().x1)/2-center)<1e-10
path=path.with_name(path.name.replace('per_matrix','shared_neutral_legend').replace('under_scale','neutral_legend_under_scale'))
fig.savefig(path,dpi=args.dpi,bbox_inches='tight',pad_inches=.04,facecolor='white')
fig.savefig(path.with_suffix('.pdf'),bbox_inches='tight',pad_inches=.04,facecolor='white')
plt.close(fig)
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--input',type=Path,default=Path(__file__).resolve().parent/'per_image_three_class_predictions_best_validation.csv')
p.add_argument('--out',type=Path,default=None); p.add_argument('--rgb-model',default='AnomalyDINO'); p.add_argument('--multimodal-model',default='M3DM')
p.add_argument('--no-margins',action='store_true'); p.add_argument('--dpi',type=int,default=400)
args=p.parse_args(); out=args.out or args.input.parent/'diagonal_confusion_compact_legends_v6'; out.mkdir(parents=True,exist_ok=True)
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':BASE_FONT_SIZE,'text.color':'black','axes.labelcolor':'black','xtick.color':'black','ytick.color':'black','axes.facecolor':'white','figure.facecolor':'white'})
matrices=rebuild(args.input,out); rgb={v:matrices[(args.rgb_model,v)] for v in ['masked','unmasked']}; mm={v:matrices[(args.multimodal_model,v)] for v in ['masked','unmasked']}
scale=Normalize(0,1,clip=True)
viridis_color = plt.get_cmap('viridis')(VIRIDIS_POINT)
cmap = LinearSegmentedColormap.from_list('white_to_viridis', ['white', viridis_color])
# Create pastel viridis colormap
c_vals = plt.get_cmap('viridis')(np.linspace(0.1, 0.8, 256))
pastel_vals = c_vals * 0.4 + 0.6
pastel_vals[:, 3] = 1.0
cmap = LinearSegmentedColormap.from_list('pastel_viridis', pastel_vals)
for placement in ['per-matrix','under-scale']:
suffix=placement.replace('-','_')
figure([(rgb[v],mm[v],v.capitalize()) for v in ['masked','unmasked']],['RGB: '+args.rgb_model,'Multimodal: '+args.multimodal_model],out/f'01_masked_vs_unmasked_{suffix}.png',args,cmap,scale,placement)
figure([(rgb['masked'],rgb['unmasked'],'RGB | '+args.rgb_model),(mm['masked'],mm['unmasked'],'Multimodal | '+args.multimodal_model)],['Masked','Unmasked'],out/f'02_rgb_vs_multimodal_{suffix}.png',args,cmap,scale,placement)
print('Created four PNG and four PDF figures with one neutral legend each, plus unchanged audit tables in',out.resolve())
if __name__=='__main__': main()