Datasets:
File size: 7,095 Bytes
ec5bf94 98bf256 ec5bf94 98bf256 ec5bf94 98bf256 ec5bf94 | 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 | # Feature normalisation, fitted on the training split alone.
#
# The scheme is picked by name: 'robust' is what the published studies used, 'standard'
# and 'robust_axov4' are the other two the configuration tree offers, and 'unnormalized'
# leaves the hardware integers as they are.
import logging
import pickle
from dataclasses import dataclass, field
from pathlib import Path
import awkward as ak
import numpy as np
log = logging.getLogger(__name__)
@dataclass
class L1DataNormalizer:
"""Shift and scale each feature of each object by parameters fitted on train.
:param name: The scheme, one of ``unnormalized``, ``robust``, ``standard`` and
``robust_axov4``. It also names the ml-ready cache, so two schemes never share
one directory.
:param hyperparams: Passed to the fit of that scheme, e.g. the quantiles bounding
the robust range. ``None`` for a scheme that takes none.
"""
name: str
hyperparams: dict | None = None
norm_params: dict = field(default_factory=dict, init=False)
def fit(self, data: ak.Array, obj_name: str) -> None:
"""Determine one object's parameters. Fit on the training split only."""
log.info("Fitting %s normalisation to %s.", self.name, obj_name)
self.obj_name = obj_name
fit = getattr(self, f"_{self.name}_fit")
if self.hyperparams:
fit(data, **self.hyperparams)
else:
fit(data)
def norm(self, data: ak.Array, obj_name: str) -> ak.Array:
"""Apply the parameters fitted earlier to any split."""
return getattr(self, f"_{self.name}")(data, obj_name)
def import_norm_params(self, norm_filepath: Path, obj_name: str) -> None:
"""Read one object's parameters back, for a run that did not fit them itself."""
if not Path(norm_filepath).is_file():
raise FileNotFoundError(f"Norm params not found at {norm_filepath}!")
self.norm_params[obj_name] = pickle.loads(Path(norm_filepath).read_bytes())
def export_norm_params(self, norm_filepath: Path, obj_name: str) -> None:
"""Write one object's parameters beside the split they were fitted on."""
if Path(norm_filepath).suffix != ".pkl":
raise ValueError(
f"Norm params are only written to .pkl, not {norm_filepath}."
)
Path(norm_filepath).write_bytes(pickle.dumps(self.norm_params[obj_name]))
def setup_1d_denorm(self, object_feature_map: dict) -> None:
"""Build the tensors that undo the normalisation on a flattened model input.
:param object_feature_map: ``{object: {feature: [flat indices]}}``, as the torch
stage writes it beside the tensors.
"""
import torch
self.object_feature_map = object_feature_map
length = sum(len(i) for m in object_feature_map.values() for i in m.values())
self.scale_tensor = torch.ones(length, dtype=torch.float32)
self.shift_tensor = torch.zeros(length, dtype=torch.float32)
for obj_name, feature_map in object_feature_map.items():
self._fill_1d(obj_name, feature_map)
def norm_1d_tensor(self, data):
"""Normalise a flattened model input in place."""
scale, shift = self._as(data)
return data.sub_(shift).div_(scale)
def denorm_1d_tensor(self, data):
"""Undo :meth:`norm_1d_tensor` in place, e.g. on a model's reconstruction."""
scale, shift = self._as(data)
return data.mul_(scale).add_(shift)
def _fill_1d(self, obj_name: str, feature_map: dict) -> None:
"""One object's parameters, spread over the columns it occupies."""
params = self.norm_params.get(obj_name)
if not params:
raise ValueError(f"Missing norm params for the {obj_name} object.")
for feat, idxs in feature_map.items():
self.scale_tensor[idxs] = float(params.get(feat, {}).get("scale", 1.0))
self.shift_tensor[idxs] = float(params.get(feat, {}).get("shift", 0.0))
def _as(self, data):
"""The parameter tensors, on the device and dtype of the data they act on."""
if getattr(self, "scale_tensor", None) is None:
raise ValueError("Run setup_1d_denorm before normalising a flat tensor.")
return (
self.scale_tensor.to(device=data.device, dtype=data.dtype),
self.shift_tensor.to(device=data.device, dtype=data.dtype),
)
def _affine(self, data: ak.Array, obj_name: str) -> ak.Array:
"""Shift and scale every feature by the parameters fitted for it."""
params = self.norm_params[obj_name]
return ak.Array(
{
f: (data[f] - params[f]["shift"]) / params[f]["scale"]
for f in data.fields
}
)
def _unnormalized(self, data: ak.Array, obj_name: str) -> ak.Array:
return data
def _unnormalized_fit(self, data: ak.Array) -> None:
self._record({f: (0.0, 1.0) for f in data.fields})
# Three schemes that differ in how they are fitted and not in how they are applied.
_robust = _affine
_standard = _affine
_robust_axov4 = _affine
def _robust_fit(self, data: ak.Array, percentiles: list) -> None:
"""Shift by the median, scale by the interquantile range."""
fitted = {}
for feat in data.fields:
values = _values(data[feat])
low, high = np.quantile(values, percentiles)
fitted[feat] = (float(np.median(values)), float(high - low))
self._record(fitted)
def _standard_fit(self, data: ak.Array) -> None:
"""Shift by the mean, scale by the standard deviation."""
fitted = {}
for feat in data.fields:
values = _values(data[feat])
fitted[feat] = (float(np.mean(values)), float(np.std(values)))
self._record(fitted)
def _robust_axov4_fit(self, data: ak.Array, percentiles: list, scale: list) -> None:
"""Robust, with the quantile range mapped onto the interval ``scale``.
``scale = [2, -2]`` puts the quantile range between -2 and 2 rather than between
0 and 1, which is the convention the axol1tl v4 and v5 trainings were run with.
"""
width = scale[0] - scale[1]
fitted = {}
for feat in data.fields:
low, high = np.quantile(_values(data[feat]), percentiles)
fitted[feat] = (
(low * scale[0] - high * scale[1]) / width,
(high - low) / width,
)
self._record(fitted)
def _record(self, fitted: dict) -> None:
"""Store one object's parameters, guarding the degenerate scale of a flat feature."""
self.norm_params[self.obj_name] = {
feat: {"shift": shift, "scale": scale if scale else 1e-12}
for feat, (shift, scale) in fitted.items()
}
def _values(feature: ak.Array) -> np.ndarray:
"""One feature's real entries, the padding not yet being there to exclude."""
return ak.to_numpy(ak.flatten(feature))
|