4

MATLAB プログラムの一部を Python と Octave に変換している最中です。

Octave を使用して 2 つの行列を生成し、oct2py. 私の問題の根本は、MATLAB のこれらの行 (H_combinedおよびf_combined以下)です。

handles.options =optimset('algorithm','interior-point-convex','Display','off','TolFun',1e-15,'TolX',1e-10,'MaxFunEvals', 1E5);

handles.x_ridge_combined = quadprog(H_combined, f_combined, [], [], [], [], handles.lb_re, handles.ub_re, handles.x_re_0, handles.options);

現在、私はPythonまたはOctaveのいずれかで、同様の出力を無駄に生成するソリューションを探しています。

quadprogOctaveから使用しようとしましたが、予想される float 値の組み合わせではなく、onoptimの出力が得られます。とが MATLAB で実行した場合とまったく同じであることを確認しましたが、Octave では同じように動作しないと思います。120, 1, 1, 1, ..., 1x_ridge_combinedH_combinedf_combinedquadprog

Octave アプローチを試した後、値を Python にインポートしてquadprogパッケージを使用してみます。

しようquadprogとして、

print(quadprog.solve_qp(H,f))

エラーが発生します

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

と の種類と形状はH次のfとおりです。

<class 'numpy.ndarray'> #H
(123, 123)
<class 'numpy.ndarray'> #f
(1, 123)

これらのエラーが発生する理由を知っている人はいますか? または、その行を MATLAB から翻訳する方法に関する他の提案はありますか?

4

3 に答える 3

0

少し範囲外ですが、プロジェクトNLoptを実行に移したいと考えています。頭字語が示すように、非線形最適化に取り組みますが、グローバル/ローカル、微分なし/明示的な微分のアルゴリズムが豊富に含まれています。私が言及したい理由は、MATLAB、Octave + Python (および C/C++ など) のインターフェイスを備えているからです。そのため、さまざまな言語でソリューションを再現するのが非常に簡単になります (それが、私がこのソリューションに出くわした理由です)。さらに、アルゴリズムは実際には MATLAB ネイティブのものよりも高速です (これは私自身の経験です)。

あなたの問題については、BOBYQA(二次最適化による境界付き最適化またはSLSQP(逐次最小二乗二次計画法))を使用します。ただし、行列を引き渡すのではなく、コスト関数を作成する必要があります

インストールはpip経由で簡単です

pip install nlopt

少しチェックして

import nlopt
# run quick test. Look for "Passed: optimizer interface test"
nlopt.test.test_nlopt()

最適化の使用方法に関するいくつかの簡単なコード:

import numpy as np
import nlopt

obj = nlopt.opt(nlopt.LN_BOBYQA,5)
obj.set_min_objective(fnc)

obj.set_lower_bounds(lb)
obj.set_upper_bounds(ub)

def fnc(x, grad):

        """
        The return value should be the value of the function at the point x, 
        where x is a NumPy array of length n of the optimization parameters 
        (the same as the dimension passed to the constructor).

        In addition, if the argument grad is not empty, i.e. grad.size>0, then 
        grad is a NumPy array of length n which should (upon return) be set to 
        the gradient of the function with respect to the optimization parameters 
        at x. That is, grad[i] should upon return contain the partial derivative , 
        for , if grad is non-empty.
        """
        H = np.eye(len(x)) # extampe matrix

        cost = 0.5*x.transpose().dot( H.dot(x) )
        return float(cost) # make sure it is a number

xopt = obj.optimize(x0)

MATLAB では、DLL をパスに追加するだけです。BOBYQA の短いラッパーを作成して、MATLAB のインターフェイスを模倣しました (両方の言語でチェックアウトしたい場合に備えて =P -- お知らせください。MATLAB でより頻繁に使用しています ... ラッパーがおそらく示すように) ^^):

