dronescapes / dronescapes_reader /npz_representation.py
Meehai's picture
refactored all code and will soon include global stats as well
0094b94
raw
history blame
3.98 kB
"""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._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
@property
def statistics(self) -> tuple[tr.Tensor, tr.Tensor, tr.Tensor, tr.Tensor] | None:
return (self._min, self._max, self._mean, self._std) if self._min is not None else None
@statistics.setter
def statistics(self, stats: tuple[tr.Tensor, tr.Tensor, tr.Tensor, tr.Tensor]):
assert isinstance(stats, tuple) and len(stats) == 4, stats
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.statistics is not None:
x = (x * self._std + self._mean) if (x.min() < 0 or x.max() > 1) else x * (self._max - (m := self._min)) + m
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.statistics 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.statistics is not None, "self.statistics must be set from reader before task.standardize(x)"
return ((x.float() - self._mean) / self._std).nan_to_num(0, 0, 0).float()
def __repr__(self):
return str(self)
def __str__(self):
return f"{str(type(self)).split('.')[-1][0:-2]}({self.name}[{self.n_channels}])"