-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
192 lines (175 loc) · 8.28 KB
/
util.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
"""
AI4ER GTC - Sea Ice Classification
Classes for loading the data for input to the models
and visualising the data
"""
import torch
import numpy as np
import matplotlib.pyplot as plt
import rioxarray as rxr
from torch.utils.data import Dataset
from torchvision import transforms
from pytorch_lightning import Callback
import pandas as pd
class SeaIceDataset(Dataset):
"""
An implementation of a PyTorch dataset for loading sea ice SAR/chart image pairs.
Inspired by https://pytorch.org/tutorials/beginner/data_loading_tutorial.html.
"""
def __init__(self, sar_path: str, sar_files: list[str],
chart_path: str, chart_files: list[str],
transform: transforms.Compose = transforms.Compose([]),
class_categories: dict = None,
sar_band3: str = "angle"):
"""
Constructs a SeaIceDataset.
:param sar_path: Base folder path of SAR images
:param sar_files: List of filenames of SAR images
:param chart_path: Base folder path of charts
:param chart_files: List of filenames of charts
:param transform: Callable transformation to apply to images upon loading
:param class_categories: Mapping from SIGRID codes to target classes
:param sar_band3: "angle" to use SAR incidence angle or "ratio" to use HH/HV as third band
"""
self.sar_path = sar_path
self.sar_files = sar_files
self.chart_path = chart_path
self.chart_files = chart_files
self.transform = transform
self.class_categories = class_categories
self.sar_band3 = sar_band3
# read in precomputed mean and std deviation for HH, HV, incidence angle, and ratio
metrics_df = pd.read_csv("metrics.csv", delimiter=",")
self.hh_mean = metrics_df.iloc[0]["hh_mean"]
self.hh_std = metrics_df.iloc[0]["hh_std"]
self.hv_mean = metrics_df.iloc[0]["hv_mean"]
self.hv_std = metrics_df.iloc[0]["hv_std"]
self.angle_mean = metrics_df.iloc[0]["angle_mean"]
self.angle_std = metrics_df.iloc[0]["angle_std"]
self.ratio_mean = metrics_df.iloc[0]["hh_hv_mean"]
self.ratio_std = metrics_df.iloc[0]["hh_hv_std"]
# handle sar_band3
if self.sar_band3 == "angle":
self.band3_mean = self.angle_mean
self.band3_std = self.angle_std
else:
self.sar_path = f"{self.sar_path}_band3"
self.band3_mean = self.ratio_mean
self.band3_std = self.ratio_std
def __len__(self):
"""
Implements the len(SeaIceDataset) magic method. Required to implement by Dataset superclass.
When training/testing, this method tells our training loop how much longer we have to go in our Dataset.
:return: Length of SeaIceDataset
"""
return len(self.sar_files)
def __getitem__(self, i: int):
"""
Implements the SeaIceDataset[i] magic method. Required to implement by Dataset superclass.
When training/testing, this method is used to actually fetch data and apply transformations.
:param i: Index of which image pair to fetch
:return: Dictionary with SAR and chart pair
"""
# load data from files
sar_name = f"{self.sar_path}/{self.sar_files[i]}"
chart_name = f"{self.chart_path}/{self.chart_files[i]}"
sar = rxr.open_rasterio(sar_name, masked=True).values # take all bands for shape of l x w x 3
chart = rxr.open_rasterio(chart_name, masked=True).values # take array of shape l x w
# recategorize classes
if self.class_categories is not None:
for key, value in self.class_categories.items():
chart[np.isin(chart, value)] = key
# apply transforms
sample = {"sar": sar, "chart": chart, "sar_name": sar_name, "chart_name": chart_name}
if self.transform is not None:
# Convert the data to tensors
sar = torch.from_numpy(sar)
chart = torch.from_numpy(chart)
# normalise the sar data with mean and std deviation for each channel
sar_transform = transforms.Compose([transforms.Normalize(mean=[self.hh_mean, self.hv_mean, self.band3_mean],
std=[self.hh_std, self.hv_std, self.band3_std])])
sar = sar_transform(sar)
sample = {"sar": self.transform(sar), "chart": self.transform(chart).squeeze(0).long(),
"sar_name": sar_name, "chart_name": chart_name}
return sample
def visualise(self, i):
"""
Allows us to visualise a particular SAR/chart pair.
:param i: Index of which image pair to visualise
:return: None
"""
sample = self[i]
fig, ax = plt.subplots(1, 2)
ax[0].imshow(sample["sar"])
ax[1].imshow(sample["chart"])
plt.tight_layout()
plt.show()
class Visualise(Callback):
"""
Callback to visualise input/output samples and predictions.
"""
def __init__(self, dataloader, n_files, classification_type):
"""
Construct callback object.
"""
self.dataloader = dataloader
self.n_files = n_files
if classification_type == "binary":
self.vmax = 1 # upper bound of color bar for prediction and truth
elif classification_type == "ternary":
self.vmax = 2 # upper bound of color bar for prediction and truth
elif classification_type == "multiclass":
self.vmax = 100 # upper bound of color bar for prediction and truth
else:
raise ValueError(f"Invalid classification_type: {classification_type}")
def on_validation_epoch_start(self, trainer, pl_module):
"""
Callback to run on validation epoch start.
:param trainer: PyTorch Lightning Trainer class instance
:param pl_module: PyTorch Lightning Module class instance
"""
for batch in self.dataloader:
x, y = batch["sar"].to(pl_module.device), batch["chart"].squeeze().long().to(pl_module.device)
y_hat = pl_module(x)
y_hat_pred = y_hat.argmax(dim=1)
fig, ax = plt.subplots(self.n_files, 5, figsize=(15, self.n_files * 3))
for i in range(self.n_files):
a = x[i].detach().cpu().numpy().transpose(1, 2, 0)
ax[i, 0].imshow(a[:, :, 0])
ax[i, 0].set_title("SAR Band 1")
ax[i, 1].imshow(a[:, :, 1])
ax[i, 1].set_title("SAR Band 2")
ax[i, 2].imshow(a[:, :, 2])
ax[i, 2].set_title("SAR Band 3")
ax[i, 3].imshow(y_hat_pred[i].detach().cpu().numpy(), vmin=0, vmax=self.vmax)
ax[i, 3].set_title("Prediction")
ax[i, 4].imshow(y[i].detach().cpu().numpy(), vmin=0, vmax=self.vmax)
ax[i, 4].set_title("Truth")
plt.tight_layout()
wandb_logger = trainer.logger.experiment
wandb_logger.log({"val_image": fig})
plt.close(fig)
break # only visualise from first batch
def on_test_epoch_start(self, trainer, pl_module):
for batch in self.dataloader:
x, y = batch["sar"].to(pl_module.device), batch["chart"].squeeze().long().to(pl_module.device)
y_hat = pl_module(x)
y_hat_pred = y_hat.argmax(dim=1)
fig, ax = plt.subplots(self.n_files, 5, figsize=(15, self.n_files * 3))
for i in range(self.n_files):
a = x[i].detach().cpu().numpy().transpose(1, 2, 0)
ax[i, 0].imshow(a[:, :, 0])
ax[i, 0].set_title("SAR Band 1")
ax[i, 1].imshow(a[:, :, 1])
ax[i, 1].set_title("SAR Band 2")
ax[i, 2].imshow(a[:, :, 2])
ax[i, 2].set_title("SAR Band 3")
ax[i, 3].imshow(y_hat_pred[i].detach().cpu().numpy(), vmin=0, vmax=self.vmax)
ax[i, 3].set_title("Prediction")
ax[i, 4].imshow(y[i].detach().cpu().numpy(), vmin=0, vmax=self.vmax)
ax[i, 4].set_title("Truth")
plt.tight_layout()
wandb_logger = trainer.logger.experiment
wandb_logger.log({"test_image": fig})
plt.close(fig)
break # only visualise from first batch