Repository navigation
Expand file tree
/
Copy pathplot_regression_interpretation.py
More file actions
384 lines (323 loc) · 12.4 KB
/
Copy pathplot_regression_interpretation.py
File metadata and controls
384 lines (323 loc) · 12.4 KB
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""
Script to visualize the interpretation of regression outputs for C. elegans lifespan prediction.
This script loads a .pt file containing the inference dump from a regression model and creates an interactive
visualization with multiple subplots:
1. A timeline plot showing the true remaining lifespan and predicted remaining lifespan over time, with confidence intervals.
2. A trajectory plot showing the movement of the worm in 2D space, with segments colored by time.
3. An attention box plot showing the attention weights for different features at the current segment.
4. A trajectory plot highlighting the segments with the most attention at the current time step.
The .pt file should contain the following keys:
- 'T_actual': The actual number of segments observed (integer).
- 'true_objective': The true objective values of the model (numpy array).
- 'true_remaining': The true remaining lifespan values (numpy array). Should be T_actual in length and be T_actual - t.
- 'predictions': The predicted remaining lifespan values (numpy array). Should be T_actual in length.
- 'variances': The predicted variances of the remaining lifespan (numpy array). Should be T_actual in length.
- 's_weights_cpu': A list of numpy arrays containing the s_weights for each segment.
- 'v_weights_cpu': A list of numpy arrays containing the v_weights for each segment.
- 'data_tensor': A numpy array containing the trajectory data of shape (T_actual, 3, segment_length), where the 3 channels are [X, Y, Speed].
"""
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Button, Slider
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
parser = argparse.ArgumentParser(
description="Visualize interpretation of regression outputs."
)
parser.add_argument("path", type=str, help="Path to the inference dump (.pt) file")
args = parser.parse_args()
path = args.path
dump_dict = torch.load(path, weights_only=False)
def to_np(v):
if hasattr(v, "numpy"): # detect if it s a torch tensor
return v.detach().cpu().numpy()
return np.array(v)
T_actual = int(dump_dict["T_actual"])
true_objective = to_np(dump_dict["true_objective"])
true_remaining = to_np(dump_dict["true_remaining"])
predictions = to_np(dump_dict["predictions"])
has_variances = "variances" in dump_dict
if has_variances:
variances = to_np(dump_dict["variances"])
else:
variances = np.zeros_like(predictions, dtype=float)
print(
"Warning: 'variances' is missing from the inference dump; confidence intervals will not be shown."
)
s_weights_cpu = [to_np(x) for x in dump_dict["s_weights_cpu"]]
v_weights_cpu = [to_np(x) for x in dump_dict["v_weights_cpu"]]
data_tensor = to_np(dump_dict["data_tensor"])
# Global variables
steps = np.arange(1, T_actual + 1)
max_predicted_total = np.max(steps + predictions)
max_true_total = np.max(steps + true_remaining)
# Set up figure
fig, axs = plt.subplots(2, 2, figsize=(16, 10))
plt.subplots_adjust(bottom=0.15, hspace=0.3, wspace=0.2)
ax1, ax2 = axs[0]
ax3, ax4 = axs[1]
# ---------------------------------------------------------
# PLOT 1 (Timeline)
# ---------------------------------------------------------
plot1_xlim = max(1.5 * T_actual, max_predicted_total, max_true_total)
y_max_val = (
max(np.max(true_remaining), np.max(predictions + 1.96 * np.sqrt(variances))) * 1.1
)
(line_true,) = ax1.plot(
[],
[],
label="True Remaining",
linestyle="--",
marker="o",
markersize=4,
color="blue",
alpha=0.7,
)
(line_pred,) = ax1.plot(
[], [], label="Predicted Remaining", color="red", marker="x", markersize=4
)
fill_ci_dummy = (
ax1.fill_between([], [], [], color="red", alpha=0.2, label="95% CI")
if has_variances
else None
)
fill_ci = None
fill_ci_vspan = None
vline_pred = ax1.axvline(
x=-1, color="red", linestyle="-", alpha=0.6, label="Current Pred Total"
)
vline_true = ax1.axvline(
x=-1, color="blue", linestyle="-", alpha=0.6, label="Current True Total"
)
ax1.set_xlim(0, plot1_xlim)
ax1.set_ylim(0, y_max_val)
ax1.set_xlabel("Time (Segments observed)")
ax1.set_ylabel("Remaining segments")
ax1.legend()
ax1.grid(True, linestyle="--", alpha=0.6)
ax1.set_title("Lifespan Prediction Timeline")
# ---------------------------------------------------------
# PLOT 2 (Trajectories)
# ---------------------------------------------------------
# Constraints
valid_points_mask = ~(
(data_tensor[:T_actual, 0, :] == 0)
& (data_tensor[:T_actual, 1, :] == 0)
& (data_tensor[:T_actual, 2, :] == 0)
)
valid_x = data_tensor[:T_actual, 0, :][valid_points_mask]
valid_y = data_tensor[:T_actual, 1, :][valid_points_mask]
if len(valid_x) > 0:
g_min_x, g_max_x = np.min(valid_x), np.max(valid_x)
g_min_y, g_max_y = np.min(valid_y), np.max(valid_y)
dx = (g_max_x - g_min_x) * 0.05
dy = (g_max_y - g_min_y) * 0.05
plot2_xlim = (g_min_x - dx, g_max_x + dx)
plot2_ylim = (g_min_y - dy, g_max_y + dy)
else:
plot2_xlim = (-1, 1)
plot2_ylim = (-1, 1)
# Define the lines and their colors
cmap = plt.cm.plasma
# Add a colorbar for Plot 2 to indicate time flow
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=0, vmax=1))
sm.set_array([])
cbar = fig.colorbar(sm, ax=ax2, fraction=0.03, shrink=0.5, pad=0.04)
cbar.set_ticks([0, 1])
cbar.set_ticklabels(["t=0", f"t={T_actual}"])
traj_lines = []
for i in range(T_actual):
x_data = data_tensor[i, 0, :]
y_data = data_tensor[i, 1, :]
valid_mask = ~((x_data == 0) & (y_data == 0))
if np.any(valid_mask):
last_valid = np.max(np.nonzero(valid_mask)[0])
x_filtered = x_data[: last_valid + 1]
y_filtered = y_data[: last_valid + 1]
else:
x_filtered = x_data
y_filtered = y_data
(line,) = ax2.plot(x_filtered, y_filtered, linewidth=1.5, alpha=0.9, visible=False)
traj_lines.append(line)
ax2.set_title("C. elegans Trajectory")
ax2.set_xlabel("X coordinate")
ax2.set_ylabel("Y coordinate")
ax2.set_xlim(*plot2_xlim)
ax2.set_ylim(*plot2_ylim)
ax2.set_aspect("equal", adjustable="box")
ax2.grid(True, linestyle="--", alpha=0.3)
# ---------------------------------------------------------
# PLOT 3 (Attention Box)
# ---------------------------------------------------------
true_lifespan = max_true_total
colors = ["#ff9999", "#66b3ff", "#99ff99"]
variates = ["X", "Y", "Speed"]
num_vars = (
len(v_weights_cpu[0])
if len(np.shape(v_weights_cpu[0])) == 1
else np.shape(v_weights_cpu[0])[1]
)
bar_containers = []
for i in range(num_vars):
# Initialize with zeros for heights.
# We will update these heights directly on update() using `.patches`
bc = ax3.bar(
np.arange(1, T_actual + 1),
np.zeros(T_actual),
color=colors[i],
label=variates[i],
edgecolor="black",
linewidth=0.5,
alpha=0.8,
)
bar_containers.append(bc)
ax3.set_xlim(0, true_lifespan)
ax3.set_ylim(0, 0.8)
ax3.set_xlabel("Segment Index")
ax3.set_ylabel("Attention Weight")
ax3.set_title("Current Segment Attention by Feature")
ax3.legend()
ax3.grid(True, axis="y", linestyle="--", alpha=0.4)
# ---------------------------------------------------------
# PLOT 4 (Empty)
# ---------------------------------------------------------
# ax4.text(0.5, 0.5, "Empty for now", ha="center", va="center", fontsize=20, color="gray")
ax4.axis("off")
# Slider and Play Button
ax_slider = plt.axes([0.15, 0.05, 0.65, 0.03], facecolor="lightgoldenrodyellow")
slider = Slider(ax_slider, "Segment (t)", 1, T_actual, valinit=T_actual, valstep=1)
# Add vertical traits for each segment
for i in np.arange(1, T_actual + 1):
ax_slider.axvline(i, color="black", linewidth=0.8, alpha=0.4, zorder=1)
ax_slider.set_xticks([]) # Ensure default x-ticks are hidden
# Add labels for lifetime info below the slider
ax_lifetime = plt.axes([0.15, 0.015, 0.65, 0.03])
ax_lifetime.axis("off")
txt_elapsed = ax_lifetime.text(
0.0, 0.5, "", transform=ax_lifetime.transAxes, ha="left", va="center", fontsize=10
)
txt_remaining = ax_lifetime.text(
1.0, 0.5, "", transform=ax_lifetime.transAxes, ha="right", va="center", fontsize=10
)
ax_play = plt.axes([0.85, 0.05, 0.08, 0.03])
btn_play = Button(ax_play, "Play")
anim_running = False
anim = None
def animate(frame):
current_val = int(slider.val)
if current_val < T_actual:
slider.set_val(current_val + 1)
else:
# Pause animation when we hit the end
if anim_running:
toggle_anim(None)
def toggle_anim(event):
global anim_running, anim
if anim_running:
if anim is not None:
anim.event_source.stop()
anim_running = False
btn_play.label.set_text("Play")
else:
# If at the end, restart from 1
if int(slider.val) == T_actual:
slider.set_val(1)
if anim is None:
anim = FuncAnimation(fig, animate, interval=500, cache_frame_data=False)
else:
anim.event_source.start()
anim_running = True
btn_play.label.set_text("Pause")
fig.canvas.draw_idle()
btn_play.on_clicked(toggle_anim)
def update(val):
global fill_ci, fill_ci_vspan
t = int(slider.val)
current_idx = t - 1
# Update Lifetime sub-labels
elapsed_hours = t * 6
e_days = elapsed_hours // 24
e_hours = elapsed_hours % 24
# Using true value for remaining time
rem_hours = float(true_remaining[current_idx]) * 6
r_days = int(rem_hours // 24)
r_hours = int(rem_hours % 24)
slider.valtext.set_text(f"{t}")
txt_elapsed.set_text(f"Elapsed adult lifetime: {e_days}d {e_hours}h")
txt_remaining.set_text(f"Remaining lifetime: {r_days}d {r_hours}h")
# Update Colorbar label
cbar.set_ticklabels(["t=0", f"t={t}"])
# Update Plot 1
line_true.set_data(steps[:t], true_remaining[:t])
line_pred.set_data(steps[:t], predictions[:t])
if has_variances:
if fill_ci is not None:
fill_ci.remove()
std_dev = np.sqrt(variances[:t])
fill_ci = ax1.fill_between(
steps[:t],
predictions[:t] - 1.96 * std_dev,
predictions[:t] + 1.96 * std_dev,
color="red",
alpha=0.2,
)
current_pred_total = t + predictions[current_idx]
current_true_total = t + true_remaining[current_idx]
vline_pred.set_xdata([current_pred_total, current_pred_total])
vline_true.set_xdata([current_true_total, current_true_total])
if has_variances:
if fill_ci_vspan is not None:
fill_ci_vspan.remove()
std_dev_current = np.sqrt(variances[current_idx])
fill_ci_vspan = ax1.axvspan(
current_pred_total - 1.96 * std_dev_current,
current_pred_total + 1.96 * std_dev_current,
color="red",
alpha=0.1,
)
# Update Plot 2
for i in range(T_actual):
if i < t:
traj_lines[i].set_visible(True)
if i == t - 1:
# Highlight the current segment
traj_lines[i].set_color(cmap(1.0))
traj_lines[i].set_linewidth(3.5)
traj_lines[i].set_alpha(1.0)
traj_lines[i].set_zorder(10) # Bring to absolute front
else:
# Draw past segments fainter
color_val = (i / max(1, t - 1)) * 0.85
traj_lines[i].set_color(cmap(color_val))
traj_lines[i].set_linewidth(1.5)
traj_lines[i].set_alpha(0.5)
traj_lines[i].set_zorder(2) # Send to back
else:
traj_lines[i].set_visible(False)
# Update Plot 3
s_W = np.atleast_1d(s_weights_cpu[current_idx])
v_W = np.atleast_2d(v_weights_cpu[current_idx])
bottom = np.zeros(T_actual)
for i, container in enumerate(bar_containers):
if t <= len(s_W) and t <= len(v_W):
contribution = s_W * v_W[:, i]
else:
# Handle padding if s_W / v_W differ slightly in shape
contribution = np.zeros(t)
min_len = min(len(s_W), len(v_W), t)
contribution[:min_len] = s_W[:min_len] * v_W[:min_len, i]
for j, patch in enumerate(container.patches):
if j < len(contribution):
patch.set_height(contribution[j])
patch.set_y(bottom[j]) # Apply stacked bottom
bottom[j] += contribution[j]
else:
patch.set_height(0)
fig.canvas.draw_idle()
# Initialize the plot with the max time
update(T_actual)
slider.on_changed(update)
plt.show()