Losses and Errors

In general we distinguish between losses that are used during training of a neural network and errors that arise in the context of reduced order modeling.

Different Neural Network Losses

GeometricMachineLearning has a number of loss functions implemented that can be called standard losses. Those are the FeedForwardLoss (defined in AbstractNeuralNetworks), the TransformerLoss, the AutoEncoderLoss and the ReducedLoss. How to implement custom losses is shown in a tutorial.

A Note on Physics-Informed Neural Networks

A popular trend in recent years has been considering known physical properties of the differential equation, or the entire differential equation, through the loss function [59]. This is one way of considering physical properties, and GeometricMachineLearning allows for a flexible implementation of custom losses, but this is nonetheless discouraged. In general a neural networks consists of three ingredients:

The three ingredients that go into neural network-based machine learning. The three ingredients that go into neural network-based machine learning.

Instead of considering certain properties through the loss function, we instead do so by enforcing them strongly through the network architecture and the optimizer; the latter pertains to manifold optimization. The advantages of this approach are the strong enforcement of properties that we know our network should have and much easier training because we do not have to tune hyperparameters.

Projection and Reduction Errors of Reduced Models

Two errors that are of very big importance in reduced order modeling are the projection and the reduction error. During training one typically aims at minimizing the projection error, but for the actual application of the model the reduction error is often more important.

Projection Error

The projection error computes how well a reduced basis, represented by the reduction $\mathcal{P}$ and the reconstruction $\mathcal{R}$, can represent the data with which it is build. In mathematical terms:

\[ e_\mathrm{proj}(\mu) := \frac{|| \mathcal{R}\circ\mathcal{P}(M) - M ||}{|| M ||},\]

where $||\cdot||$ is the Frobenius norm (one could also optimize for different norms). The corresponding function in GeometricMachineLearning is projection_error. The projection error is equivalent to AutoEncoderLoss and is used for training under that name.

Reduction Error

The reduction error measures how far the reduced system diverges from the full-order system during integration (online stage). In mathematical terms (and for a single initial condition):

\[e_\mathrm{red}(\mu) := \sqrt{ \frac{\sum_{t=0}^K|| \mathbf{x}^{(t)}(\mu) - \mathcal{R}(\mathbf{x}^{(t)}_r(\mu)) ||^2}{\sum_{t=0}^K|| \mathbf{x}^{(t)}(\mu) ||^2} },\]

where $\mathbf{x}^{(t)}$ is the solution of the FOM at point $t$ and $\mathbf{x}^{(t)}_r$ is the solution of the ROM (in the reduced basis) at point $t$. The reduction error, as opposed to the projection error, not only measures how well the solution manifold is represented by the reduced basis, but also measures how well the FOM dynamics are approximated by the ROM dynamics (via the induced vector field on the reduced basis). The corresponding function in GeometricMachineLearning is reduction_error. The reduction error is, in contract to the projection error, typically not used during training (even though some authors are using a similar error to do so [49]).

For a decoder whose reduced dynamics matter more than the pointwise reconstruction, ReducedHamiltonianLoss fits the states together with the gradient of the reduced Hamiltonian $H\circ\Psi^\mathrm{dec}$, which for a symplectic decoder is the reduced vector field up to $\mathbb{J}$.

LatentVectorFieldLoss trains encoder and decoder on states of the full system and on its vector field there: besides the reconstruction it compares the reduced vector field $\mathbb{J}_{2n}\nabla_\xi(H\circ\Psi^\mathrm{dec})$ at $\xi=\Psi^\mathrm{enc}(x)$ with the full vector field pushed forward by the encoder.

Library Functions

GeometricMachineLearning.TransformerLoss — Type
TransformerLoss(seq_length, prediction_window)

Make an instance of the transformer loss.

This should be used together with a neural network of type TransformerIntegrator.

Example

TransformerLoss applies a neural network to an input and compares it to the output via an $L_2$ norm:

using GeometricMachineLearning
using LinearAlgebra: norm
import Random

const d = 2
const seq_length = 3
const prediction_window = 2

Random.seed!(123)
arch = StandardTransformerIntegrator(d)
nn = NeuralNetwork(arch)

input_mat =  [1. 2. 3.; 4. 5. 6.]
output_mat = [1. 2.; 3. 4.]
loss = TransformerLoss(seq_length, prediction_window)

