Reference

CounterfactualTraining.AdversarialObjective — Type
(obj::AdversarialObjective)(
    yhat,
    y,
    energy_differential::Vector{<:AbstractFloat}=[0.0f0],
    regularization::Vector{<:AbstractFloat}=[0.0f0],
    adversarial_loss::Union{AbstractFloat,Vector{<:AbstractFloat}}=0.0f0;
    agg=mean,
    kwrgs...,
)

If the adversarial_loss has been computed already, obj::AdversarialObjective can be called directly on predictions yhat and labels y. The different loss components are then added together with a weighting vector lambda.

source
CounterfactualTraining.AdversarialObjective — Type
AdversarialObjective <: AbstractObjective

The AdversarialObjective is a concrete implementation of the AbstractObjective abstract type that optimizes for:

  1. Standard classification objective (the discriminative task).
  2. Adversarial classification objective on the counterfactuals (the explainability task).
source
CounterfactualTraining.EnergyDifferentialObjective — Type
(obj::EnergyDifferentialObjective)(
    yhat,
    y,
    energy_differential::Vector{<:AbstractFloat}=[0.0f0],
    regularization::Vector{<:AbstractFloat}=[0.0f0],
    adversarial_loss::Union{AbstractFloat,Vector{<:AbstractFloat}}=0.0f0;
    agg=mean,
    kwrgs...,
)

If the energy_differential and regularization have been computed already, obj::EnergyDifferentialObjective can be called directly on predictions yhat and labels y. The different loss components are then added together with a weighting vector lambda.

source
CounterfactualTraining.EnergyDifferentialObjective — Type
EnergyDifferentialObjective <: AbstractObjective

The EnergyDifferentialObjective is a concrete implementation of the AbstractObjective abstract type that optimizes for:

  1. Standard classification objective (the discriminative task)
  2. Energy differential between counterfactuals and observed data (the explainability task).
source
CounterfactualTraining.FullObjective — Type
(obj::FullObjective)(
    yhat,
    y,
    energy_differential::Vector{<:AbstractFloat}=[0.0f0],
    regularization::Vector{<:AbstractFloat}=[0.0f0],
    adversarial_loss::Union{AbstractFloat,Vector{<:AbstractFloat}}=[0.0f0];
    agg=mean,
    kwrgs...,
)

If the adversarial_loss has been computed already, obj::FullObjective can be called directly on predictions yhat and labels y. The different loss components are then added together with a weighting vector lambda.

source
CounterfactualTraining.FullObjective — Type
FullObjective <: AbstractObjective

The FullObjective is a concrete implementation of the AbstractObjective abstract type that optimizes for all three tasks:

  1. Standard classification objective (the discriminative task)
  2. Energy differential between counterfactuals and observed data (the explainability task).
  3. Adversarial classification objective on the counterfactuals (the explainability task).
source
CounterfactualTraining.FullObjective — Method
FullObjective(;
    class_loss::Function=Flux.Losses.logitcrossentropy,
    energy_differential::PenaltyOrFun=EnergyDifferential(),
    lambda::Vector{<:AbstractFloat}=[1.0, 0.5, 0.1, 0.25]
)

Outer constructor for the FullObjective type.

source
CounterfactualTraining.VanillaObjective — Type
(obj::VanillaObjective)(
    yhat,
    y,
    energy_differential::Vector{<:AbstractFloat}=[0.0f0],
    regularization::Vector{<:AbstractFloat}=[0.0f0],
    adversarial_loss::Union{AbstractFloat,Vector{<:AbstractFloat}}=0.0f0;
    agg=mean,
    kwrgs...,
)

obj::VanillaObjective can be called directly on predictions yhat and labels y.

source
CounterfactualTraining.VanillaObjective — Type
VanillaObjective <: AbstractObjective

The VanillaObjective is a concrete implementation of the AbstractObjective abstract type that optimizes for:

  1. Standard classification objective (the discriminative task).
source
CounterfactualTraining.VanillaObjective — Method
VanillaObjective(;
    class_loss::Function=Flux.Losses.logitcrossentropy,
    lambda::Vector{<:AbstractFloat}=[1.0],
    needs_ce::Bool=false,
)

Outer constructor for the VanillaObjective type.

source
CounterfactualTraining.accuracy — Method
accuracy(model, train_set)

Compute classification accuracy over a DataLoader. Uses Flux.onecold on whole matrices — GPU-compatible and faster than per-column argmax.

source
CounterfactualTraining.generate! — Method
generate!(
    model,
    data,
    generator::AbstractGenerator;
    nsamples::Union{Int,Nothing}=nothing,
    convergence=Convergence.MaxIterConvergence(),
    parallelizer=nothing,
    input_encoder=nothing,
    verbose=1,
    domain=nothing,
)

This function generates counterfactual explanations for the whole dataset data or a subset thereof (nsamples). It is supposed to be used outside of the mini-batch training loop.

source
CounterfactualTraining.implausibility — Method
implausibility(model, counterfactual, samples, targets)

Compute the implausibility (contrastive divergence) of the counterfactuals (counterfactual) with respect to samples in the target class. This is computed as the difference between negative logits indexed at the target class for the samples and the counterfactual.

source
CounterfactualTraining.protect_immutable! — Method
protect_immutable!(
    samples::AbstractArray,
    counterfactuals::AbstractArray,
    mutability::Union{Nothing,AbstractArray},
)

