Regressor#
A regressor replaces a fit with a trained inverse of the model. It is three objects:
the trainer (
esc.regressor) owns a model stack, simulates curves and fits a network;the network is supplied by the caller and only sees arrays;
the surrogate is what
train()returns. It stores the fitted network, the preprocessing and the parameter bounds, and it is what you save and apply to measured curves.
A surrogate does not minimise a cost and it does not report how well the parameters describe one measurement. It is valid inside the parameter ranges it was trained on. The usual workflow is to take its prediction as a starting point and refine it with an ordinary fit.
The worked examples are four notebooks in notebooks/repository/core.
regressor_mlp_1d.ipynb and regressor_mlp_2d.ipynb use a fully
connected network, on a two-layer film with absorption and on a hollow prism.
regressor_surrogate_1d.ipynb and regressor_surrogate_2d.ipynb use
SurrogateNet("auto") with a prior box on every sample, for the same two
models.
What the network predicts#
A parameter is predicted only when it is free and marked trained=True.
Fixed parameters and parameters without that mark stay at their current
values. The coordinates of the data object are the grid the network uses;
a curve you predict on has to lie on the same grid.
userlim of each trained parameter is the box the trainer samples from,
and therefore the range in which the surrogate is valid.
import escape as esc
from escape.utils.regressor import LogScaler
from escape.utils.regressor.torch import TorchEncoderHead
thkn = esc.par("Thkn", 20, units="nm", userlim=[15, 25], trained=True)
rough = esc.par("Roughness", 1.5, units="nm", userlim=[1.0, 2.0], trained=True)
background = esc.par("Background", 0, scale=1e-6, userlim=[0, 10])
Build the model stack the same way as for a fit, then create the trainer:
reg = esc.regressor(stack, nsamples=20000, ntests=1000)
reg.seed = 1
reg.noise_model = "poisson"
reg.noise_counts = 1e8
reg.set_input_chain([LogScaler(apply_to_features=True, base=10)])
reg.set_nn_model(
esc.nn_model(TorchEncoderHead(encoder="cnn", epochs=50, batch_size=128, seed=1))
)
nsamples is the number of simulated training curves and ntests the
number held out for the score. noise_model is "gaussian" (relative
error noise_level), "poisson" (noise_counts counts per unit
intensity), "lognormal" or "none". The training curves should carry
the same noise as the measurements.
LogScaler is applied to the input curves. Targets are scaled separately:
each trained parameter is mapped to [0, 1] over the box it was drawn
from, and the surrogate maps the network output back to physical units.
TorchEncoderHead is a convolutional encoder followed by a fully connected
head. GrecoMLP is the fully connected network of Greco et al. (2019).
MunteanuNet is the CNN and residual network of Munteanu et al.,
J. Appl. Cryst. 57 (2024) 456. Any of them is passed through esc.nn_model.
Device#
The device belongs to the network.
import torch
reg.network.device = "cuda" if torch.cuda.is_available() else "cpu"
"cpu" is the default. Asking for "cuda" when no GPU is visible raises
ValueError at construction. A saved surrogate does not store the device:
load restores the weights onto the device you pass, "cpu" by default.
Training#
surrogate = reg.train()
print(f"score: {surrogate.score:.3f}")
print(list(surrogate.parameter_names))
train() prints what it is doing: the curve counts, simulation progress on
a long run, the epoch and batch, the batch loss and the learning rate, then
the test score. The score is the mean coefficient of determination of the
predicted parameters on the test set. 1 is exact, 0 is no better than
predicting the mean. It is a check on the surrogate, not a goodness of fit of
a measurement.
train(reset_data=False) refits the network on the curves already
generated.
Large training sets#
When the training matrices would exceed the memory budget, train() writes
them to reg.train_data_file and fits one batch at a time. The test curves
stay in memory. Importing ESCAPE records the currently available RAM in
ESCAPE_TRAIN_MEMORY_BYTES; a C++ run that does not set that variable uses
an 8 GiB ceiling. Set the path before training:
reg.train_data_file = "surrogates/train.estd"
A chain that is fitted on the whole training set cannot be streamed. That
includes MinMaxScaler and LogScaler(apply_to_features=True) unless
plain=True. Noise transforms and LogAffineScaler do not need the
whole set. generate_train_data(path) writes the file without training;
load_train_data(path) reads it back, and a file above the memory budget
stays on disk. x_train is not available in that case.
Prediction#
apply matches parameters by name. With a stack it writes the values into
that stack; without one it returns the list.
surrogate.apply(data, stack=stack)
values = surrogate.apply(data)
The coordinates must match the grid stored in the surrogate.
Saving and loading#
surrogate.save("surrogates/ni_si_ni", nsamples=reg.nsamples)
loaded = esc.surrogate_obj.load("surrogates/ni_si_ni", device="cpu")
The directory contains three files:
<name>.nnblob– the network weights, without pickle;<name>.stack– the model stack the surrogate was trained on;<name>.json– parameter names and bounds, the preprocessing chains, the reference coordinates, the score, the training settings and the ESCAPE version.
A surrogate written by a newer ESCAPE than the one that loads it is refused.
Extra keyword arguments of save are stored in the JSON. loaded.show()
opens the same test widget as a freshly trained surrogate.
Sampled prior#
A prior is the range you already trust for a parameter before looking at the curve. A thickness might be allowed anywhere from 0 to 500 Å, while for one particular sample you already know it lies between 80 and 120 Å. The sampled prior teaches the network to use that extra range, so a later measurement can be predicted inside whatever range you know at the time, without training again.
Fixed mode#
prior_mode is "fixed" unless you change it. Every training curve is
drawn from the full userlim of each trained parameter. The network sees
only the curve. Its job is to return each parameter as a fraction of that one
fixed box: 0 at the lower limit, 1 at the upper limit. Use this when every
curve you will ever predict has the same allowed ranges.
Sampled mode#
prior_mode = "sampled" gives every training curve its own smaller box
inside those full limits. For a thickness whose full range is 0 to 500 Å and
a drawn width of 40 Å, one curve might be told “the thickness is between 90
and 130 Å” and the true value is then picked inside that interval, say 112 Å.
The next curve gets a different interval. The network receives two inputs:
the simulated curve, and the box. The number it must learn is where the truth
sits inside that box, again from 0 at the box’s lower edge to 1 at its
upper edge. In the example, 112 Å inside 90-130 Å is about 0.55.
The curve is the simulation of the truth drawn inside that box, so each training example is one curve tied to one box. The network learns to stay inside the box it was given. That only works if training has already shown it many widths and positions, which is what the random draw does.
At prediction you do not draw a box. You set each trained parameter’s
min and max to the range you believe for that measurement, then call
apply. Those two numbers are handed to the network as the box, the
network’s output is converted back to physical units through that box, and
the result is kept inside the box. Narrowing the limits narrows the answer.
Leaving min and max at the original userlim asks for a prediction
over the full training range.
How wide the boxes are#
prior_width is a pair (smallest, largest) of widths as a fraction of
each parameter’s full range. The default (0.1, 1.0) means a training box
is somewhere between 10% of the range and the whole range. A width of 1 is
the fixed-mode box; a width of 0.1 on a 0-500 Å thickness is a 50 Å window.
reg.prior_mode = "sampled"
reg.prior_width = (0.05, 1.0)
Use set_prior_widths_physical when the parameters do not share a sensible
fraction. A thickness window of a few ångströms and an SLD window of
1e-6 per square ångström are different physical statements. Pass one
(smallest, largest) pair per trained parameter, in parameter_names
order. None or an empty list returns to the shared prior_width.
reg.set_prior_widths_physical([
(0.01, 500.0), # thickness, in the parameter's own units
(0.01, 60.0), # roughness
])
Signed targets#
With a sampled prior the network is learning a position inside a box, and
that position is stored as a number from 0 to 1. signed_output_scaling =
True shows the network the same position mapped onto -1 to 1, by
2y - 1, and converts the network output back before turning it into
physical units. The tables y_train and y_test stay on 0 to 1; only
the values used while fitting and scoring move to -1 to 1. This setting
requires prior_mode = "sampled".
It matters for a network whose last operation cannot produce a negative
number. GrecoMLP ends with a ReLU unless you build it as
GrecoMLP(output_relu=False). A ReLU output cannot represent a target of
-1, so turn the ReLU off when signed scaling is on. MunteanuNet has no
output ReLU and can be used with either scaling.
Learning rate on a single pass#
batch_plateau is not part of the prior. It reduces the learning rate
during a single pass over the curves. The section 4.1 notebook leaves the
rate fixed (lr_patience=0), which is what that ReflectorCH configuration
does. Turn the batch schedule on when a one-pass run should still react to
a plateau:
MunteanuNet(
epochs=1,
batch_plateau=True,
lr_patience=500,
lr_loss_window=50,
)
The fit starts at learning_rate. After every mini-batch the loss of that
batch is recorded. Once lr_patience losses have been seen, the mean of
the latest lr_loss_window of them is compared with the mean of the
window just before. If the recent window is no lower, the learning rate is
multiplied by 0.1 and the record is cleared, so the next decision waits for
lr_patience new batches at the reduced rate. The rate does not fall
below min_lr.
lr_patience = 0 leaves the learning rate constant. With
batch_plateau left off and lr_patience positive, the same network
instead uses a slower rule: the rate is halved, and the decision is made
once per epoch rather than once per batch. On a one-epoch run that rule
never gets a second epoch to act.
Sampled parameters and identifiability#
A parameter is drawn while curves are generated when it is not fixed and it
is marked trained, or when it is marked sampled and not trained.
A trained parameter is drawn whether or not sampled is set, and it is
predicted. A parameter that is sampled and not trained is a nuisance, such as
a resolution width or a background: it is randomized, and the network does
not predict it. Every other parameter keeps its current value.
reg.identifiability() runs a Fisher-information analysis with the
training noise model and reports parameters the curves cannot constrain.
reg.fix_unidentifiable_parameters() fixes them. Gaussian noise of level
0 is analysed as no noise, and the Cramer–Rao bounds are then undefined.
De-duplication#
Uniform boxes do not produce uniformly different curves. A thickness that barely moves the fringe pattern, or two parameter sets that compensate each other, can yield almost the same intensities. Repeating that curve wastes the fit. Repeating it with two different truths is worse: the network is asked to give two answers to one input.
set_dedup(tolerance, parameter_tolerance, policy) runs after the clean
curves are simulated and before noise is added. A tolerance of 0 leaves
every curve in the set. The comparison needs the whole training set in
memory, so a run that streams to disk does not deduplicate.
Two curves are close when the root-mean-square difference of their natural
logarithms is below tolerance. For a small change that distance is about
the RMS of ΔI / I, so 0.01 is roughly a one-percent difference. Two
parameter sets are close when
every trained parameter, scaled to its full userlim, differs by at most
parameter_tolerance (default 0.05). One parameter outside that gap
makes the pair distant.
Each close pair is then handled by the policy:
Curves |
Parameters |
|
|
|
|---|---|---|---|---|
close |
close |
drop the later copy |
drop the later copy |
drop the later copy |
close |
far |
keep both |
drop both |
drop the later copy |
not close |
either |
keep both |
keep both |
keep both |
thin is the default. It deletes only the repeated copies, the pairs that
carry no new parameters. Close curves with distant parameters stay in the
set, so the ambiguity is still visible while training. dedup_ambiguous_train
counts rows that were actually removed as ambiguous, so under thin that
count stays zero.
drop_ambiguous does the same thinning and then deletes both members of
every close-but-conflicting pair. Use it when those regions should not be in
the training distribution. The score is then computed without them, so it
describes the reduced set. The underlying inverse problem in the deleted
regions is unchanged.
keep_one keeps a single curve from every close pair and throws the other
away even when the parameters disagree. The surviving row supplies the
target. That hides the fact that another parameter set produced the same
curve.
dedup_removed_train is how many training rows were discarded. The rows
kept plus the rows removed equal the number you requested. The test set is
filtered with the same rule, and its counts are dedup_removed_test and
dedup_ambiguous_test.
reg.set_dedup(0.02, 0.05, "thin")
loss_reweighting = True weights each target by the inverse of its
variance. With uniform draws on [0, 1] the weights are nearly equal; they
matter after de-duplication and in the sampled prior.