# start of prediction
const sop = seq_length - prediction_window + 1
loss(nn, input_mat, output_mat) ≈ norm(output_mat - nn(input_mat)[:, sop:end]) / norm(output_mat)

# output

true

So TransformerLoss simply does:

\[ \mathtt{loss}(\mathcal{NN}, \mathtt{input}, \mathtt{output}) = || \mathcal{NN}(\mathtt{input})[(\mathtt{sl} - \mathtt{pw} + 1):\mathtt{end}] - \mathtt{output} || / || \mathtt{output} ||,\]

where $||\cdot||$ is the $L_2$ norm.

Parameters

The prediction_window specifies how many time steps are predicted into the future. It defaults to the value specified for seq_length.

source
GeometricMachineLearning.AutoEncoderLoss — Type
AutoEncoderLoss()

Make an instance of AutoEncoderLoss.

This loss should always be used together with a neural network of type AutoEncoder (and it is also the default for training such a network).

Example

AutoEncoderLoss applies a neural network to an input and compares it to the input via an $L_2$ norm:

using GeometricMachineLearning
using LinearAlgebra: norm
import Random
Random.seed!(123)

const N = 4
const n = 1
arch = SymplecticAutoencoder(2*N, 2*n)
nn = NeuralNetwork(arch)

input_vec =  [1., 2., 3., 4., 5., 6., 7., 8.]
loss = AutoEncoderLoss()

loss(nn, input_vec) ≈ norm(input_vec - nn(input_vec)) / norm(input_vec)

# output

true

So AutoEncoderLoss simply does:

\[ \mathtt{loss}(\mathcal{NN}, \mathtt{input}) = || \mathcal{NN}(\mathtt{input}) - \mathtt{input} || / || \mathtt{input} ||,\]

where $||\cdot||$ is the $L_2$ norm.

Parameters

This loss does not have any parameters. The four-argument method reconstructs its input and ignores the target it is given, so an autoencoder is trained on the input alone.

source
GeometricMachineLearning.ReducedLoss — Type
ReducedLoss(encoder, decoder)

Make an instance of ReducedLoss based on an Encoder and a Decoder.

This loss should be used together with a NeuralNetworkIntegrator or TransformerIntegrator.

Example

ReducedLoss applies the encoder, integrator and decoder neural networks in this order to an input and compares it to the output via an $L_2$ norm:

using GeometricMachineLearning
using LinearAlgebra: norm
import Random
Random.seed!(123)

const N = 4
const n = 1

Ψᵉ = NeuralNetwork(Chain(Dense(N, n), Dense(n, n))) |> encoder
Ψᵈ = NeuralNetwork(Chain(Dense(n, n), Dense(n, N))) |> decoder
transformer = NeuralNetwork(StandardTransformerIntegrator(n))

input_mat =  [1.  2.;  3.  4.;  5.  6.;  7.  8.]
output_mat = [9. 10.; 11. 12.; 13. 14.; 15. 16.]
loss = ReducedLoss(Ψᵉ, Ψᵈ)

output_prediction = Ψᵈ(transformer(Ψᵉ(input_mat)))
loss(transformer, input_mat, output_mat) ≈ norm(output_mat - output_prediction) / norm(output_mat)

# output

true

So the loss computes:

\[\mathrm{loss}_{\mathcal{E}, \mathcal{D}}(\mathcal{NN}, \mathrm{input}, \mathrm{output}) = ||\mathcal{D}(\mathcal{NN}(\mathcal{E}(\mathrm{input}))) - \mathrm{output}||,\]

where $\mathcal{E}$ is the Encoder, $\mathcal{D}$ is the Decoder. $\mathcal{NN}$ is the neural network we compute the loss of.

source
GeometricMachineLearning.ReducedHamiltonianLoss — Type
ReducedHamiltonianLoss(hamiltonian; λ = 1, h = nothing, gradient_scale = 1)

Make an instance of ReducedHamiltonianLoss for a Hamiltonian $H$ on the full space.

The loss fits a Decoder $\Psi^\mathrm{dec}:\mathbb{R}^{2n}\to\mathbb{R}^{2N}$ on latent points $z$ to target states $x^*$ and to target gradients $g^*$ of the reduced Hamiltonian $H\circ\Psi^\mathrm{dec}$:

