Optimization of Dynamical Systems Containing Neural Networks