Skip to contents

The main user-facing function for training. Given prepared training and (optionally) validation data, it builds the model, creates physics residual sets, runs the training loop with early stopping, and returns a fitted object for prediction and evaluation.

Usage

fit_swrc(
  train_df,
  x_inputs,
  val_df = NULL,
  hidden = c(128L, 64L),
  dropout = 0.1,
  lr = 0.001,
  epochs = 80L,
  batch_size = 256L,
  patience = 5L,
  K = 64L,
  monotone = TRUE,
  lambdas = norouzi_lambdas("norouzi"),
  S1 = 1500L,
  S2 = 500L,
  S3 = 500L,
  S4 = 1500L,
  pF_lin_min = 5,
  pF_lin_max = 7.6,
  pF0_pos = 6.2,
  pF1_neg = 7.6,
  pF_sat_min = -2,
  pF_sat_max = -0.3,
  s3_form = c("inequality", "equality"),
  wet_split_cm = 4.2,
  w_wet = 1,
  w_dry = 1,
  pf_left = -2,
  pf_right = 7.6,
  seed = 123L,
  verbose = TRUE
)

Arguments

train_df

Data frame for training (output of prepare_swrc_data()).

x_inputs

Character vector of covariate column names.

val_df

Optional validation data frame (same structure as train_df). If NULL, early stopping is skipped.

hidden

Integer vector of length 2: Conv1D filter counts (default c(128L, 64L)).

dropout

Dropout rate (default 0.10).

lr

Learning rate for the Adam optimizer (default 1e-3).

epochs

Maximum number of epochs (default 80).

batch_size

Mini-batch size (default 256).

patience

Early-stopping patience in multiples of 5 epochs (default 5).

K

Number of knot points (default 64L).

monotone

Logical scalar. Passed to build_swrc_model(). TRUE (default) uses the monotone integral head, which guarantees \(\partial \theta / \partial pF \le 0\); FALSE fits the same backbone with a free output head, as an ablation control. It is not a modelling recommendation, and predict_theta_s() refuses to run on a model fitted with FALSE, because \(\theta_s\) is then not identified.

lambdas

Named list of loss weights; use norouzi_lambdas() to generate (default: norouzi_lambdas("norouzi")).

S1, S2, S3, S4

Residual set sizes (defaults: 1500, 500, 500, 1500).

pF_lin_min

Lower pF for S1 linearity constraint (default 5.0).

pF_lin_max

Upper pF for S1 linearity constraint (default 7.6).

pF0_pos

pF threshold for S2 (default 6.2).

pF1_neg

pF threshold for S3 (default 7.6).

pF_sat_min

Lower pF for S4 (default -2.0).

pF_sat_max

Upper pF for S4 (default -0.3).

s3_form

Form of the S3 dry-end residual, "inequality" (default, reproducing Norouzi et al. 2025) or "equality", which pins theta(pF1) at zero instead of merely bounding it above. See compute_physics_loss() for why the two differ in their consequences.

wet_split_cm

Matric head (cm) separating wet/dry end (default 4.2).

w_wet

Per-observation sample weight for wet observations (default 1.0). Note that this is a second wet/dry weighting: it is applied to each observation inside the data loss, which lambdas already weights by term through lambda_wet and lambda_dry. Both split the data at the same wet_split_cm, so the two multiply. Leaving these at 1.0 and changing lambdas is the published behaviour; setting w_dry = 10 on top of lambda_dry = 10 weights the dry end a hundredfold, not tenfold.

w_dry

Per-observation sample weight for dry observations (default 1.0). See w_wet.

pf_left

Left pF domain boundary (default -2.0).

pf_right

Right pF domain boundary (default 7.6).

seed

Random seed (default 123).

verbose

Logical; print progress (default TRUE).

Value

An S3 object of class swrc_fit, a named list containing:

theta_model

The fitted Keras model.

param_model

The theta_s extractor model.

monotone

Whether the monotone integral head was used.

hidden,dropout

Architecture settings, kept so that save_swrc_model() can rebuild the identical graph.

x_inputs

Covariate names used.

scaler

Fitted min-max scaler.

K

Number of knot points.

dk

Knot spacing.

knot_grid

Knot positions in [0, 1].

pf_left,pf_right

pF domain boundaries.

theta_factor

Unit multiplier for theta.

best_epoch

Epoch at which validation loss was minimised.

lambdas

Loss weights used during training.

history

Data frame of per-epoch training/validation losses.

Examples

# \donttest{
if (reticulate::py_module_available("tensorflow")) {
  # Deliberately small and fast: 20 pedons, K = 16, 50 collocation
  # points per residual set, 2 epochs. These settings demonstrate the
  # interface and fit nothing worth using; the vignette has a realistic
  # configuration.
  d  <- prepare_swrc_data(swrc_example, depth_col = "depth")
  d  <- d[d$PEDON_ID %in% utils::head(unique(d$PEDON_ID), 20L), ]
  x  <- c("clay", "silt", "bd_gcm3", "soc", "Depth_num")
  SM <- list(K = 16L, S1 = 50L, S2 = 50L, S3 = 50L, S4 = 50L,
             epochs = 2L, verbose = FALSE)

  # Published configuration: monotone head, inequality S3.
  fit <- do.call(fit_swrc, c(list(train_df = d, x_inputs = x), SM))
  fit

  # S3 as an equality instead. The published inequality is satisfied by
  # any non-positive value, so under a decreasing curve it drives the
  # whole dry end below zero and collides with S2; the equality pins
  # theta(pF 7.6) at zero and removes that conflict.
  eq <- do.call(fit_swrc,
                c(list(train_df = d, x_inputs = x,
                       s3_form = "equality"), SM))

  # Ablation control: same backbone, free output head. Use it to measure
  # what the monotone architecture contributes; it is not a modelling
  # recommendation, and theta_s is not identified in such a fit.
  free <- do.call(fit_swrc,
                  c(list(train_df = d, x_inputs = x,
                         monotone = FALSE), SM))
}
# }