\[L = \frac{\lVert\Psi^\mathrm{dec}(z) - x^*\rVert}{\lVert x^*\rVert} + \lambda\,\frac{\lVert\nabla_z(H\circ\Psi^\mathrm{dec})(z) - g^*\rVert}{\sqrt{B}\,s},\]

where the norms are taken over the batch of $B$ latent points and $s$ is gradient_scale. The gradient term is the root-mean-square error of the gradient over the batch, divided by a scale fixed when the loss is built. It is continuous in $g^*$, also at $g^* = 0$, and a minibatch and the whole data set give values of the same size. With $s = 1$ it is the absolute error. A natural scale is the root-mean-square of $g^*$ over the whole data set of $N_\mathrm{data}$ points, $s = \lVert g^*\rVert/\sqrt{N_\mathrm{data}}$, which makes the term a relative error over the data set.

For a symplectic decoder, as in a SymplecticAutoencoder, the reduced vector field is $\mathbb{J}_{2n}\nabla_z(H\circ\Psi^\mathrm{dec})$, so the second term fits the reduced vector field at the sampled points. A fit of the states alone can be small while this gradient is not, in particular where $H\circ\Psi^\mathrm{dec}$ is steep.

The gradient with respect to $z$ is computed by central differences with step h, from one evaluation of the decoder on the batch and two on the $2n$ shifted copies of the batch, one per sign of the step; with λ = 0 the gradient term is left out, and the loss evaluates the decoder once. This keeps the loss differentiable with respect to the parameters by the same reverse-mode pass as any other loss, without nesting automatic differentiation.

Arguments

  • hamiltonian: a function that maps a matrix of states in $\mathbb{R}^{2N}$, one per column, to the vector of their energies. It has to be differentiable by Zygote.
  • λ = 1: the weight of the gradient term, finite and $\geq 0$.
  • h = nothing: the step of the central differences, in latent coordinates, finite and $> 0$, also in the element type of the data; a step that rounds to zero or to infinity there raises an ArgumentError when the loss is evaluated. With nothing, the step is cbrt(eps(T)) for the element type T of the data, which balances the truncation and the round-off error of the central differences.
  • gradient_scale = 1: the scale $s$ of the gradient term, finite and $> 0$.

Another λ, h or gradient_scale raises an ArgumentError.

Functor

loss(model, ps, input, output)
loss(nn, input, output)

input holds the latent points $z$, one per column ($2n$ rows). output stacks the targets: the first $2N$ rows are $x^*$, the last $2n$ rows are $g^*$; another number of rows raises an ArgumentError. The loss has the element type of the data, for a network of the same element type. Both forms also take the 3-tensors of a DataLoader built from an input and an output matrix; $B$ then counts the columns of all batches.

Examples

A decoder fitted to its own states and reduced gradients has a loss of the size of the difference error:

using GeometricMachineLearning
using Zygote: gradient
import Random
Random.seed!(123)

H(X) = vec(sum(abs2, X[3:4, :]; dims = 1)) ./ 2 .+ X[2, :]   # |p|²/2 + q₂ on ℝ⁴
dec = decoder(NeuralNetwork(SymplecticAutoencoder(4, 2; n_encoder_blocks = 2, n_decoder_blocks = 2)))
z = randn(2, 20)
x = dec(z)
g = reduce(hcat, [gradient(ζ -> H(reshape(dec(ζ), 4, 1))[1], collect(ζ))[1] for ζ in eachcol(z)])
loss = ReducedHamiltonianLoss(H)
loss(dec, z, vcat(x, g)) < 1e-6

# output

true
source
GeometricMachineLearning.LatentVectorFieldLoss — Type
LatentVectorFieldLoss(arch, hamiltonian; λ = 1, h = nothing, vector_field_scale = 1, reconstruction = true, energy = false, reference_state = nothing, energy_scale = 1)

Make an instance of LatentVectorFieldLoss for a symplectic autoencoder architecture arch and a Hamiltonian $H$ on the full space.

The loss trains encoder and decoder together on states $x$ of the full system and on its vector field $X_H(x) = \mathbb{J}_{2N}\nabla{}H(x)$ there. With $\xi = \Psi^\mathrm{enc}(x)$ it is

