-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexplain.py
316 lines (255 loc) · 10.9 KB
/
explain.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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BSD 3-Clause License (see LICENSE file)
# Copyright (c) Image and Signaling Process Group (ISP) IPL-UV 2021
# All rights reserved.
"""
Explain latent space of LatentGranger
"""
import os
import git
import numpy as np
import argparse, yaml
from datetime import datetime
import netCDF4 as nc
from natsort import natsorted
import torch
import pytorch_lightning as pl
from PIL import Image
import loaders
# Model
import archs
from losses import lag_cor
from losses import granger_loss, granger_simple_loss
from utils import *
# PyTorch Captum for XAI
from captum.attr import IntegratedGradients
from captum.attr import LayerConductance, LayerIntegratedGradients
from captum.attr import NeuronConductance, NeuronIntegratedGradients
# ArgParse
parser = argparse.ArgumentParser(description="ArgParse")
parser.add_argument('--arch', default='vae', type=str,
help='arch name (default: vae)')
parser.add_argument('-d', '--data', default='toy', type=str,
help='database name (default: toy)')
parser.add_argument('--loader', default='base', type=str,
help='loaders name (default: base) associated to a config file in configs/loaders/')
parser.add_argument('--dir', default='experiment', type=str,
help='path to experiment folder')
parser.add_argument('-c','--checkpoint', default='best.ckpt', type=str,
help='checkpoint (default: last)')
parser.add_argument('-t','--timestamp', default='', type=str,
help='timestampt (default:)')
parser.add_argument('--train', action = 'store_true',
help='use trainig data')
parser.add_argument('--val', action = 'store_true',
help='use val data')
parser.add_argument('--save', action = 'store_true',
help='save images')
parser.add_argument('--grad', action = 'store_true',
help='compute average gradient')
parser.add_argument('--extract', action = 'store_true',
help='extract latent series')
parser.add_argument('--nig', action = 'store_true',
help='run NIG')
parser.add_argument('--latint', action = 'store_true',
help='run LATENT INTERVENTIONS')
parser.add_argument('--idx', type=int, default = 0,
help='index of reconstruction to plot')
args = parser.parse_args()
log_root = os.path.join(args.dir, 'logs', args.data, args.arch)
check_root = os.path.join(args.dir, 'checkpoints', args.data, args.arch)
print(check_root)
allchckpts = natsorted(
[
fname
for fname in os.listdir(check_root)
],
)
if args.timestamp == '':
chosen = allchckpts[-1]
else:
### search the closer one
### .... to do ...
#for timestamp in timestamps:
dt = datetime.fromisoformat(args.timestamp)
chosen = min(allchckpts,key=lambda x : abs(datetime.fromisoformat(x) - dt))
checkpoint = os.path.join(check_root, chosen, args.checkpoint)
print('chosen checkpoint: ' + checkpoint)
with open(f'configs/archs/{args.arch}.yaml') as file:
# The FullLoader parameter handles the conversion from YAML
# scalar values to Python dictionary format
arch_config = yaml.load(file, Loader=yaml.FullLoader)
## define the model and load the checkpoint
model = getattr(archs, arch_config['class']).load_from_checkpoint(checkpoint)
print("model loaded with chosen checkpoint")
################### print model info #####################
print(model)
print(f'gamma: {model.gamma}, maxlag: {model.lag}')
print(f'causalix: {model.causalix}')
#################### load data #########################
with open(f'configs/loaders/{args.loader}.yaml') as file:
# The FullLoader parameter handles the conversion from YAML
# scalar values to Python dictionary format
loader_config = yaml.load(file, Loader=yaml.FullLoader)
with open(f'configs/data/{args.data}.yaml') as file:
# The FullLoader parameter handles the conversion from YAML
# scalar values to Python dictionary format
data_config = yaml.load(file, Loader=yaml.FullLoader)
# Build data module
datamodule_class = getattr(loaders, loader_config['class'])
datamodule = datamodule_class(loader_config, data_config, arch_config['processing_mode'])
##################### here we can do inference, plot ##############
if args.train:
data = datamodule.data_train
elif args.val:
data = datamodule.data_val
else:
data = datamodule.data_test
savedir = os.path.join('viz', chosen)
os.makedirs(savedir, exist_ok = True)
x, target = data.getAll()
print(target.shape)
x = torch.reshape(x, (1,) + x.shape)
x.requires_grad_()
target = torch.reshape(target, (1,) + target.shape)
model.eval()
x_out, latent, mu, sigma = model(x)
for j in range(latent.shape[-1]):
corr = lag_cor(latent[:,:,j], target, lag = model.lag)
print(f'lagged correlation with target of latent {j}: {corr}')
gloss = granger_loss(latent, target, maxlag = model.lag, idx=j)
print(f'granger losss of latent {j}: {gloss}')
if args.save:
svpth = os.path.join(savedir, f'{chosen}_latents.tiff')
plot_latent(mu[:,:], target, svpth)
else:
plot_latent(mu, target)
### prepare arrays
if hasattr(data, 'mask'):
mask = data.mask
avg = np.zeros(data.mask.shape + (latent.shape[-1],), dtype = float)
imout = np.zeros(data.mask.shape + (3,), dtype = float)
else:
avg = np.zeros(data.input_size + (latent.shape[-1],), dtype = float)
imout = np.zeros(data.input_size + (3,), dtype = float)
mask = avg[:,:,0] == 0
tpb = model.tpb
if arch_config['processing_mode']== 'flat':
imout[mask, 0] = x.detach().numpy()[0, args.idx, :]
imout[mask, 1] = x_out.detach().numpy()[0, args.idx, :]
imout[mask, 2] = (imout[mask, 0] - imout[mask, 1])**2
else:
imout[:, :, 0] = x.detach().numpy()[0, args.idx, :, :, 0]
imout[:, :, 1] = x_out.detach().numpy()[0, args.idx, :, :, 0]
imout[:, :, 2] = (imout[:, :, 0] - imout[:, :, 1])**2
if args.grad:
for j in range(latent.shape[-1]):
grad = np.zeros(x.shape[1:])
for i in range(latent.shape[1]):
mu[i,j].backward(retain_graph = True)
#grad[i,:] += np.abs(x.grad.numpy()[0,i,:])
grad[i,:] += x.grad.numpy()[0,i,:]
x.grad.fill_(0.0)
avg[:,:,j][mask] = np.mean(grad, 0)
#avg[:,:,j][mask] = np.amax(grad, 0)
#avg[:,:,j] = grad.mean(0)[:,:,0]
if args.save:
img = Image.fromarray(imout[:,:,1])
svpth = os.path.join(savedir, f'{chosen}_reconstruction_lag={model.lag}.tiff')
img.save(svpth)
for j in range(latent.shape[-1]):
img = Image.fromarray(avg[:,:,j])
svpth = os.path.join(savedir, f'{chosen}_grad_avg_latent{j}_lag={model.lag}.tiff')
img.save(svpth)
else:
plot_output(imout)
if args.grad:
plot_output(avg)
if args.extract:
## save latent
np.savetxt(os.path.join(savedir, f'{chosen}_latents.csv'), mu.detach().numpy())
## save target
np.savetxt(os.path.join(savedir, f'{chosen}_target.csv'), target.detach().numpy()[0,:])
## save causal latent
np.savetxt(os.path.join(savedir, f'{chosen}_causal_latent.csv'), mu.detach().numpy()[:,
int(model.causalix)])
if args.nig:
#baseline = np.zeros(x.shape, dtype="float32")
#baseline = torch.Tensor(baseline)
baseline = torch.mean(x[0,:,:], 0).expand(x.shape)
nig = NeuronIntegratedGradients(model, model.mu_layer, multiply_by_inputs = False)
for j in range(latent.shape[-1]):
avg_nig = np.zeros(x.shape[-1], dtype="float32")
# Baseline for Integrated Gradients
# Zeros (default)
# 1) NeuronIntegratedGradients, to see, for each latent representation,
# the attribution to each of the input spatial locations in features (e.g. NDVI)
attr_maps = nig.attribute(x,(j,), baselines=baseline, internal_batch_size=1)
attr_maps = attr_maps
os.makedirs(os.path.join(savedir, f'nig{j}'), exist_ok = True)
for i in range(attr_maps.shape[1]):
imgarray = np.zeros(mask.shape)
avg_nig += attr_maps.detach().numpy()[0,i,:]
imgarray[mask] = attr_maps.detach().numpy()[0,i,:]
img = Image.fromarray(imgarray)
img.save(os.path.join(savedir, f'nig{j}', f'{i}_.tiff'))
avg_nig = avg_nig / attr_maps.shape[1]
imgarray = np.zeros(mask.shape)
imgarray[mask] = avg_nig
img = Image.fromarray(imgarray)
img.save(os.path.join(savedir, f'avg_nig_{j}_.tiff'))
if args.latint:
avg.fill(0) ##clean avg array
avg_max = avg.copy()
avg_min = avg.copy()
avg_plus = avg.copy()
avg_minus = avg.copy()
latent_max = torch.amax(mu, 0)
latent_min = torch.amin(mu, 0)
std, m = torch.std_mean(mu, 0)
print(m)
print(std)
for j in range(mu.shape[1]):
basemu = mu.clone()
#basemu[:,j] = m[j]
base = model.decoder(basemu)
latent_int_max = mu.clone()
latent_int_max[:,j] = latent_max[j]
latent_int_min = basemu.clone()
latent_int_min[:,j] = latent_min[j]
latent_int_plus = basemu.clone()
latent_int_plus[:,j] += 2 * sigma[:, j]
latent_int_minus = basemu.clone()
latent_int_minus[:,j] -= 2 * sigma[:, j]
out_int_max = model.decoder(latent_int_max)
out_int_min = model.decoder(latent_int_min)
out_int_plus = model.decoder(latent_int_plus)
out_int_minus = model.decoder(latent_int_minus)
diff_int_max = (out_int_max - base) #/ (x_out[0,:,:] + 0.0001)
diff_int_min = (out_int_min - base) #/ (x_out[0,:,:] + 0.0001)
diff_int_plus = (out_int_plus - base) #/ (x_out[0,:,:] + 0.0001)
diff_int_minus = (out_int_minus - base) #/ (x_out[0,:,:] + 0.0001)
avg_max[:,:,j][mask] = np.mean(diff_int_max.detach().numpy(), 0)
avg_min[:,:,j][mask] = np.mean(diff_int_min.detach().numpy(), 0)
avg_plus[:,:,j][mask] = np.mean(diff_int_plus.detach().numpy(), 0)
avg_minus[:,:,j][mask] = np.mean(diff_int_minus.detach().numpy(), 0)
if args.save:
for j in range(latent.shape[-1]):
img_max = Image.fromarray(avg_max[:,:,j])
img_min = Image.fromarray(avg_min[:,:,j])
img_plus = Image.fromarray(avg_plus[:,:,j])
img_minus = Image.fromarray(avg_minus[:,:,j])
svpth = os.path.join(savedir, f'{chosen}_latint_max_avg_latent{j}_lag={model.lag}.tiff')
img_max.save(svpth)
svpth = os.path.join(savedir, f'{chosen}_latint_min_avg_latent{j}_lag={model.lag}.tiff')
img_min.save(svpth)
svpth = os.path.join(savedir, f'{chosen}_latint_plus_avg_latent{j}_lag={model.lag}.tiff')
img_plus.save(svpth)
svpth = os.path.join(savedir, f'{chosen}_latint_minus_avg_latent{j}_lag={model.lag}.tiff')
img_minus.save(svpth)
else:
plot_output(avg_max)
plot_output(avg_min)
plot_output(avg_plus)
plot_output(avg_minus)