Protects immutable features from the contrastive divergence penalty.

source
CounterfactualTraining.unwrap — Method
unwrap(train_set; labels=nothing)

Unwraps the data from a Flux.DataLoader or zip iterator. The output variables is assumed to be categorical. If no labels are provided, then 1 to n is used where n is the number of classes.

source
CounterfactualTraining.Native.NativeGenerator — Type
NativeGenerator

Lightweight generator for batched counterfactual search. Holds only the fields needed by generate_counterfactuals!: penalty weights λ and a Flux optimiser opt.

This avoids the Flux 0.16 incompatibility in CE.jl's GradientBasedGenerator (whose opt field is typed against the old Flux.Optimise.AbstractOptimiser).

Keyword fields

  • λ::Vector{Float32} — penalty weights [λ₁, λ₂] for the L1 distance penalty and the energy constraint (default [0.1f0, 1.0f0]).
  • opt — a Flux optimiser (default Flux.Descent(0.1f0)).
source
CounterfactualTraining.Native.batched_energy — Method
batched_energy(model, X′::AbstractMatrix, target_idx::AbstractVector)

Returns a length-N vector of negative logits at the target class for each sample in X′. Uses CartesianIndex for GPU compatibility.

source
CounterfactualTraining.Native.check_batched_convergence — Method
check_batched_convergence(probs, target_idx, iter, maxiter, threshold)

Returns a BitVector of length N indicating which samples have converged. Convergence is reached when the target-class probability ≥ threshold or iter ≥ maxiter.

source
CounterfactualTraining.Native.find_neighbours — Method
find_neighbours(X, y, targets, y_levels; rng=Random.default_rng())

For each counterfactual with target targets[i], samples a random training point that has label targets[i]. Returns a D×N matrix (one neighbour per counterfactual column).

source
CounterfactualTraining.Native.generate_counterfactuals! — Method
generate_counterfactuals!(
    model,
    X::AbstractMatrix,
    targets::Vector{Int},
    data::CounterfactualData,
    generator::NativeGenerator;
    maxiter = 30,
    decision_threshold = 0.75f0,
    decay = 0.9f0,
    reg_strength = 1.0f-3,
    epsilon = 0.3f0,
    p = Inf,
)

Generates counterfactual explanations for a batch of N factuals in a fully batched (GPU-compatible) fashion.

Arguments

  • model: A Flux model (or any callable that accepts a D×N matrix and returns a C×N matrix of logits).
  • X: D×N matrix of factuals.
  • targets: Length-N vector of target class indices (1-based integers).
  • data: A CounterfactualData object providing domain bounds and mutability.
  • generator: A NativeGenerator.

Keyword arguments

  • maxiter: Maximum number of search iterations.
  • decision_threshold: Target probability threshold for convergence.
  • decay: Decay rate for the polynomial decay schedule.
  • reg_strength: Regularization strength for the energy penalty.
  • epsilon: Norm bound for tracking valid adversarial examples.
  • p: Norm order for the adversarial example bound (default Inf).

Returns

  • counterfactuals::AbstractMatrix: The final counterfactuals (D×N).
  • last_valid_ae::AbstractMatrix: Last valid adversarial examples (D×N).
  • converged_mask::BitVector: Per-sample convergence flag.
  • maxiter::Int: The maximum number of iterations used.
source
CounterfactualTraining.Native.generate_native! — Method
generate_native!(
    model, train_set, generator::NativeGenerator;
    nsamples=nothing, nneighbours=1, domain=nothing, mutability=nothing,
    maxiter=30, decision_threshold=0.75f0, decay=0.9f0,
    reg_strength=1.0f-3, epsilon=0.3f0, p=Inf, verbose=1,
)

Top-level counterfactual generation for the native branch. Generates counterfactuals for a subset of the training data, finds neighbours, applies mutability protection, and partitions results into a data loader aligned with train_set batches.

Returns (dl, percent_valid, nothing) — same interface as the old generate!().

source
CounterfactualTraining.Native.protect_immutable! — Method
protect_immutable!(neighbours, counterfactuals, mutability)

Protects immutable features by setting neighbour values according to mutability directions. For each feature row:

  • :both → keep neighbour value
  • :none → use counterfactual value (no change)
  • :increase → max(counterfactual, neighbour)
  • :decrease → min(counterfactual, neighbour)
source
CounterfactualTraining.counterfactual_training — Method
counterfactual_training(
    loss::AbstractObjective,
    model,
    generator::NativeGenerator,
    train_set,
    opt_state;
    device = identity,
    val_set = nothing,
    nepochs = 100,
    burnin = 0.0f0,
    nce = nothing,
    nneighbours = 100,
    domain = nothing,
    mutability = nothing,
    maxiter = 30,
    decision_threshold = 0.75f0,
    decay = 0.9f0,
    reg_strength = 1.0f-3,
    epsilon = 0.3f0,
    p = Inf,
    verbose = 1,
    checkpoint_dir = nothing,
    callback = nothing,
)

Native GPU-compatible counterfactual training. Dispatches here when the generator is a NativeGenerator.

The device keyword is a function: identity (CPU), Flux.gpu (CUDA), or AMDGPU.gpu (AMDGPU). The model is moved to the device; training data should already be on the device (user moves it before constructing the DataLoader).

source