\[L = \frac{\lVert\Psi^\mathrm{dec}(\xi) - x\rVert}{\lVert x\rVert} + \lambda\,\frac{\lVert\mathbb{J}_{2n}\nabla_\xi(H\circ\Psi^\mathrm{dec})(\xi) - \nabla\Psi^\mathrm{enc}(x)X_H(x)\rVert}{\sqrt{B}\,s},\]

where the norms are taken over the batch of $B$ states and $s$ is vector_field_scale. The first term is the relative reconstruction error. The second term compares two vector fields in the latent space: the reduced vector field $\mathbb{J}_{2n}\nabla_\xi(H\circ\Psi^\mathrm{dec})$, which is the vector field of the reduced system for a symplectic decoder, and the full vector field pushed forward by the encoder. It vanishes when the encoder maps the trajectories of the full system onto those of the reduced one. No target decoder and no latent targets are needed, only states and the full vector field.

The second term is the root-mean-square error of the latent vector field over the batch, divided by a scale fixed when the loss is built. It is continuous in $X_H$, also where $X_H$ vanishes, and a minibatch and the whole data set give values of the same size. With $s = 1$ it is the absolute error. The target $\nabla\Psi^\mathrm{enc}(x)X_H(x)$ changes with the encoder, so no scale makes the term relative for every encoder; the root-mean-square of $X_H$ over the data set of $N_\mathrm{data}$ states, $s = \lVert X_H\rVert/\sqrt{N_\mathrm{data}}$, is a natural choice for an encoder whose derivative has a norm of order one, such as the transpose of an orthonormal basis.

With energy = true the loss has a third term, the energy error

\[\frac{\lVert(\tilde{H}(\xi) - \tilde{H}(\xi_\mathrm{ref})) - (H(x) - H(x_\mathrm{ref}))\rVert}{\sqrt{B}\,s_E},\]

with the reduced Hamiltonian $\tilde{H} = H\circ\Psi^\mathrm{dec}$, the reference state $x_\mathrm{ref}$ = reference_state, its encoding $\xi_\mathrm{ref} = \Psi^\mathrm{enc}(x_\mathrm{ref})$, and $s_E$ = energy_scale. A Hamiltonian is defined up to an additive constant, which the dynamics do not see. The term compares energy differences against one fixed reference point, so it does not depend on that constant either; this is the normalisation of a learned Hamiltonian at a reference point of C. Offen and S. Ober-Blöbaum, "Symplectic integration of learned Hamiltonian systems", Chaos 32(1), 013122 (2022), doi:10.1063/5.0065913, Sec. III, Eq. (12). The reference is fixed when the loss is built, not taken from the batch, so the term of a state does not depend on the other states of its batch. The term asks that the reduced Hamiltonian take the energy of the state it encodes. Unlike the reconstruction it does not tie $\Psi^\mathrm{dec}(\xi)$ to $x$, and unlike the vector-field term it keeps its weight where the vector field vanishes.

Reconstruction and dynamics can contradict each other

The reconstruction term asks that $\Psi^\mathrm{dec}(\Psi^\mathrm{enc}(x)) = x$; the vector-field and energy terms ask that the reduced Hamiltonian system reproduce the full system's trajectories and energies. Where no symplectic chart can do both (for instance where the data contain a separatrix that a single chart cannot reconstruct), a network trained on both must fail one of them. The weight λ and the scales vector_field_scale and energy_scale decide which; they also carry the units of the vector field and of the energy, which the reconstruction term does not have.

The vector field has to be the one the data follow

When the states lie on a submanifold, as the states of a constrained system do, the target is the system's vector field there, which is tangent to it, and not $\mathbb{J}_{2N}\nabla{}H$ of a Hamiltonian that merely restricts to the right energy on it. The push-forward of a field that leaves the submanifold involves the derivatives of the encoder off the data, which do not describe how encoded trajectories move.

