Training Hamiltonian neural networks without backpropagation