torch_ecg.utils.normalize_t

torch_ecg.utils.normalize_t(sig: Tensor, method: str = 'z-score', mean: Real | Iterable[Real] = 0.0, std: Real | Iterable[Real] = 1.0, per_channel: bool = False, inplace: bool = True) Tensor

Perform z-score normalization on sig, to make it has fixed mean and standard deviation, or perform min-max normalization on sig, or normalize sig using mean and std via \((sig - mean) / std\). More precisely,

\[\begin{split}\begin{align*} \text{Min-Max normalization:}\quad & \frac{sig - \min(sig)}{\max(sig) - \min(sig)} \\ \text{Naive normalization:}\quad & \frac{sig - m}{s} \\ \text{Z-score normalization:}\quad & \left(\frac{sig - mean(sig)}{std(sig)}\right) \cdot s + m \end{align*}\end{split}\]
Parameters:
  • sig (torch.Tensor) – Signal to be normalized, assumed to have shape (..., n_leads, siglen).

  • method ({"z-score", "min-max", "naive"}, optional) – Normalization method, by default “z-score”, case insensitive.

  • mean (numbers.Real or array_like, default 0.0) – Mean value of the normalized signal, or mean values for each lead of the normalized signal, if method is “z-score”; mean values to be subtracted from the original signal, if method is “naive”. Useless if method is “min-max”.

  • std (numbers.Real or array_like, default 1.0) – Standard deviation of the normalized signal, or standard deviations for each lead of the normalized signal, if method is “z-score”; or std to be divided from the original signal, if method is “naive”. Useless if method is “min-max”.

  • per_channel (bool, default False) – If True, normalization will be done per channel, not strictly required per channel; if False, normalization will be done per sample, strictly required per sample.

  • inplace (bool, default True) – If True, normalization will be done inplace (on sig).

Returns:

sig – The normalized signal

Return type:

torch.Tensor

Note

In cases where normalization is infeasible (std = 0), only the mean value will be shifted

feasible shapes of sig and std, mean are as follows

shape of sig

per_channel

shape of std or mean

(b,l,s)

False

scalar, (b,), (b,1), (b,1,1)

(b,l,s)

True

scalar, (b,), (l,), (b,1), (b,l), (l,1), (1,l), (b,1,1), (b,l,1), (1,l,1,)

(l,s)

False

scalar

(l,s)

True

scalar, (l,), (l,1), (1,l)

scalar includes native scalar or scalar tensor. One can check by

(b, l, s) = 2, 12, 20
for shape in [(b,), (l,), (b,1), (b,l), (l,1), (1,l), (b,1,1), (b,l,1), (1,l,1,)]:
    nm_sig = normalize(torch.randn(b,l,s), per_channel=True, mean=torch.rand(*shape))
for shape in [(b,), (b,1), (b,1,1)]:
    nm_sig = normalize(torch.randn(b,l,s), per_channel=False, mean=torch.rand(*shape))
for shape in [(l,), (l,1), (1,l)]:
    nm_sig = normalize(torch.randn(l,s), per_channel=True, mean=torch.rand(*shape))