Both derivatives are central differences with the step h. The gradient $\nabla_\xi(H\circ\Psi^\mathrm{dec})$ takes two decoder evaluations on the $2n$ shifted copies of the batch, one per sign of the step h in latent coordinates. The push-forward is $\nabla\Psi^\mathrm{enc}(x)X_H(x) \approx (\Psi^\mathrm{enc}(x + hX_H) - \Psi^\mathrm{enc}(x - hX_H))/(2h)$, from two encoder evaluations; its step in the full space is $h\lVert X_H(x)\rVert$, so it scales with the vector field. With λ = 0 the vector-field term is left out, and neither derivative is computed. This keeps the loss differentiable with respect to the parameters by the same reverse-mode pass as any other loss, without nesting automatic differentiation.

Arguments

  • arch: the architecture whose network is trained, a SymplecticAutoencoder, a PSDArch or a LeftInverseSymplecticAutoencoder. It fixes the number of layers of the encoder and of the decoder, and the latent dimension $2n$. The decoder of a LeftInverseSymplecticAutoencoder takes the parameter tree of the network and its encoder the reversed tree, as in its forward pass. Another symplectic architecture raises an ArgumentError, and an architecture that is not symplectic has no method.
  • hamiltonian: a function that maps a matrix of states in $\mathbb{R}^{2N}$, one per column, to the vector of their energies. It has to be differentiable by Zygote.
  • λ = 1: the weight of the vector-field term, finite and $\geq 0$.
  • h = nothing: the step of the central differences, finite and $> 0$, also in the element type of the data; a step that rounds to zero or to infinity there raises an ArgumentError when the loss is evaluated. With nothing, the step is cbrt(eps(T)) for the element type T of the data, which balances the truncation and the round-off error of the central differences.
  • vector_field_scale = 1: the scale $s$ of the vector-field term, finite and $> 0$.
  • reconstruction = true: with false the reconstruction term is left out. Only the reduced dynamics (and, with energy = true, the energies) are then fitted; nothing ties $\Psi^\mathrm{dec}(\xi)$ to $x$ except through $H\circ\Psi^\mathrm{dec}$.
  • energy = false: with true the loss has the energy term.
  • reference_state = nothing: the reference state $x_\mathrm{ref}$ of the energy term, a vector of the full dimension $2N$ with finite entries. It is required with energy = true.
  • energy_scale = 1: the scale $s_E$ of the energy term, finite and $> 0$. The root-mean-square of $H(x) - H(x_\mathrm{ref})$ over the data set is a natural choice.

Another λ, h, vector_field_scale, energy_scale or reference_state, and energy = true without a reference_state, raise an ArgumentError.

Functor

loss(model, ps, input, output)
loss(nn, input, output)

input holds the states $x$, one per column ($2N$ rows), and output the vector field $X_H(x)$ at them, of the same size; another size raises an ArgumentError, and so does a network that does not have the number of layers of arch, those of its encoder and its decoder together, or whose encoder does not give its latent dimension. The model is the whole autoencoder. The loss has the element type of the data, for a network of the same element type. Both forms also take the 3-tensors of a DataLoader built from an input and an output matrix; $B$ then counts the columns of all batches.

Examples

After solve!, the encoder of a proper symplectic decomposition is the transpose $A^T$ of the symplectic and orthonormal basis $A$ of the decoder, and $A^T\mathbb{J}_{2N} = \mathbb{J}_{2n}A^T$. For a state in the range of the decoder, the reconstruction is therefore exact, and the pushed-forward field $A^T\mathbb{J}_{2N}\nabla{}H$ is the reduced field $\mathbb{J}_{2n}A^T\nabla{}H$, for every Hamiltonian. The loss vanishes up to the error of the central differences:

using GeometricMachineLearning
using GeometricMachineLearning: solve!
import Random
Random.seed!(123)

H(X) = vec(sum(abs2, X[3:4, :]; dims = 1)) ./ 2 .+ cos.(X[1, :])   # |p|²/2 + cos(q₁) on ℝ⁴
XH(X) = vcat(X[3:4, :], sin.(X[1:1, :]), zero(X[2:2, :]))           # 𝕁∇H = (p, -∇_q H)
arch = PSDArch(4, 2)
nn = NeuralNetwork(arch)
solve!(nn, randn(4, 20))
x = decoder(nn)(randn(2, 10))
loss = LatentVectorFieldLoss(arch, H)
loss(nn, x, XH(x)) < 1e-8

# output

true
source
GeometricMachineLearning.CharbonnierRelativeLoss — Type
CharbonnierRelativeLoss(; ε = 1e-3, λ_lat = 1e-2)

