Repository navigation
Expand file tree
/
Copy pathtest.py
More file actions
487 lines (408 loc) · 19.6 KB
/
Copy pathtest.py
File metadata and controls
487 lines (408 loc) · 19.6 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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import torch
import rasterio
import numpy as np
from pathlib import Path
from glob import glob
import pickle
from torch import nn
from torchvision.transforms import Normalize, Compose
from models import UNet, Veg_MT, UNet3Plus, AttentionUNet
from geoutils import save_np_array_to_img, file_meta
import datetime
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from scipy.interpolate import interpn
from geoutils import file_meta
from utils import (
load_checkpoint, most_recent_file,
parse_date, apply_checkpoint, nanmean, nanIoU, nanFscore,
generate_model_name, ToTensor, SelectChannels, normalize_val
)
import scipy
# import segmentation_models_pytorch as smp
cfg = {
'unet_data': {
'opt_image_bands': [1, 2, 3, 4],
'sar_image_polarizations': [1],
'labels_bands': [1, 2, 3, 4],
'data_stats': {
'opt_mean': 1065.408447265625,
'opt_std': 1222.510009765625,
'sar_mean': 250.40419006347656,
'sar_std': 141.63661193847656,
# ['avg', 'cov', 'dns', 'p95']
'labels_mean': [2.6482544, 27.901573, 21.948093, 3.10381],
'labels_std': [4.6751084, 42.40032, 34.249233, 5.437437]
},
'pkl_path': 'data/datasets/pkl/dataset_unet_*.pkl',
}
}
"""
Unpickles the most recent dataset and makes prediction on all test (1) tiles
"""
class PredictTestset():
def __init__(self, model: nn.Module,
opt_image_bands: list[int] = [1, 2, 3, 4], sar_image_polarizations: list[int] = [1], labels_bands: list[int] = [1], edge = 0,
output_activation=False,bayesian: bool = False, pkl_path: str = 'data/datasets/pkl/*.pkl', supervised=True, name=None,
seg=True, reg=True, local_model=True):
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
self.model = model
self.arch = model.__class__.__name__.lower()
self.bayesian = bayesian
self.output_activation = output_activation
self.supervised=supervised
self.seg =seg
self.reg=reg
self.local_model = local_model
if name is None:
self.name = generate_model_name(self.model, self.supervised)
else:
self.name = name
self.directory = self.name.split('_')[0].lower()
self.performed_predictions = False
pkl_files = glob(f'{pkl_path}')
pkl_file = Path(most_recent_file(pkl_files))
with pkl_file.open('rb') as pkl:
print(f"Loading dataset '{pkl_file}'...")
dataset = pickle.load(pkl)
self.labels = dataset['labels']
self.images = dataset['images']
self.patch_size = dataset['patch_size']
self.margin = edge # dataset['margin']
# total number of pixels to predict in each patch
self.n_points = (self.patch_size-(2*self.margin))**2
# number of variables to predict
c = len(self.labels)
h, w = self.labels[0].shape
if bayesian:
self.mean_result = torch.zeros((c,h,w), dtype=float)
self.mean_result[self.labels == np.nan] = np.nan
self.variance_result = torch.zeros((c,h,w), dtype=float)
self.variance_result[self.labels == np.nan] = np.nan
else:
self.result = torch.full((len(self.labels),h,w), float('nan'), dtype=float)
self.result[torch.from_numpy(self.labels == np.nan)] = np.nan
self.smooth_result = torch.full((len(self.labels),h,w), 0.0, dtype=float)
self.smooth_result[torch.from_numpy(self.labels == np.nan)] = np.nan
self.iou = torch.zeros((1), dtype=float)
self.fscore = torch.zeros((1), dtype=float)
self.mae_error = torch.zeros((c,h,w), dtype=float)
self.mse_error = torch.zeros((c,h,w), dtype=float)
self.total_me_error = torch.zeros((c), dtype=float)
self.total_mae_error = torch.zeros((c), dtype=float)
self.total_mse_error = torch.zeros((c), dtype=float)
self.ds_split_mask = dataset['split_mask'].squeeze(0)
self.image_indices = dataset['image_indices']
self.locations = dataset['test']
opt_channels = np.array(opt_image_bands) - 1
sar_channels = np.array(sar_image_polarizations) - 1
labels_channels = np.array(labels_bands) - 1
def predict_all(self):
print(f'Performing predictions with {self.margin} px margin..')
self.model.eval()
for i in range(len(self)):
self.predict(i,self.seg, self.reg, self.local_model)
#plt.imshow(self.smooth_result.transpose(1,2,0))
self.smooth_result[0] = (self.smooth_result[0] >= 0.5).to(dtype= torch.float32)
self.performed_predictions = True
def predict_all_test(self, subdivs:np.ndarray, seg=True, reg=True):
subdivs = torch.from_numpy(subdivs).to('cuda')
n_bands = 2
a, b, c, d = subdivs.shape
predicted = np.zeros((a,n_bands,c,d), dtype=float)
for i in range(len(subdivs)):
pred_patch = self.predict_test(subdivs[i:i+1,:,:,:], seg, reg)
predicted[i] = pred_patch.detach().cpu().numpy()
return predicted
"""
The code is setup to expect data in batches. As a result there is some squeezing/unsqueezing in the following code to address this.
"""
def predict(self, index, seg, reg, local_model, smoothen=True):
i, j = self.locations[index]
i_slice = slice(i, i+self.patch_size)
j_slice = slice(j, j+self.patch_size)
# consider only pixels within margin to allow to sufficient spatial context
i_margin_slice = slice(i+self.margin, i+self.patch_size-self.margin)
j_margin_slice = slice(j+self.margin, j+self.patch_size-self.margin)
i_patch_slice = slice(self.margin, -self.margin)
j_patch_slice = slice(self.margin, -self.margin)
opt_idx, sar_idx = self.image_indices['opt'], self.image_indices['sar']
opt_patch = torch.from_numpy(self.images[opt_idx][:, i_slice, j_slice])
sar_patch = torch.from_numpy(self.images[sar_idx][:, i_slice, j_slice])
# input patch
x = torch.cat([opt_patch, sar_patch], dim=0).unsqueeze(0).to(device=self.device)
if local_model:
if self.model.opt_only:
x = x[:,:self.model.in_channels]
if self.model.sar_only:
x = x[:,-self.model.sar_channels:]
# ground truth patch
if (seg and reg):
y = self.labels
elif seg:
y = self.labels[:1]
else:
y = self.labels[1:]
y = torch.from_numpy(y[:, i_slice, j_slice])
y = y.unsqueeze(0)
mask = torch.isnan(y[:,:1])
y_pred = self.model(x)
y_pred = y_pred.detach().cpu()
if seg:
m = torch.nn.Sigmoid()
y_pred[0,0] = m(y_pred[0,0, :,:])
if (seg and reg):
y_pred_reg = y_pred[:,1:]
y_reg = y[:,1:]
elif reg:
y_pred_reg = y_pred
y_reg = y
if seg:
self.iou += nanIoU(y_pred, y, mask, test=True)
self.fscore += nanFscore(y_pred, y, mask, test=True)
if reg:
self.total_me_error += nanmean((y_pred_reg-y_reg), mask, edge=self.margin).squeeze()
self.total_mae_error += nanmean((y_pred_reg-y_reg).abs(), mask, edge=self.margin).squeeze()
self.total_mse_error += nanmean((y_pred_reg-y_reg)**2, mask, edge=self.margin).squeeze()
error_mae = (y_pred_reg - y_reg).abs()
error_mae[mask==True] = 0
error_mse =(y_pred_reg - y_reg)**2
error_mse[mask==True] = 0
y_pred[torch.isnan(y)] = 0 #np.nan
y_pred = y_pred.squeeze(0)
if smoothen:
# Weight the prediction in the center of the window more than the edges
window_size= self.patch_size
WINDOW_SPLINE_2D = _window_2D(window_size=window_size, power=2)
smooth_patch = y_pred * WINDOW_SPLINE_2D
self.smooth_result[:, i_slice, j_slice] += smooth_patch
if reg:
if self.margin == 0:
self.result[:,i_slice, j_slice] = y_pred
self.mae_error[:,i_slice, j_slice] = error_mae
self.mse_error[:,i_slice, j_slice] = error_mse
else:
self.result[:,i_margin_slice,j_margin_slice] = y_pred[:,i_patch_slice,j_patch_slice]
self.mae_error[0,i_margin_slice,j_margin_slice] = error_mae[:, :,i_patch_slice,j_patch_slice]
self.mse_error[0,i_margin_slice,j_margin_slice] = error_mse[:, :,i_patch_slice,j_patch_slice]
def predict_patch(self, index):
self.margin = 0
i, j = self.locations[index]
# consider only pixels within margin to allow to sufficient spatial context
i_margin_slice = slice(i+self.margin, i+self.patch_size-self.margin)
j_margin_slice = slice(j+self.margin, j+self.patch_size-self.margin)
self.predict( index)
return self.result[:,i_margin_slice,j_margin_slice]
def predict_test(self, x:np.ndarray):
y_pred = self.model(x)
m = torch.nn.Sigmoid()
y_pred[:,0] = m(y_pred[:,0])
y_pred = y_pred.detach().cpu()
return y_pred
def binarize_treeMap(self, map_pred, thresholds):
"""
From a threshold list 'thresholds' containing one threshold per output
channel for comparison, the predictions are converted to a binary mask.
"""
assert (map_pred.shape[0] == len(thresholds))
for i in range(map_pred.shape[0]):
# Per-pixel and per-channel comparison on a threshold to
# binarize prediction masks:
map_pred[i, :, :] = (map_pred[i, :, :] > thresholds[i]).astype('uint8')
return map_pred
"""
Save prediction and errors as maps (.tif)
"""
def write_to_disk(self, gt_meta):
assert self.performed_predictions
print(f'Writing {self.name} predictions to disk..')
meta = gt_meta.copy()
meta['driver'] = 'GTiff'
meta['count'] = 1
meta['dtype'] = 'float32'
Path(f'result/{self.name}').mkdir(parents=True, exist_ok=True)
if self.bayesian:
for i, label in enumerate(['treemask','treeheight']):
save_np_array_to_img(np.expand_dims(self.mean_result.numpy()[i], 0), meta, f'result/{self.name}/mean_{label}_{self.name}_{parse_date()}.tif')
save_np_array_to_img(np.expand_dims(self.variance_result.numpy()[i], 0), meta, f'result/{self.name}/variance_{label}_{self.name}_{parse_date()}.tif')
save_np_array_to_img(np.expand_dims(self.mae_error.numpy()[i], 0), meta, f'result/{self.name}/mae_{label}_{self.name}_{parse_date()}.tif')
save_np_array_to_img(np.expand_dims(self.mse_error.numpy()[i], 0), meta, f'result/{self.name}/mse_{label}_{self.name}_{parse_date()}.tif')
else:
for i, label in enumerate(['treemask','treeheight']):
save_np_array_to_img(np.expand_dims(self.smooth_result.numpy()[i], 0), meta, f'result/{self.name}/{label}_{self.name}_{parse_date()}.tif')
label = 'treeheight'
if self.reg:
save_np_array_to_img(self.mae_error.numpy(), meta, f'result/{self.name}/mae_{label}_{self.name}_{parse_date()}.tif')
save_np_array_to_img(self.mse_error.numpy(), meta, f'result/{self.name}/mse_{label}_{self.name}_{parse_date()}.tif')
def write_error_to_disk(self):
assert self.performed_predictions
err = str(self.calculate_errors())
Path(f'result/{self.name}').mkdir(parents=True, exist_ok=True)
with open(f'result/{self.name}/{self.name}_{parse_date()}.txt', 'w') as fh:
fh.write(err)
def calculate_errors(self):
assert self.performed_predictions
y_mean = np.nanmean(self.labels[1,self.ds_split_mask == 1], axis=0)
y_max = np.nanmax(self.labels[1,self.ds_split_mask == 1], axis=0)
y_min = np.nanmin(self.labels[1,self.ds_split_mask == 1], axis=0)
# MAE
mae_nums = (self.total_mae_error / len(self.locations)).numpy()
mae = []
mae_norm = []
mae_range = []
# MSE
mse_nums = (self.total_mse_error / len(self.locations)).numpy()
mse = []
mse_norm = []
mse_range = []
# RMSE
rmse_nums = np.array([np.sqrt(x) for x in mse_nums])
rmse = []
rmse_norm = []
rmse_range = []
# MBE
me_nums = (self.total_me_error / len(self.locations)).numpy()
mbe = []
#IoU
iou_nums = (self.iou/len(self.locations)).numpy()
iou = []
#fscore
fscore_nums = (self.fscore/len(self.locations)).numpy()
fscore = []
for i, label in enumerate(['treeheight']):
iou.append(f'{label}: {100*iou_nums[i]:.4f}')
fscore.append(f'{label}: {100*fscore_nums[i]:.4f}')
mae.append(f'{label}: {mae_nums[i]:.3f}')
mae_norm.append(f'{label}: {100*(mae_nums[i]/y_mean)}')
mae_range.append(f'{label}: {100*(mae_nums[i]/(y_max-y_min))}')
mse.append(f'{label}: {mse_nums[i]}')
mse_norm.append(f'{label}: {100*(mse_nums[i]/y_mean)}')
mse_range.append(f'{label}: {100*(mse_nums[i]/(y_max-y_min))}')
rmse.append(f'{label}: {rmse_nums[i]}')
rmse_norm.append(f'{label}: {100*(rmse_nums[i]/y_mean)}')
rmse_range.append(f'{label}: {100*(rmse_nums[i]/(y_max-y_min))}')
mbe.append(f'{label}: {me_nums[i]}')
results = {
'IoU': iou,
'F-score': fscore,
'mae': mae,
'mae_norm': mae_norm,
'mae_range': mae_range,
'mse': mse,
'mse_norm': mse_norm,
'mse_range': mse_range,
'rmse': rmse,
'rmse_norm': rmse_norm,
'rmse_range': rmse_range,
'mbe': mbe
}
return results
"""
Return a flattened vector for each structure variable
Each vector contain (y_pred,y) tuples excluding all nan values
"""
def prediction_label_matrix(self):
assert self.performed_predictions
predictions = torch.clone(self.result)
# predictions from the test set
predictions = predictions[:,self.ds_split_mask == 1]
y = torch.clone(torch.from_numpy(self.labels))
# labels from the test set
y = y[:,self.ds_split_mask == 1]
assert predictions.shape == y.shape
indices = predictions.isfinite() & y.isfinite()
matrix = torch.stack((predictions[indices],y[indices]), dim=1)
# maps with tuple (y_pred,y) for each pixel
return matrix.reshape(len(self.labels),-1,2)
def __len__(self):
return len(self.locations)
def _spline_window(window_size, power=2):
"""
Squared spline (power=2) window function:
https://www.wolframalpha.com/input/?i=y%3Dx**2,+y%3D-(x-2)**2+%2B2,+y%3D(x-4)**2,+from+y+%3D+0+to+2
"""
intersection = int(window_size/4)
wind_outer = (abs(2*(scipy.signal.triang(window_size))) ** power)/2
wind_outer[intersection:-intersection] = 0
wind_inner = 1 - (abs(2*(scipy.signal.triang(window_size) - 1)) ** power)/2
wind_inner[:intersection] = 0
wind_inner[-intersection:] = 0
wind = wind_inner + wind_outer
wind = wind / np.average(wind)
wind = normalize_val(wind)
return wind
cached_2d_windows = dict()
def _window_2D(window_size, power=2, plot=False):
"""
Make a 1D window function, then infer and return a 2D window function.
Done with an augmentation, and self multiplication with its transpose.
Could be generalized to more dimensions.
"""
# Memorization
#global cached_2d_windows
key = "{}_{}".format(window_size, power)
if key in cached_2d_windows:
wind = cached_2d_windows[key]
else:
wind = _spline_window(window_size, power)
wind = np.expand_dims(np.expand_dims(wind, axis=1), axis=1)
print(wind.shape, wind.transpose(1, 0, 2).shape)
wind = wind * wind.transpose(1, 0, 2) #1,64,1
wind = wind.transpose(2,0,1)
if plot:
# For demo purpose, let's look once at the window:
plt.imshow(wind[:, :, 0], cmap="viridis")
plt.title("2D Windowing Function for a Smooth Blending of "
"Overlapping Patches")
plt.show()
cached_2d_windows[key] = wind
return wind
def main():
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
# # Test
cfg = {
'unet_data': {
'opt_image_bands': [1, 2, 3, 4],
'sar_image_polarizations': [1],
'labels_bands': [1,2],
'pkl_path': 'data/datasets/pkl/dataset_unet_*.pkl'
}}
# sar only
model = Veg_MT(in_channels=1, out_channels=2,features=[32, 64, 128, 256, 512], upsample='bilinear', use_se_block=False, sar_channels=1,
partial_conv=True, entry_block=True, dropout=True, compute_seg=True, compute_reg=True , sar_only=True
).to(device=DEVICE)
ckpt = load_checkpoint(r"C:\GridEyeS\MT_3DTrees\model\saronly_Veg_MT\05-Dec-2023\saronly_Veg_MT_E19_05-Dec-2023.pt")
apply_checkpoint(ckpt, model)
name = generate_model_name(model)
meta = file_meta()
test_ds = PredictTestset(model, name=name, bayesian=False, output_activation=True, **cfg['unet_data'], edge=16, seg=True,reg=True)
test_ds.predict_all()
test_ds.write_to_disk(meta)
test_ds.write_error_to_disk()
# opt only
model = Veg_MT(in_channels=4, out_channels=2,features=[32, 64, 128, 256, 512], upsample='bilinear', use_se_block=False,
partial_conv=True, entry_block=True, dropout=True, compute_seg=True, compute_reg=True , opt_only=True
).to(device=DEVICE)
ckpt = load_checkpoint(r"C:\GridEyeS\MT_3DTrees\model\optonly_Veg_MT\05-Dec-2023\optonly_Veg_MT_E15_05-Dec-2023.pt")
apply_checkpoint(ckpt, model)
name = generate_model_name(model)
meta = file_meta()
test_ds = PredictTestset(model, name=name, bayesian=False, output_activation=True, **cfg['unet_data'], edge=16, seg=True,reg=True)
test_ds.predict_all()
test_ds.write_to_disk(meta)
test_ds.write_error_to_disk()
# opt+sar
model = Veg_MT(in_channels=5, out_channels=2,features=[32, 64, 128, 256, 512], upsample='bilinear', use_se_block=False, sar_channels=1,
partial_conv=False, entry_block=True, dropout=True, compute_seg=True, compute_reg=True
).to(device=DEVICE)
ckpt = load_checkpoint(r"C:\GridEyeS\MT_3DTrees\model\Veg_MT_opt_sar\Veg_MT_E21_14-Dec-2023.pt")
apply_checkpoint(ckpt, model)
name = generate_model_name(model)+'wo_partial_conv_wo_seg_branch'
meta = file_meta()
test_ds = PredictTestset(model, name=name, bayesian=False, output_activation=True, **cfg['unet_data'], edge=16, seg=True,reg=True)
test_ds.predict_all()
test_ds.write_to_disk(meta)
test_ds.write_error_to_disk()
if __name__ == '__main__':
torch.cuda.empty_cache()
main()