Skip to main content

Transfer

Train, cache, apply and adapt spectral models across datasets and instruments
from fastcore.test import *
import tempfile
from fasttransform import Transform
from sklearn.pipeline import make_pipeline
from soilspecdl.datasets import load_toy_kssl
from soilspecdl.models import CutCNN
from soilspecdl.dataloader import get_mask_splitter
from fastai.losses import L1LossFlat

A transfer experiment trains a model on a large spectral library, such as OSSL, then uses it on spectra from another dataset or instrument. It can apply the model as it is, recompute its normalisation statistics on the new spectra, fit a new head on its frozen features, or fine-tune it. The functions here do these steps for any SpectralCNN or CutCNN.

The examples use the toy dataset from soilspecdl.datasets: 500 KSSL MIR spectra. The target is log1p of exchangeable potassium (Kex), and every fifth sample is a test sample:

toy = load_toy_kssl()
X, y, ids = toy.xy('k.ext_usda.a725_cmolc.kg')
y, wns = np.log1p(y.flatten()), toy.wavenumbers
is_test = np.arange(len(X)) % 5 == 0
X.shape, is_test.sum()
((500, 1701), np.int64(100))

Training once


source

load_weights

def load_weights(
    path, # File of the weights, such as the `path` of `train_or_load`
    model_fn:type=SpectralCNN, # Function returning a new model, as in training
)->torch.nn.modules.module.Module: # The model, on the CPU

Load the weights in path into a new model from model_fn


source

train_or_load

def train_or_load(
    path, # File for the weights, such as `models/kex.pth`; the training history goes beside it, as a `.csv` file
    X, # Spectra, one per row
    y, # Targets
    wns, # Wavenumbers of the columns of `X`
    model_fn:type=SpectralCNN, # Function returning a new model
    epochs:int=20, # Number of one-cycle epochs
    lr:float=0.001, # Maximum learning rate
    valid_pct:float=0.1, # Proportion of the samples for validation
    seed:int=42, # Seed for the validation split and the training
    tfm:soilspecdl.transforms.BatchSNV=BatchSNV(enc:1,dec:0), # Transform applied to each batch, or a list of transforms applied in order
    **kwargs
)->torch.nn.modules.module.Module: # The trained model, on the CPU

Train a model from model_fn and save its weights to path, or load the weights if path exists

Pretraining on a large library takes hours, and an experiment reuses the same pretrained model many times. train_or_load trains the model once, with a one-cycle schedule, and saves its weights to path. Later calls with the same path load the weights and skip the training. The function does not check that the arguments match the saved run. A new path is needed for every new setting.

Training also saves the losses and the validation R² of every epoch, in a .csv file beside the weights:

path = Path(tempfile.mkdtemp())/'kex.pth'
model = train_or_load(path, X[~is_test], y[~is_test], wns, epochs=5)
hist = pd.read_csv(path.with_suffix('.csv'), index_col='epoch')
test_eq(len(hist), 5)
hist
train_loss valid_loss r2_score
epoch
0 0.157453 0.101628 -0.044382
1 0.143392 0.081949 0.157855
2 0.132672 0.092736 0.046997
3 0.129656 0.080547 0.172256
4 0.126212 0.073516 0.244508

Other keyword arguments go to spectral_learner, to train with another loss or other metrics. The history has one column per metric:

path_mae = path.with_name('kex_mae.pth')
train_or_load(path_mae, X[~is_test], y[~is_test], wns, epochs=1, loss_func=L1LossFlat(), metrics=[])
test_eq(list(pd.read_csv(path_mae.with_suffix('.csv'), index_col='epoch').columns), ['train_loss', 'valid_loss'])

tfm also takes a list of transforms, applied in order. A transform whose split_idx is 0 runs on training batches only, as an augmentation needs. Jitter adds noise to the training spectra before SNV:

class Jitter(Transform):
    "Add Gaussian noise to each training spectrum"
    split_idx = 0
    def encodes(self, x:TensorSpectrum): return x + 0.01*torch.randn_like(x)

path_aug = path.with_name('kex_jitter.pth')
train_or_load(path_aug, X[~is_test], y[~is_test], wns, epochs=1, tfm=[Jitter(), BatchSNV()])
test_eq(len(pd.read_csv(path_aug.with_suffix('.csv'), index_col='epoch')), 1)

Predicting


source

predict

def predict(
    model, # Trained model
    X, # Spectra, one per row
    wns, # Wavenumbers of the columns of `X`
    bs:int=256, # Batch size
    tfm:soilspecdl.transforms.BatchSNV=BatchSNV(enc:1,dec:0), # Transform applied to each batch, as in training
)->numpy.ndarray: # One prediction per spectrum

Predict X with model

predict needs no DataLoaders. It applies the same batch transform as training, BatchSNV by default, and works on a copy of the model in evaluation mode. A second train_or_load with the same path loads the saved weights, and gives the same predictions:

p = predict(model, X[is_test], wns)
test_close(predict(train_or_load(path, X[~is_test], y[~is_test], wns), X[is_test], wns), p)
p.shape
(100,)

To load a saved model without its training data, use load_weights. If path is missing, it raises FileNotFoundError and does not train a new model:

test_close(predict(load_weights(path), X[is_test], wns), p)
test_fail(lambda: load_weights(path.with_name('missing.pth')), exc=FileNotFoundError)

Scores


source

regression_scores

def regression_scores(
    y, # Observed targets
    p, # Predicted targets
    inv:NoneType=None, # Inverse of the target transform, such as `np.expm1`, for RMSE and bias on the property's own scale
)->dict: # R², correlation `r` and concordance `CCC` of the targets; RMSE and bias of the property