Smooth Charbonnier relative reconstruction and latent consistency loss:

\[\mathcal{L}_{\mathrm{Charb}}(\hat{x}, x) = \frac{\sqrt{\|\hat{x} - x\|_F^2 + \varepsilon^2} - \varepsilon}{\sqrt{\|x\|_F^2 + \varepsilon^2}} + \lambda_{\mathrm{lat}}\,\frac{\|\mathrm{encode}(nn, m, \hat{x}) - \mathrm{encode}(nn, m, x)\|_F^2}{\|x\|_F^2 + \varepsilon^2}.\]

Called as loss(nn, m, x̂, x), it takes an external reconstruction $\hat{x}$. Called as loss(nn, m, x) (or loss(nn, x) for the first modality), it uses $\hat{x} = \mathrm{decode}(nn, m, \mathrm{encode}(nn, m, x))$.

Both forms compare $\hat{x}$ with $x$ in the form that decode returns: a pre-split pair (q = F⁺, p = F⁻) of a BilinearStiefelLayer modality, passed as $x$ or as $\hat{x}$, is recombined into the full field. The two halves of such a pair have one element type; halves of different element types raise an ArgumentError.

Here $\varepsilon > 0$ (default 1e-3) regularizes the Frobenius norm at $\hat{x} = x$ and $x = 0$, and $\lambda_{\mathrm{lat}} \ge 0$ (default 1e-2) weights the latent re-encoding consistency penalty.

When $x = 0$ and $\hat{x} = 0$, the loss returns exact zero(T) (not NaN), and its gradient at $\hat{x} = x$ is finite and zero (0 / ε = 0).

source
GeometricMachineLearning.IsometricRolloutLoss — Type
IsometricRolloutLoss(integrator; α_lat = 1.0, α_rec = 1.0, α_H = 0.0, H = nothing)

Multi-step latent rollout, decoded trajectory reconstruction, and latent Hamiltonian conservation loss:

\[\mathcal{L}_{\mathrm{roll}} = \frac{1}{K - 1}\sum_{k=2}^{K} \left( \alpha_{\mathrm{lat}}\,\|\hat{z}_k - z_k\|_F^2 + \alpha_{\mathrm{rec}}\,\|\mathrm{decode}(nn, m, \hat{z}_k) - x_k\|_F^2 + \alpha_H\,\bigl|H(\hat{z}_k) - H(\hat{z}_1)\bigr|^2 \right),\]

where $z_k = \mathrm{encode}(nn, m, x_k)$, $\hat{z}_1 = z_1$, $\hat{z}_{k+1} = \mathrm{integrator}(\hat{z}_k)$ for $k = 1, \dots, K - 1$, and H is a callable latent Hamiltonian. H(ẑ) takes the latent state as encode and integrator give it, a vector of length $2n$ or a matrix of size $(2n, B)$ for a batched snapshot, and returns one scalar, one value for a whole batch. The decoded state is compared with $x_k$ in the form that decode returns: a pre-split pair (q = F⁺, p = F⁻) of a BilinearStiefelLayer modality is recombined into the full field. The weights default to α_lat = 1.0, α_rec = 1.0, and α_H = 0.0, so IsometricRolloutLoss(integrator) has no energy term.

H has no default: the loss requires a latent Hamiltonian H when α_H > 0, and the constructor raises an ArgumentError without one. A fixed latent energy such as $\frac{1}{2}\|\hat{z}\|_2^2$ is not the energy of the system. With α_H = 0, the loss has no energy term and takes no H: a given H would have no effect, so the constructor raises an ArgumentError. The data, the output of integrator and, with α_H > 0, the value of H have the element type of the network's parameters; another element type raises an ArgumentError.

source
GeometricMachineLearning.CrossModalLoss — Type
CrossModalLoss(mod_a::Symbol, mod_b::Symbol; β_align = 1.0, β_cross = 1.0)

Cross-modal paired latent alignment and cross-reconstruction loss between modalities mod_a and mod_b:

\[\mathcal{L}_{\mathrm{cross}}(x_a, x_b) = \beta_{\mathrm{align}}\,\|z_a - z_b\|_F^2 + \beta_{\mathrm{cross}}\,\|\mathrm{decode}(nn, b, z_a) - x_b\|_F^2,\]

