File size: 4,090 Bytes
5e6866e
 
 
 
 
 
 
 
0094b94
5e6866e
0094b94
 
22a896e
 
 
 
 
0094b94
 
 
 
 
 
22a896e
 
 
0094b94
22a896e
 
5e6866e
 
 
 
 
0094b94
 
 
 
 
 
5e6866e
 
 
 
 
 
 
 
 
0094b94
5e6866e
 
0094b94
5e6866e
0094b94
 
22a896e
 
 
 
0094b94
5e6866e
 
0094b94
5e6866e
22a896e
 
5e6866e
0094b94
5e6866e
22a896e
 
 
 
5e6866e
 
 
 
 
0094b94
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
"""MultiTask representations stored as .npz files on the disk"""
from __future__ import annotations
from pathlib import Path
import numpy as np
import torch as tr

class NpzRepresentation:
    """Generic Task with data read from/saved to npz files. Tries to read data as-is from disk and store it as well"""
    def __init__(self, name: str, n_channels: int):
        self.name = name
        self.n_channels = n_channels
        self.classes: list[str] | None = None
        self.normalization: str | None = None
        self.min: tr.Tensor | None = None
        self.max: tr.Tensor | None = None
        self.mean: tr.Tensor | None = None
        self.std: tr.Tensor | None = None

    @property
    def is_classification(self) -> bool:
        """if we have self.classes"""
        return self.classes is not None

    def set_normalization(self, normalization: str, stats: tuple[tr.Tensor, tr.Tensor, tr.Tensor, tr.Tensor]):
        """sets the normalization"""
        assert normalization in ("min_max", "standardization"), normalization
        assert isinstance(stats, tuple) and len(stats) == 4, stats
        self.normalization = normalization
        self.min, self.max, self.mean, self.std = stats

    def load_from_disk(self, path: Path) -> tr.Tensor:
        """Reads the npz data from the disk and transforms it properly"""
        data = np.load(path, allow_pickle=False)
        data = data if isinstance(data, np.ndarray) else data["arr_0"] # in case on npz, we need this as well
        data = data.astype(np.float32) if np.issubdtype(data.dtype, np.floating) else data # float16 is dangerous
        res = tr.from_numpy(data)
        res = res.unsqueeze(-1) if len(res.shape) == 2 and self.n_channels == 1 else res # (H, W) in some dph/edges
        assert ((res.shape[-1] == self.n_channels and len(res.shape) == 3) or
                (len(res.shape) == 2 and self.is_classification)), f"{self.name}: {res.shape} vs {self.n_channels}"
        return res

    def save_to_disk(self, data: tr.Tensor, path: Path):
        """stores this item to the disk which can then be loaded via `load_from_disk`"""
        np.save(path, data.cpu().detach().numpy(), allow_pickle=False)

    def plot_fn(self, x: tr.Tensor) -> np.ndarray:
        """very basic implementation of converting this representation to a viewable image. You should overwrite this"""
        assert isinstance(x, tr.Tensor), type(x)
        assert len(x.shape) == 3, x.shape # guaranteed to be (H, W, C) at this point
        x = x.nan_to_num(0).cpu().detach()
        if x.shape[-1] != 3:
            x = x[..., 0:1]
        if x.shape[-1] == 1: # guaranteed to be (H, W, 3) after this if statement hopefully
            x = x.repeat(1, 1, 3)
        if x.dtype == tr.uint8 or self.is_classification:
            return x.numpy()
        if self.normalization is not None:
            x = (x * self.std + self.mean) if self.normalization == "standardization" else x
            x = x * (self.max - self.min) + self.min if self.normalization == "min_max" else x
            x = (x * 255) if (self.max <= 1).any() else x
        x = x.numpy().astype(np.uint8)
        return x

    def normalize(self, x: tr.Tensor) -> tr.Tensor:
        """normalizes a data point read with self.load_from_disk(path) using external min/max information"""
        assert self.min is not None, "self.statistics must be set from reader before task.normalize(x)"
        return ((x.float() - self.min) / (self.max - self.min)).nan_to_num(0, 0, 0).float()

    def standardize(self, x: tr.Tensor) -> tr.Tensor:
        """standardizes a data point read with self.load_from_disk(path) using external min/max information"""
        assert self.min is not None, "self.statistics must be set from reader before task.normalize(x)"
        res = ((x.float() - self.mean) / self.std).nan_to_num(0, 0, 0)
        res[(res < -10) | (res > 10)] = 0
        return res.float()

    def __repr__(self):
        return str(self)

    def __str__(self):
        return f"{str(type(self)).split('.')[-1][0:-2]}({self.name}[{self.n_channels}])"