R², correlation, Lin’s concordance correlation coefficient, RMSE and bias of predictions

Lin’s concordance correlation coefficient (CCC) measures agreement with the 1:1 line. Unlike r, it drops when predictions are biased or on the wrong scale. Safanelli et al. (2023) used it as their main metric for the soil spectroscopy ring trial. Models that predict a transformed target, such as log1p of a property, are often judged on the property itself. With inv, RMSE and bias are computed after the inverse transform, in the property’s own units. R², r and CCC stay on the transformed scale:

scores = regression_scores(y[is_test], p, inv=np.expm1)
test_close(regression_scores(y, y)['CCC'], 1)
scores
{'R²': 0.22418335926025057,
 'r': 0.6029749923404765,
 'CCC': 0.4288575795203078,
 'RMSE': 0.5868559092121325,
 'bias': 0.10391348495597841}

Frozen features


source

features

def features(
    model, # Model with a `backbone`, such as a `SpectralCNN` or a `CutCNN`
    X, # Spectra, one per row
    wns, # Wavenumbers of the columns of `X`
    bs:int=256, # Batch size
    tfm:soilspecdl.transforms.BatchSNV=BatchSNV(enc:1,dec:0), # Transform applied to each batch, as in training
)->numpy.ndarray: # One row of features per spectrum

The outputs of the backbone of model for the spectra X, which are the inputs of its head

The backbone of a SpectralCNN gives one value per channel of its last block. A CutCNN cut after four blocks gives the 128 channels of block 4:

cut = CutCNN(model, len(wns))
test_eq(features(model, X[:10], wns).shape, (10, 256))
features(cut, X[:10], wns).shape
(10, 128)
/opt/hostedtoolcache/Python/3.12.15/x64/lib/python3.12/site-packages/fastcore/docments.py:488: UserWarning: docments unavailable for ridge_head: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
  warnings.warn(f'docments unavailable for {self.nm}: {type(e).__name__}: {e}')

source

ridge_head

ridge_head(model, X, y, wns, alphas=array([1.00000000e-01, 3.16227766e-01, 1.00000000e+00, 3.16227766e+00,
       1.00000000e+01, 3.16227766e+01, 1.00000000e+02, 3.16227766e+02,
       1.00000000e+03, 3.16227766e+03, 1.00000000e+04, 3.16227766e+04,
       1.00000000e+05, 3.16227766e+05, 1.00000000e+06]), tfm=BatchSNV(enc:1,dec:0)) -> torch.nn.modules.module.Module

Copy of model whose head holds a ridge regression of y on the features of X

With few target samples, a ridge regression on frozen features can beat fine-tuning. ridge_head standardises the features, fits RidgeCV, and folds the scaling into the weights of the head’s last Linear layer. The result is an ordinary model: predict, spectral_learner and fine-tuning work on it. Its predictions match a scikit-learn pipeline fitted on the same features:

rh = ridge_head(cut, X[~is_test], y[~is_test], wns)
F = features(cut, X[~is_test], wns)
pipe = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-1, 6, 15))).fit(F, y[~is_test])
test_close(predict(rh, X[~is_test], wns), pipe.predict(F), eps=1e-4)
regression_scores(y[is_test], predict(rh, X[is_test], wns), inv=np.expm1)
{'R²': 0.415871848976444,
 'r': 0.6712359540465389,
 'CCC': 0.5915279429029128,
 'RMSE': 0.5306872989165431,
 'bias': 0.027256447220993064}

Adapting to new spectra


source

test_preds

def test_preds(
    learn, # `Learner` whose `dls` comes from `get_spectral_dls`
)->numpy.ndarray: # One prediction per test sample

Predict the test samples learn.dls.test_idx


source

adabn

def adabn(
    model, # Trained model
    dls, # `DataLoaders` of the new spectra
)->torch.nn.modules.module.Module: # Copy of `model`, in evaluation mode

Copy of model whose BatchNorm running statistics are recomputed from the training and validation spectra of dls

Spectra from another instrument shift the activations inside the network. BatchNorm layers normalise with running means and variances learned during training, which then no longer fit, and each layer receives off-centre inputs. AdaBN (Li et al., 2016) resets the statistics and recomputes them from the new spectra. adabn runs the training and validation spectra of dls through a copy of the model, with BatchNorm in training mode and momentum=None. Each running statistic becomes the average of the per-batch statistics, with every batch weighted equally. adabn changes no weights, uses no targets, and leaves the test spectra out. Afterwards, the running mean of the first BatchNorm layer is the average over batches of the mean output of the first convolution:

dls, _ = get_spectral_dls(X, y, wns, splitter=get_mask_splitter(is_test), batch_tfms=[BatchSNV()])
ada = adabn(model, dls)
conv, bn = ada.backbone.layers[0].conv[0], ada.backbone.layers[0].conv[1]
with torch.no_grad(): outs = [conv(xb) for dl in (dls.train.new(shuffle=False, drop_last=False), dls.valid) for xb, _ in dl]
test_close(bn.running_mean.cpu().numpy(), torch.stack([o.mean(dim=(0, 2)) for o in outs]).mean(0).cpu().numpy(), eps=1e-6)
{'R²': 0.33156271998704046,
 'r': 0.5971741783023902,
 'CCC': 0.47963940503303787,
 'RMSE': 0.5793957682479973,
 'bias': -0.00779515136514901}

test_preds predicts the test samples of the DataLoaders that a Learner uses. Here the new spectra come from the same instrument as the training spectra, so AdaBN changes the predictions only a little:

p_ada = test_preds(spectral_learner(dls, ada))
regression_scores(y[is_test], p_ada, inv=np.expm1)