Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions gluon_utils/scalers/robust_scaler.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
class RobustScaler(Scaler):
"""
Computes a scaling factor by removing the median and scaling by the
interquartile range (IQR).
interquartile range (IQR) or, if IQR is 0, by the full range.

Parameters
----------
Expand Down Expand Up @@ -61,9 +61,18 @@ def __call__(
q3 = torch.nanquantile(observed_data, 0.75, dim=self.dim, keepdim=True)
iqr = q3 - q1

# Compute full range as a fallback if IQR is 0
data_min = torch.nanquantile(observed_data, 0, dim=self.dim, keepdim=True)
data_max = torch.nanquantile(observed_data, 1, dim=self.dim, keepdim=True)
full_range = data_max - data_min

# if observed data is all zeros, nanmedian returns nan
loc = torch.where(torch.isnan(med), torch.zeros_like(med), med)
scale = torch.where(torch.isnan(iqr), torch.ones_like(iqr), iqr)
scale = torch.where(
torch.isnan(iqr),
torch.ones_like(iqr),
torch.where(iqr == 0, full_range, iqr)
)
scale = torch.maximum(scale, torch.full_like(iqr, self.minimum_scale))

scaled_data = (data - loc) / scale
Expand Down