function [x_opt, fval, exitflag] = BOBYQA(fnc,x0,lb,ub, varargin)
% performes a constrained, derivative-free local optimization
%
% --- Syntax:
% x_opt = BOBYQA(fnc,x0,lb,ub)
% x_opt = BOBYQA(...,'MaxEval',10)
% x_opt = BOBYQA(...,'MaxTime',5)
% [x_opt, fval] = BOBYQA(...)
% [x_opt, fval, exitflag] = BOBYQA(...)
% 
% --- Description:
% x_opt = BOBYQA(fnc,x0,lb,ub)  takes a function handle 'func', an initial 
%               value 'x0' and lower and upper boundary constraints 'lb' 
%               and 'ub' as input. Performes a constrained local 
%               optimization using the algorithm BOBYQA from Powell 
%               http://www.damtp.cam.ac.uk/user/na/NA_papers/NA2009_06.pdf.
%               Returns the optimal value 'x_opt'.
% x_opt = BOBYQA(...,'MaxEval',10)optional input parameter that defines the
%               maximum number of evaluations.
% x_opt = BOBYQA(...,'MaxTime',5) optional input parameter that defines the
%               maximum allowed time in seconds for the optimization. This 
%               is a soft constraint and may be (slightly) broken.
% [x_opt, fval] = BOBYQA(...) seconds return value is the optimal function 
%               value.
% [x_opt, fval, exitflag] = BOBYQA(...) third return value is the exitflag,
%               see function NLoptExitFlag().
% 
% ------------------------------------------------------------------- 2017

% NLOPT_LN_BOBYQA

% --- parse input
IN = inputParser;
addParameter(IN,'MaxEval',10000, @(x)validateattributes(x,{'numeric'},{'positive'}));
addParameter(IN,'MaxTime',60, @(x)validateattributes(x,{'numeric'},{'positive'}));
parse(IN,varargin{:});

% generic success code: +1
%      stopval reached: +2
%         ftol reached: +3
%         xtol reached: +4
%      maxeval reached: +5
%      maxtime reached: +6
% generic failure code: -1
%    invalid arguments: -2
%        out of memory: -3
%     roundoff-limited: -4

    % set options
    opt = struct();
    opt.min_objective = fnc;
    opt.lower_bounds = lb;
    opt.upper_bounds = ub;



    % stopping criteria
    opt.maxtime = IN.Results.MaxTime; % s  % status = +6
%     opt.fc_tol = FncOpt.STOP_FNC_TOL*ones(size(ParInit)); % +3
%     opt.xtol_rel = FncOpt.STOP_XTOL_REL; % +4
%     opt.xtol_abs = FncOpt.STOP_XTOL_ABS*ones(size(ParInit)); % +4
    opt.maxeval = IN.Results.MaxEval; % status = +5

    % call function
    opt.algorithm = 34;% eval('NLOPT_LN_BOBYQA');

    t_start = tic;
    [x_opt, fval, exitflag] = nlopt_optimize(opt,x0);
    dt = toc(t_start);
    fprintf('BOBYQA took %.5f seconds | exitflag: %d (%s)\n',dt,exitflag,NLoptExitFlag(exitflag))
end

function txt = NLoptExitFlag(exitflag)
% generic success code: +1
%      stopval reached: +2
%         ftol reached: +3
%         xtol reached: +4
%      maxeval reached: +5
%      maxtime reached: +6
% generic failure code: -1
%    invalid arguments: -2
%        out of memory: -3
%     roundoff-limited: -4

switch exitflag
    case 1
        txt = 'generic success code';
    case 2
        txt = 'stopval reached';
    case 3
        txt = 'ftol reached';
    case 4
        txt = 'xtol reached';
    case 5
        txt = 'maxeval reached';
    case 6
        txt = 'maxtime reached';
    case -1
        txt = 'generic failure code';
    case -2
        txt = 'invalid arguments';
    case -3
        txt = 'out of memory';
    case -4
        txt = 'roundoff-limited';
    otherwise
        txt = 'undefined exitflag!';
end
end
于 2020-05-22T17:01:56.427 に答える
0

はい、cvxopt_quadprog の問題は、問題が PSD であるかどうかを毎回チェックするため、時系列の大規模な反復最適化ではかなり遅いことです。もっと早く。参照: https://github.com/stephane-caron/qpsolvers

于 2020-05-16T21:46:18.973 に答える