Hamiltonian Neural Network

The following layer helps construct a neural network which allows learning dynamics and conservation laws by approximating the hamiltonian of a system.


Constructs a Hamiltonian Neural Network [1]. This neural network is useful for learning symmetries and conservation laws by supervision on the gradients of the trajectories. It takes as input a concatenated vector of length 2n containing the position (of size n) and momentum (of size n) of the particles. It then returns the time derivatives for position and momentum.


This doesn't solve the Hamiltonian Problem. Use NeuralHamiltonianDE for such applications.


This layer currently doesn't support GPU. The support will be added in future with some AD fixes.

To obtain the gradients to train this network, ReverseDiff.gradient is supposed to be used. This prevents the usage of DiffEqFlux.sciml_train or Flux.train. Follow this tutorial to see how to define a training loop to circumvent this issue.

HamiltonianNN(model; p = nothing)
HamiltonianNN(model::FastChain; p = initial_params(model))


  1. model: A Chain or FastChain neural network that returns the Hamiltonian of the system.
  2. p: The initial parameters of the neural network.

References: [1] Greydanus, Samuel, Misko Dzamba, and Jason Yosinski. "Hamiltonian neural networks." Advances in Neural Information Processing Systems. 2019.


Contructs a Neural Hamiltonian DE Layer for solving Hamiltonian Problems parameterized by a Neural Network HamiltonianNN.

NeuralHamiltonianDE(model, tspan, args...; kwargs...)


  • model: A Chain, FastChain or Hamiltonian Neural Network that predicts the Hamiltonian of the system.
  • tspan: The timespan to be solved on.
  • kwargs: Additional arguments splatted to the ODE solver. See the Common Solver Arguments documentation for more details.