nelder-mead.py 882 B

1234567891011121314151617181920212223242526
  1. """Nelder-Mead minimization algorithm for the 4D function:
  2. F = (x/4-1)**2 + (y+2)**2 + z**2 + (w-6)**2 + 3"""
  3. from vedo import Minimizer, Line, show
  4. from vedo.pyplot import plot
  5. def func(pars):
  6. x, y, z, w = pars # unpack parameters for convenience
  7. F = (x/4-1)**2 + (y+2)**2 + z**2 + (w-6)**2 + 3
  8. return F
  9. mini = Minimizer(func)
  10. mini.set_parameter("x", 4.0) # set initial values
  11. mini.set_parameter("y", -3.0)
  12. mini.set_parameter("z", 1.0)
  13. mini.set_parameter("w", 1.0)
  14. res = mini.minimize() # run the minimization
  15. mini.compute_hessian() # compute the Hessian to estimate the errors
  16. print(mini)
  17. # Draw the path of the minimization
  18. path = res["parameters_path"]
  19. vals = res["function_path"]
  20. line = Line(path[:,:3], lw=5).cmap("jet", path[:,3]).add_scalarbar()
  21. plo = plot(vals, xtitle="iteration", ytitle="function eval", lw=3)
  22. show(line, plo.clone2d(), __doc__, axes=1)