-
Notifications
You must be signed in to change notification settings - Fork 2
/
scatter.py
149 lines (124 loc) · 4.3 KB
/
scatter.py
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import pandas as pd
import matplotlib.pyplot as plt
import os
import numpy as np
import seaborn as sns
import argparse
from matplotlib.lines import Line2D
from matplotlib.colors import ListedColormap, Normalize
parser = argparse.ArgumentParser('Generate a scatter plot of two variables')
parser.add_argument('file', type=str,
metavar='DF',
help='Location where pkl file saved')
parser.add_argument('--fig-size', type=float, default=6,
help='Figure size (inches)')
parser.add_argument('--font-size',type=float, default=20)
parser.add_argument('--dpi', type=int, default=80)
parser.add_argument('--xvar', type=str, default='model_entropy')
parser.add_argument('--yvar', type=str, default='loss')
parser.add_argument('--no-show', action='store_false', dest='show')
parser.add_argument('--show', action='store_true', dest='show')
parser.add_argument('--save', action='store_true', dest='save')
parser.add_argument('--no-save', action='store_false',dest='save')
parser.add_argument('--leg', action='store_true', dest='leg')
parser.add_argument('--no-leg', action='store_false',dest='leg')
parser.add_argument('--log', action='store_true', dest='log')
parser.add_argument('--no-log', action='store_false',dest='log')
parser.add_argument('--name', type=str, default='scatter.pdf', help='file name for saving')
parser.add_argument('--xlim', type=float, default=None, nargs='*')
parser.add_argument('--ylim', type=float, default=None, nargs='*')
parser.set_defaults(show=True)
parser.set_defaults(log=True)
parser.set_defaults(save=False)
parser.set_defaults(leg=False)
args = parser.parse_args()
from common import labdict
sns.set_palette(palette='colorblind')
colors = sns.color_palette()
cmap = ListedColormap(colors)
fsz = args.font_size
figsz = (args.fig_size, args.fig_size)
plt.rc('font', size=fsz)
plt.rc('axes', titlesize=fsz)
plt.rc('axes', labelsize=fsz)
plt.rc('xtick', labelsize=fsz)
plt.rc('ytick', labelsize=fsz)
plt.rc('legend', fontsize=.66*fsz)
plt.rc('figure', titlesize=fsz)
dpi = args.dpi
show=args.show
df = pd.read_pickle(args.file)
Nsamples = len(df)
plt.close('all')
fig, ax = plt.subplots(1, figsize=figsz)
norm = Normalize(vmin=0,vmax=1.)
C = df['type'].map({'top1':0.2, 'top5':0.0, 'mis-classified':0.39})
X = df[args.xvar]
Y = df[args.yvar]
if args.xlim is None:
xmin = max(0.9*X.min(), 1e-6)
xmax = 1.5*X.max()
scxlim = (xmin, xmax)
else:
scxlim = tuple(args.xlim)
if args.ylim is None:
ymin = max(0.9*Y.min(), 1e-6)
ymax = 1.5*Y.max()
scylim = (ymin, ymax)
else:
scylim = tuple(args.ylim)
sc = ax.scatter(X,Y, c=C, s=1, cmap=cmap, norm=norm)
# ----------
# Set up GUI
# ----------
annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
def update_annot(ind):
pos = sc.get_offsets()[ind["ind"][0]]
annot.xy = pos
text = "{}".format(" ".join(list(map(str,ind["ind"]))))
annot.set_text(text)
annot.get_bbox_patch().set_facecolor(cmap(norm(C[ind["ind"][0]])))
annot.get_bbox_patch().set_alpha(0.4)
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
cont, ind = sc.contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("motion_notify_event", hover)
# ------------
# Minor tweaks
# ------------
ax.grid()
ax.set_axisbelow(True)
if args.log:
ax.set_xscale('log',nonposx='clip')
ax.set_yscale('log',nonposy='clip')
ax.set_xlim(scxlim)
ax.set_ylim(scylim)
extra = []
extra.append(ax.set_xlabel(labdict[args.xvar]))
extra.append(ax.set_ylabel(labdict[args.yvar]))
fig.tight_layout()
if args.leg:
leg_el = []
labels = ['top5', 'mis-classified','top1']
for c,lab in zip(colors[:3],labels):
leg_el.append(Line2D([0],[0],markerfacecolor=c,markersize=10,marker='o', label=lab, color='w'))
le =ax.legend(handles=leg_el,loc='left', bbox_to_anchor=(1,0.75))
extra.append(le)
if show:
plt.show()
if args.save:
pth = os.path.split(args.file)[0]
fig.savefig(os.path.join(pth,args.name),
format='pdf',bbox_inches='tight',dpi=dpi)