从Matlab到Python的优化器

时间:2017-02-22 14:22:02

标签: python matlab optimization

我想将以下问题从Matlab转换为Python(Matlab代码):

  function [f,g] = rosenbrockwithgrad(x)
    f = 100*(x(2) - x(1)^2)^2 + (1-x(1))^2;

    if nargout > 1 % gradient required
      g = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1));
      200*(x(2)-x(1)^2)];
   end

然后调用优化器:

   options = optimoptions('fminunc','Algorithm','trust-region','SpecifyObjectiveGradient',true);
   fminunc(@(x) rosenbrockwithgrad(x),x0,options)

的Python:

  def rosenbrockwithgrad(x, nargout = 1):
    f = 100*(x[1] - x[0]**2)**2 + (1-x([0]))**2;

    if nargout > 1: #gradient
     g = ([-400*(x[1]-x[0]**2)*x[0]-2*(1-x[0]), 200*(x[1]-x[0])**2]);
   return f,g

然后调用优化器:

   scipy.optimise.fmin_cg(...no idea...)

是否有必要拆分函数或是否有类似于Matlab的方法?

0 个答案:

没有答案