使用 MATLAB `fminunc` 的问题

计算科学 优化 统计数据
2021-12-28 05:03:27

我试图找到这个函数的最小值。但是当我运行脚本时收到以下错误。我究竟做错了什么:

            % pre allocating
            x=zeros(10,4);
            mu=zeros(10,1);% process parameter
            T=zeros(10,1);% spike times
            y=zeros(10,1);%number of spikes
            eta=zeros(10,1);% linear predictor
            for i=1:10 % on trials
                for j=1:4 % on pixels
                    x(i,j)=randi(2,1)-1;
                end
                mu(i)=randi(20,1)/100;
                [T,y(i)]=ppsample(mu(i),20);
                eta(i)=log(mu(i));
                syms b0;syms b1;syms b2;syms b3;syms b4;syms objfun;
                o(i)=((b0+b1*x(i,1)+b2*x(i,2)+b3*x(i,3)+b4*x(i,4))*y(i))-exp(b0+b1*x(i,1)+b2*x(i,2)+b3*x(i,3)+b4*x(i,4));
            end
            %%finding optimum weights

            objfun=sum(o);
            ofun= matlabFunction(objfun);
            x0 = ones(1,5);
            [x,fval] = fminunc(ofun,x0);

这给出了以下内容:

Error using makeFhandle/@(b0,b1,b2,b3,b4)b0.*1.9e1+b1.*9.0+b2.*1.2e1+b3.*7.0+b4.*7.0-exp(b0+b1+b2+b3)-exp(b0+b2+b3+b4)-exp(b0+b1).*2.0-exp(b0+b2)-exp(b0)-exp(b0+b1+b2)-exp(b0+b1+b3)-exp(b0+b2+b4)-exp(b0+b3+b4)
Not enough input arguments.

Error in fminunc (line 254)
    f = feval(funfcn{3},x,varargin{:});

Error in GLM (line 30)
[x,fval] = fminunc(ofun,x0);

Caused by:
    Failure in initial user-supplied objective function evaluation.
    FMINUNC cannot continue.
1个回答

您的目标函数评估语法是错误的。

下面的代码应该可以工作。1 x 5 向量 b 是您的优化变量。它从 fminunc 调用中 x0 的维度继承其维度。我摆脱了所有 syms 的东西。请注意,在对 fminunc 的调用中,您需要在目标函数名称之前使用 @ ,以便它成为函数句柄。

                % Put this in the file ofun.m somewhere in your MATLAB path                
                function [objective] = ofun(b)
                % The line below is so that your expression for o(i) is left unchanged
                b0 = b(1); b1 = b(2); b2 = b(3); b3 = b(4); b4 = b(5);
                % pre allocating
                x=zeros(10,4);
                mu=zeros(10,1);% process parameter
                T=zeros(10,1);% spike times
                y=zeros(10,1);%number of spikes
                eta=zeros(10,1);% linear predictor
                for i=1:10 % on trials
                    for j=1:4 % on pixels
                        x(i,j)=randi(2,1)-1;
                    end
                    mu(i)=randi(20,1)/100;
                    [T,y(i)]=ppsample(mu(i),20);
                    eta(i)=log(mu(i));
                    o(i)=((b0+b1*x(i,1)+b2*x(i,2)+b3*x(i,3)+b4*x(i,4))*y(i))-exp(b0+b1*x(i,1)+b2*x(i,2)+b3*x(i,3)+b4*x(i,4));
                end
                objective = sum(o);
                end
                % end of what goes in ofun.m

                %%finding optimum weights

                x0 = ones(1,5);
                [x,fval] = fminunc(@ofun,x0);