where $z_a = \mathrm{encode}(nn, a, x_a)$ and $z_b = \mathrm{encode}(nn, b, x_b)$. The pair $(x_a, x_b)$ is the same physical state in two modalities: the alignment term asks that both encode to one latent state, and the cross-reconstruction term asks that the latent state of $x_a$ decodes to $x_b$. The loss is not symmetric in $a$ and $b$: the cross-reconstruction term decodes only into modality mod_b, so CrossModalLoss(mod_b, mod_a) is another loss. decode(nn, b, z_a) is compared with $x_b$ in the form that decode returns: a pre-split pair (q = F⁺, p = F⁻) of a BilinearStiefelLayer modality is recombined into the full field. A batch is the sum of its samples' losses; x_a and x_b with different numbers of samples raise a DimensionMismatch.

The weights are non-negative and default to β_align = 1.0 and β_cross = 1.0; a negative or NaN weight raises an ArgumentError. x_a and x_b have the element type of the network's parameters; another element type raises an ArgumentError.

source
GeometricMachineLearning.ParametricLoss — Type
ParametricLoss()

Make an instance of the loss of a network whose forward pass takes the parameters $\mu$ of the system beside its input.

ParametricLoss()(model, ps, input, output, μ) applies the network with apply_parametric and compares the result with output in the relative $L_2$ norm:

\[\mathrm{loss}(\mathcal{NN}, \mathrm{input}, \mathrm{output}, \mu) = ||\mathcal{NN}(\mathrm{input}, \mu) - \mathrm{output}|| / ||\mathrm{output}||.\]

This is FeedForwardLoss with the system parameters passed to the network. μ is one OptionalParameters for one sample, or a vector of them, one per sample of a batch, as a ParametricDataLoader draws it. train! on a ParametricDataLoader trains on this loss when no loss is given.

source
GeometricMachineLearning.apply_parametric — Function
apply_parametric(model, x, μ, ps)

Apply the Chain model with the network parameters ps to the input x and the parameters μ of the system.

x is one sample — a vector, or a (q, p) named tuple of vectors — with one μ, an OptionalParameters. Or x is a batch of k samples — a 2d × 1 × k tensor, or a (q, p) named tuple of d × 1 × k tensors — with a vector of k values of μ, one per sample, as a ParametricDataLoader draws them. A batch holds at least one sample. The output has the shape of the input.

The Chain receives the pair (x, μ), so its first layer takes one sample and its μ, and a layer that returns such a pair passes μ on to the next. A batch is applied sample by sample.

Examples

using GeometricMachineLearning
using GeometricMachineLearning: apply_parametric
import AbstractNeuralNetworks: AbstractExplicitLayer

# a layer that adds the system parameter `a` to its input
struct AddParameter <: AbstractExplicitLayer{2, 2} end
(::AddParameter)((x, μ)::Tuple, ps) = x .+ μ.a

model = Chain(AddParameter())
ps = NetworkParameters((L1 = NamedTuple(),))
x = reshape([1.0, 2.0, 3.0, 4.0], 2, 1, 2)
apply_parametric(model, x, [(a = 10.0,), (a = 20.0,)], ps)

# output

2×1×2 Array{Float64, 3}:
[:, :, 1] =
 11.0
 12.0

[:, :, 2] =
 23.0
 24.0
source
GeometricMachineLearning.projection_error — Function
projection_error(rs)

Compute the projection error for a HRedSys.

Arguments

If the full system has already been integrated, then the projection error can be computed quicker:

projection_error(rs, sol_full)

This saves the cost of again integrating the systems.

source
GeometricMachineLearning.reduction_error — Function
reduction_error(rs)

Compute the reduction error for a HRedSys.

Arguments

If the full system and the reduced system have already been integrated, then the reduction error can be computed quicker:

reduction_error(rs, sol_full, sol_reduced)

This saves the cost of again integrating the respective systems.

source

References

[49]
K. Lee and K. T. Carlberg. Model reduction of dynamical systems on nonlinear manifolds using deep convolutional autoencoders. Journal of Computational Physics 404, 108973 (2020).
[59]
M. Raissi, P. Perdikaris and G. E. Karniadakis. Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations. Journal of Computational physics 378, 686–707 (2019).