Skip to main content

Transforms

Batch transforms for spectral DataLoaders
import torch, numpy as np
from soilspectfm.preprocessing import SNV

SNV (standard normal variate) centers each spectrum on its own mean and divides it by its own standard deviation across wavenumbers. BatchSNV applies SNV as a fastai batch transform, on the device that holds the batch. It uses no fitted statistics. The result for a spectrum depends only on that spectrum, whatever the batch or the train/test split.

A CNN’s default weight initialization, and fastai’s ActivationStats diagnostics, assume inputs of roughly unit scale. BatchSNV also restores that scale after preprocessing for classical models. For example, SNV followed by a Savitzky-Golay derivative leaves spectra with very small values, because the derivative shrinks the unit variance that SNV gives. That scale suits PLSR or a random forest, but not a CNN.


source

BatchSNV

def BatchSNV(
    eps:float=1e-06
):

Center and scale each spectrum by its own mean and standard deviation (SNV)

Spectra with a standard deviation of 0.02 come out with a mean of 0 and a standard deviation of 1:

x = TensorSpectrum(torch.randn(32, 1, 657) * 0.02)
out = BatchSNV()(x)
assert out.mean(-1).abs().max() < 1e-5
assert (out.std(-1, unbiased=False) - 1).abs().max() < 1e-3
float(out.mean(-1).abs().max()), float(out.std(-1, unbiased=False).min()), float(out.std(-1, unbiased=False).max())
(2.1773386649215354e-08, 0.9999467134475708, 0.9999530911445618)

BatchSNV divides by the population standard deviation, as NumPy’s np.std does. It gives the same result as SNV from soilspectfm, which applies SNV to NumPy arrays. The remaining difference comes from eps, which is 1e-6 here and 1e-10 in soilspectfm:

expected = SNV().fit_transform(x.squeeze(1).numpy().astype(float))
test_close(out.squeeze(1).numpy(), expected, eps=1e-3)
np.abs(out.squeeze(1).numpy() - expected).max()
np.float64(0.00018637861981440906)