Sequence Hybrid Models (LSTM & Transformer)
This tutorial demonstrates how to use EasyHybrid to train a hybrid model with sequence neural networks (LSTMs and Transformers) on synthetic data for respiration modeling with Q10 temperature sensitivity. The code for this tutorial can be found in docs/literate/tutorials => example_synthetic_sequence.jl.
1. Load Packages
using EasyHybrid
using AxisKeys
using DimensionalData
using CairoMakie2. Data Loading and Preprocessing
Load synthetic dataset from GitHub - it's tabular data
df = load_timeseries_netcdf("https://github.com/bask0/q10hybrid/raw/master/data/Synthetic4BookChap.nc");Each row becomes one window, and the three trainings below run on all of them.
df = df[1:2000, :];
first(df, 5);3. Define Neural Network Architectures
Define a standard feedforward neural network
NN = Chain(Dense(15, 15, Lux.sigmoid), Dense(15, 15, Lux.sigmoid), Dense(15, 1))Chain(
layer_(1-2) = Dense(15 => 15, σ), # 480 (240 x 2) parameters
layer_3 = Dense(15 => 1), # 16 parameters
) # Total: 496 parameters,
# plus 0 states.Define LSTM-based neural network with memory
TIP
When the Chain ends with a Recurrence layer, EasyHybrid automatically adds a RecurrenceOutputDense layer to handle the sequence output format. The user only needs to define the Recurrence layer itself!
NN_Memory = Chain(
Recurrence(LSTMCell(15 => 15), return_sequence = true),
)Chain(
layer_1 = Recurrence(
cell = LSTMCell(15 => 15), # 1_920 parameters, plus 1 non-trainable
),
) # Total: 1_920 parameters,
# plus 1 states.4. We define the process-based model, a classical Q10 model for respiration
"""
RbQ10(; ta, Q10, rb, tref=15.0f0)
Respiration model with Q10 temperature sensitivity.
- `ta`: air temperature [°C]
- `Q10`: temperature sensitivity factor [-]
- `rb`: basal respiration rate [μmol/m²/s]
- `tref`: reference temperature [°C] (default: 15.0)
"""
function RbQ10(; ta, Q10, rb, tref = 15.0f0)
reco = rb .* Q10 .^ (0.1f0 .* (ta .- tref))
return (; reco, Q10, rb)
end5. Define Model Parameters
Parameter specification: (default, lower_bound, upper_bound)
parameters = (
rb = (3.0f0, 0.0f0, 13.0f0), # Basal respiration [μmol/m²/s]
Q10 = (2.0f0, 1.0f0, 4.0f0), # Temperature sensitivity factor [-]
)(rb = (3.0f0, 0.0f0, 13.0f0), Q10 = (2.0f0, 1.0f0, 4.0f0))6. Configure Hybrid Model Components
Define input variables Forcing variables (temperature)
forcing = [:ta]1-element Vector{Symbol}:
:taPredictor variables (solar radiation, and its derivative)
predictors = [:sw_pot, :dsw_pot]2-element Vector{Symbol}:
:sw_pot
:dsw_potTarget variable (respiration)
target = [:reco]1-element Vector{Symbol}:
:recoParameter classification Global parameters (same for all samples)
global_param_names = [:Q10]1-element Vector{Symbol}:
:Q10Neural network predicted parameters
neural_param_names = [:rb]1-element Vector{Symbol}:
:rb7. Construct LSTM Hybrid Model
Create LSTM hybrid model using the unified constructor
hlstm = constructHybridModel(
predictors,
forcing,
target,
RbQ10,
parameters,
neural_param_names,
global_param_names,
hidden_layers = NN_Memory, # Neural network architecture
scale_nn_outputs = true, # Scale neural network outputs
input_batchnorm = false # Apply batch normalization to inputs
)Hybrid Model (Single NN)
Neural Network:
Chain(
layer_1 = WrappedFunction(identity),
layer_2 = Dense(2 => 15, tanh), # 45 parameters
layer_3 = Recurrence(
cell = LSTMCell(15 => 15), # 1_920 parameters, plus 1 non-trainable
),
layer_4 = RecurrenceOutputDense(
layer = Dense(15 => 15, tanh), # 240 parameters
),
layer_5 = Dense(15 => 1), # 16 parameters
) # Total: 2_221 parameters,
# plus 1 states.
Configuration:
predictors = [:sw_pot, :dsw_pot]
forcing = [:ta]
targets = [:reco]
mechanistic_model = RbQ10
neural_param_names = [:rb]
global_param_names = [:Q10]
fixed_param_names = Symbol[]
scale_nn_outputs = true
start_from_default = true
config = (; hidden_layers = Chain{@NamedTuple{layer_1::Recurrence{Static.True, LSTMCell{Static.False, Static.False, Int64, Int64, NTuple{4, Nothing}, NTuple{4, Nothing}, NTuple{4, Nothing}, typeof(WeightInitializers.zeros32), typeof(WeightInitializers.zeros32), Static.True}, Lux.BatchLastIndex}}, Nothing}((layer_1 = Recurrence{Static.True, LSTMCell{Static.False, Static.False, Int64, Int64, NTuple{4, Nothing}, NTuple{4, Nothing}, NTuple{4, Nothing}, typeof(WeightInitializers.zeros32), typeof(WeightInitializers.zeros32), Static.True}, Lux.BatchLastIndex}(LSTMCell(15 => 15), Lux.BatchLastIndex(), static(true), false, false),), nothing), activation = tanh, scale_nn_outputs = true, input_batchnorm = false, start_from_default = true,)
Parameters:
┌─────┬────────┬───────┬───────┬────────┐
│ │ value │ lower │ upper │ scale │
├─────┼────────┼───────┼───────┼────────┤
│ rb │ NN │ 0.0 │ 13.0 │ linear │
│ Q10 │ Global │ 1.0 │ 4.0 │ linear │
└─────┴────────┴───────┴───────┴────────┘
value: number = fixed; NN/Global = estimated; Forcing = overridden by forcing data8. Data Preparation Steps (Demonstration)
The following steps demonstrate what happens under the hood during training. In practice, you can skip to Section 9 and use the train function directly.
:KeyedArray and :DimArray are supported
pref_array_type = :DimArray
x, y = prepare_data(hlstm, df, array_type = pref_array_type);Convert a (single) time series into many training samples by windowing.
Each sample consists of:
input_window: number of past steps given to the model (sequence length)output_window: number of steps to predictoutput_shift: stride between consecutive windows (controls overlap)lead_time: prediction lead (e.g. lead_time=1 predicts starting 1 step ahead)
This supports many-to-one / many-to-many forecasting depending on output_window. Creates an array of shape (variable, time, batch_size) with variable being feature, time the input window, andbatch_size1:n samples (= full batch)
output_shift = 1
output_window = 1
input_window = 10
(xs, forcings_s), ys = split_into_sequences(x, y; input_window = input_window, output_window = output_window, output_shift = output_shift, lead_time = 0);First input_window/sample
xs[:, :, 1]┌ 2×10 DimArray{Float32, 2} ┐
├───────────────────────────┴─────────────────────────────────────── dims ┐
↓ variable Categorical{Symbol} [:sw_pot, :dsw_pot] Unordered,
→ time Categorical{Symbol} [:x9_to_x9, …, :x9_to_x0_y0] ReverseOrdered
└─────────────────────────────────────────────────────────────────────────┘
↓ → :x9_to_x9 :x9_to_x8 … :x9_to_x1 :x9_to_x0_y0
:sw_pot 109.817 109.817 109.817 109.817
:dsw_pot 115.595 115.595 115.595 115.595Second input_window/sample
xs[:, :, 2]┌ 2×10 DimArray{Float32, 2} ┐
├───────────────────────────┴─────────────────────────────────────── dims ┐
↓ variable Categorical{Symbol} [:sw_pot, :dsw_pot] Unordered,
→ time Categorical{Symbol} [:x9_to_x9, …, :x9_to_x0_y0] ReverseOrdered
└─────────────────────────────────────────────────────────────────────────┘
↓ → :x9_to_x9 :x9_to_x8 … :x9_to_x1 :x9_to_x0_y0
:sw_pot 109.817 109.817 109.817 109.817
:dsw_pot 115.595 115.595 115.595 115.595test of shift
xs[:, output_shift + 1, 1] == xs[:, 1, 2]trueFirst output_window/sample with time label like :x30_to_x5_y4 which indicates an accumulation of memory from x30 to x5 for the prediction of y4
ys.reco┌ 1×1991 DimArray{Float32, 2} ┐
├─────────────────────────────┴─────────────────────────────────────── dims ┐
↓ time Categorical{Symbol} [:x9_to_x0_y0] ForwardOrdered,
→ batch_size Sampled{Int64} [1, …, 1991] ForwardOrdered Irregular Points
└───────────────────────────────────────────────────────────────────────────┘
↓ → 1 2 3 … 1990 1991
:x9_to_x0_y0 0.806911 0.803646 0.794573 0.124091 0.124738Second output_window/sample
ys.reco[:, 2]
forcings_s.ta10×1991 Matrix{Float32}:
2.1 1.98 1.89 2.06 2.09 1.75 1.51 … -8.77 -10.21 -9.89 -9.26
1.98 1.89 2.06 2.09 1.75 1.51 1.36 -10.21 -9.89 -9.26 -8.64
1.89 2.06 2.09 1.75 1.51 1.36 1.11 -9.89 -9.26 -8.64 -7.74
2.06 2.09 1.75 1.51 1.36 1.11 0.97 -9.26 -8.64 -7.74 -6.87
2.09 1.75 1.51 1.36 1.11 0.97 0.87 -8.64 -7.74 -6.87 -6.19
1.75 1.51 1.36 1.11 0.97 0.87 0.59 … -7.74 -6.87 -6.19 -5.45
1.51 1.36 1.11 0.97 0.87 0.59 0.23 -6.87 -6.19 -5.45 -4.67
1.36 1.11 0.97 0.87 0.59 0.23 0.06 -6.19 -5.45 -4.67 -4.92
1.11 0.97 0.87 0.59 0.23 0.06 -0.23 -5.45 -4.67 -4.92 -5.12
0.97 0.87 0.59 0.23 0.06 -0.23 -0.23 -4.67 -4.92 -5.12 -5.08Any of the first output_window the same as the second output_window? ideally not big overlap
overlap = output_window - output_shift
overlap_length = sum(in(ys.reco[:, 1]), ys.reco[:, 2])0Split the (windowed) dataset into train/validation in the same way as train does.
sdf = split_data(df, hlstm, sequence_kwargs = (; input_window = input_window, output_window = output_window, output_shift = output_shift, lead_time = 0), array_type = pref_array_type);
((x_train, f_train), y_train), ((x_val, f_val), y_val) = sdf;
x_train
y_train
f_train
y_train_nan = map(v -> .!isnan.(v), y_train)(reco = Bool[1 1 … 1 1],)Wrap the training windows/samples in a DataLoader to form batches.
WARNING
batchsize is the number of windows/samples used per gradient step to update the parameters. Processing 32 windows in one array is usually much faster than doing 32 separate forward/backward passes with batch_size=1.
train_dl = EasyHybrid.DataLoader(((x_train, f_train), y_train); batchsize = 32);Run hybrid model forwards
(x_first, forcings_first), y_first = first(train_dl)
ps, st = Lux.setup(Random.default_rng(), hlstm);
xf = (x_first, forcings_first)
frun = hlstm(xf, ps, st);┌ Warning: `replicate` doesn't work for `TaskLocalRNG`. Returning the same `TaskLocalRNG`.
└ @ LuxCore ~/.julia/packages/LuxCore/ev567/src/LuxCore.jl:18
┌ Warning: `replicate` doesn't work for `TaskLocalRNG`. Returning the same `TaskLocalRNG`.
└ @ LuxCore ~/.julia/packages/LuxCore/ev567/src/LuxCore.jl:18Extract predicted yhat
reco_mod = frun[1].reco10×32 Matrix{Float32}:
2.24392 2.22533 2.21149 2.23771 … 3.02609 3.06138 3.00345 2.97682
2.12173 2.10854 2.13353 2.13797 2.99202 2.93534 2.90934 2.73349
2.10903 2.13403 2.13847 2.08866 2.98587 2.95981 2.78104 2.78299
2.14487 2.14934 2.09928 2.06464 2.97796 2.79835 2.80041 2.75043
2.15377 2.1036 2.0689 2.0475 2.80289 2.80526 2.75529 2.67259
2.10484 2.07011 2.0487 2.0135 … 2.79974 2.75016 2.6677 2.61106
2.07022 2.0488 2.01361 1.99416 2.7388 2.65691 2.60056 2.62416
2.04836 2.01317 1.99373 1.97996 2.64486 2.5889 2.61243 2.56759
2.01254 1.9931 1.97933 1.94129 2.57984 2.60335 2.55868 2.61609
1.99243 1.97867 1.94063 1.89281 2.59787 2.55333 2.61062 2.60882Bring observations in same shape
reco_obs = y_first.reco
reco_nan = .!isnan.(reco_obs);Compute loss
EasyHybrid.compute_loss(hlstm, ps, st, ((x_train, f_train), (y_train, y_train_nan)), logging = LoggingLoss(train_mode = true))(2.2506366f0, (st_nn = (layer_1 = NamedTuple(), layer_2 = NamedTuple(), layer_3 = (rng = TaskLocalRNG(),), layer_4 = NamedTuple(), layer_5 = NamedTuple()), fixed = NamedTuple()), NamedTuple())9. Train LSTM Hybrid Model
out_lstm = train(
hlstm,
df;
nepochs = 100, # Number of training epochs
patience = 10,
batchsize = 128, # Batch size of training windows/samples
opt = RMSProp(0.01), # Optimizer and learning rate
monitor_names = [:rb, :Q10], # Parameters to monitor during training
yscale = identity, # Scaling for outputs
shuffleobs = true,
training_loss = :nseLoss,
loss_types = [:nseLoss, :nse],
sequence_kwargs = (; input_window = input_window, output_window = output_window, output_shift = output_shift, lead_time = 0),
plotting = true,
show_progress = false,
input_batchnorm = false,
array_type = pref_array_type,
model_name = "RbQ10_synthetic_lstm"
);[ Info: Using split_into_sequences: (input_window = 10, output_window = 1, output_shift = 1, lead_time = 0)
┌ Warning: `replicate` doesn't work for `TaskLocalRNG`. Returning the same `TaskLocalRNG`.
└ @ LuxCore ~/.julia/packages/LuxCore/ev567/src/LuxCore.jl:18
┌ Warning: Early stopping at epoch 14, best validation loss wrt nseLoss: 0.12158501 at epoch 4
└ @ EasyHybrid ~/work/EasyHybrid.jl/EasyHybrid.jl/src/training/early_stopping.jl:39
[ Info: Animation (dashboard) saved to /home/runner/work/EasyHybrid.jl/EasyHybrid.jl/docs/build/training_history_RbQ10_synthetic_lstm.mp4
[ Info: Dashboard (dashboard) saved to /home/runner/work/EasyHybrid.jl/EasyHybrid.jl/docs/build/train_history_RbQ10_synthetic_lstm.png
[ Info: Returning best model from epoch 4 with validation loss: 0.12158501first(out_lstm.val_obs_pred, 5)| Row | reco | reco_pred |
|---|---|---|
| Float32 | Float32 | |
| 1 | 0.803646 | 0.673001 |
| 2 | 0.783059 | 0.643185 |
| 3 | 0.77768 | 0.63549 |
| 4 | 0.872431 | 0.808454 |
| 5 | 0.854878 | 0.785323 |
10. Train Single NN Hybrid Model (Optional)
For comparison, we can also train a hybrid model with a standard feed-forward neural network
hm = constructHybridModel(
predictors,
forcing,
target,
RbQ10,
parameters,
neural_param_names,
global_param_names,
hidden_layers = NN, # Neural network architecture
scale_nn_outputs = true, # Scale neural network outputs
input_batchnorm = false, # Apply batch normalization to inputs
);Train the hybrid model
single_nn_out = train(
hm,
df;
nepochs = 100, # Number of training epochs
patience = 10,
batchsize = 128, # Batch size for training
opt = RMSProp(0.01), # Optimizer and learning rate
monitor_names = [:rb, :Q10], # Parameters to monitor during training
yscale = identity, # Scaling for outputs
shuffleobs = true,
training_loss = :nseLoss,
loss_types = [:nseLoss, :nse],
array_type = :DimArray,
plotting = true,
show_progress = false,
model_name = "RbQ10_synthetic_single_nn"
);┌ Warning: Early stopping at epoch 32, best validation loss wrt nseLoss: 0.023266915 at epoch 22
└ @ EasyHybrid ~/work/EasyHybrid.jl/EasyHybrid.jl/src/training/early_stopping.jl:39
[ Info: Animation (dashboard) saved to /home/runner/work/EasyHybrid.jl/EasyHybrid.jl/docs/build/training_history_RbQ10_synthetic_single_nn.mp4
[ Info: Dashboard (dashboard) saved to /home/runner/work/EasyHybrid.jl/EasyHybrid.jl/docs/build/train_history_RbQ10_synthetic_single_nn.png
[ Info: Returning best model from epoch 22 with validation loss: 0.023266915Close enough
out_lstm.best_loss, single_nn_out.best_loss(0.12158501f0, 0.023266915f0)11. Train Transformer Hybrid Model
using EasyHybrid.TransformersWe can also use the state-of-the-art Transformer models for time-series regression. By wrapping it in a Chain, we bypass the default MLP construction. EasyHybrid's TransformerModel naturally handles (features, seq_len, batch) sequences.
NN_Transformer = Chain(
TransformerModel(
in_features = length(predictors),
d_model = 16,
n_layers = 1,
n_heads = 2,
out_features = length(neural_param_names),
dropout_rate = 0.1f0,
# layer_scale_init = 0.00001f0,
)
)
hm_transformer = constructHybridModel(
predictors,
forcing,
target,
RbQ10,
parameters,
neural_param_names,
global_param_names,
hidden_layers = NN_Transformer, # Pass the Transformer Chain
scale_nn_outputs = true,
input_batchnorm = false,
);Time the same training with the dashboard recorded, and without it. One untimed epoch pays for compilation. Both timed runs use 100 epochs and patience = 10.
function train_transformer(; plotting, save_training, model_name, nepochs = 100)
return train(
hm_transformer,
df;
nepochs,
patience = 10,
batchsize = 128, # Batch size for training
opt = RMSProp(0.005), # Optimizer and learning rate
monitor_names = [:rb, :Q10],
yscale = identity,
shuffleobs = true,
training_loss = :nseLoss,
loss_types = [:nseLoss, :nse],
sequence_kwargs = (; input_window = input_window, output_window = output_window, output_shift = output_shift, lead_time = 0),
array_type = :DimArray,
plotting,
save_training,
show_progress = false,
model_name,
)
end
train_transformer(; plotting = false, save_training = false, model_name = "RbQ10_transformer_warmup_plain", nepochs = 1)
seconds_plain = @elapsed train_transformer(; plotting = false, save_training = false, model_name = "RbQ10_transformer_plain")
train_transformer(; plotting = true, save_training = true, model_name = "RbQ10_transformer_warmup_plot", nepochs = 1)
seconds_plot = @elapsed transformer_out = train_transformer(; plotting = true, save_training = true, model_name = "RbQ10_synthetic_transformer")46.938144339seconds_plain is the time taken to train the transformer model without plotting, and seconds_plot is the time taken to train the transformer model with plotting.
seconds_plain, seconds_plot(39.4461855, 46.938144339)Compare the best validation losses!
out_lstm.best_loss, single_nn_out.best_loss, transformer_out.best_loss(0.12158501f0, 0.023266915f0, 0.108427465f0)