Skip to content

Sequences, streaming data, robotics, and scientific extensions · Entry index · SEQ012 · Architecture

Hamiltonian Neural Networks

An architecture learning a scalar Hamiltonian whose derivatives define a vector field with canonical conservative structure.

Explained here Component demo, not a trained model CodeSplash's own run

In CodeSplash

Documented in the Academy only. There's no Set up button.

Availability
Explained here
Code example
Component demo, not a trained model
Who ran it
CodeSplash's own run
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review, but on a different version of the code. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

An architecture learning a scalar Hamiltonian whose derivatives define a vector field with canonical conservative structure. It embeds an energy-based inductive bias in learned dynamics, making trajectories and learned energy inspectable. It is distinct from an unconstrained neural ordinary differential equation and from a claim that all physical systems conserve energy.

Question / hypotheses

Can a learned energy function explain measured canonical-state derivatives and improve long-horizon dynamics under an appropriate conservative model? Evaluation uses derivative/trajectory errors, invariants, and extrapolation; the architecture provides no statistical test null.

Architecture / computational structure

A differentiable scalar network maps state to energy; automatic differentiation yields gradients, and a fixed symplectic transformation produces time derivatives. A separate ODE solver produces trajectories. This structure imposes algebraic constraints on the vector field without prescribing the exact functional form of the energy.

Assumptions

The basic formulation assumes suitable canonical coordinates and approximately autonomous Hamiltonian dynamics. Dissipation, forcing, noncanonical coordinates, hidden variables, or noisy derivative estimates may violate that setup. Numerical integration introduces its own error; a continuous energy-conserving vector field does not make every discrete solver conserve energy exactly.

Formula / computational definition

For state (q,p)(q,p), learn Hθ(q,p)H_\theta(q,p) and set q˙=∂Hθ/∂p\dot q=\partial H_\theta/\partial p, p˙=−∂Hθ/∂q\dot p=-\partial H_\theta/\partial q. A derivative-fitting loss compares these outputs with measured (q˙,p˙)(\dot q,\dot p). For an autonomous smooth Hamiltonian, ∇H⊤J∇H=0\nabla H^\top J\nabla H=0, with skew-symmetric canonical matrix JJ.

Parameters and notation

Learned parameters: weights defining the scalar energy function and any explicitly introduced coordinate encoder. Hyperparameters: network width/depth, derivative-estimation method, trajectory sampling, integrator, time step, and regularization. Solver tolerance and step size affect rollout error but do not change the fitted continuous vector field.

Fitting, fine-tuning, and adaptation

Train from state/derivative pairs or a clearly specified trajectory loss, splitting complete trajectories and initial-condition regimes. For a related physical system, fine-tune energy-network weights with a low learning rate while checking invariant structure and altered parameters. Reconsider the model class rather than merely optimizing longer when forcing/damping dominates.

How to use and calibrate

Report derivative error, long-horizon trajectory error, energy behavior, and performance on unseen initial conditions. Compare integrators under matched step-size budgets. Plot energy drift separately from state error: a nearly conserved but incorrect Hamiltonian can still predict the wrong physical motion.

Example application

Fit synthetic spring-mass dynamics across initial energies, then study whether long rollouts preserve the learned energy and extrapolate to larger amplitudes.

Interpretation / pitfalls

Watch out

Python: authors’ HNN implementation or an autodifferentiation framework; R: reticulate or native differential-equation analysis. The paired example verifies the conservation identity for a known quadratic oscillator; it is neither a learned Hamiltonian nor a numerical integrator.

Python and R code examples (dependencies/validation)

Python uses NumPy and the shared mse helper when called; base R uses the shared helper when called. Validation: Python component executed; R companion reviewed, not executed. Scope: the specific component described above, not the full model or its training.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — synthetic mathematical component, not a full-model implementation

Shared setup for this chapter
import numpy as np

def mse(a,b):
    a,b=np.asarray(a),np.asarray(b)
    if a.shape!=b.shape or a.size==0:
        raise ValueError("MSE needs nonempty equal shapes")
    return float(np.mean((a-b)**2))
q=.7; p=.4; mass=2.; spring=3.
gradH=np.array([spring*q,p/mass]); vector_field=np.array([p/mass,-spring*q])
energy=.5*spring*q*q+p*p/(2*mass); drift=float(gradH@vector_field)
assert abs(drift)<1e-12
result={"energy":float(energy),"instantaneous_drift":drift}
print(result)
R

Component demo, not a trained model — synthetic mathematical component, not a full-model implementation

Shared setup for this chapter
mse <- function(a,b) {
  stopifnot(length(a)>0L, identical(dim(a),dim(b)), length(a)==length(b))
  mean((a-b)^2)
}
q <- .7; p <- .4; mass <- 2; spring <- 3
gradH <- c(spring*q,p/mass); vector_field <- c(p/mass,-spring*q)
energy <- .5*spring*q*q+p*p/(2*mass); drift <- sum(gradH*vector_field)
stopifnot(abs(drift)<1e-12)
result <- c(energy=energy,instantaneous_drift=drift)
print(result)

Sources

From the CodeSplash reference, entry SEQ012.