This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
yap-6.3/packages/yap-lbfgs/ex2.pl

66 lines
2.0 KiB
Perl
Raw Normal View History

2013-06-13 23:57:55 +01:00
%%% -*- Mode: Prolog; -*-
% This file is part of YAP-LBFGS.
% Copyright (C) 2009 Bernd Gutmann
%
% YAP-LBFGS is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% YAP-LBFGS is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with YAP-LBFGS. If not, see <http://www.gnu.org/licenses/>.
:- use_module(library(lbfgs)).
2018-09-13 13:35:37 +01:00
:- use_module(library(matrix)).
2013-06-13 23:57:55 +01:00
2018-10-05 10:26:34 +01:00
f(X0,X1,FX) :-
FX is (X0-2)*(X0-2) + (X1-1)*(X1-1).
2013-06-13 23:57:55 +01:00
% This is the call back function which evaluates F and the gradient of F
2018-10-05 10:26:34 +01:00
evaluate(FX,X,G,_N,_Step,_U) :-
2018-09-13 13:35:37 +01:00
X0 <== X[0],
X1 <== X[1],
2018-10-05 10:26:34 +01:00
f(X0,X1,FX),
2013-06-13 23:57:55 +01:00
G0 is 2*(X0-2),
2018-09-13 13:35:37 +01:00
G1 is 2*(X1-2),
G[0] <== G0,
G[1] <== G1.
2013-06-13 23:57:55 +01:00
% This is the call back function which is invoked to report the progress
2018-09-13 13:35:37 +01:00
% if the last argument is set to anything else than 0, the optimizer will
2013-06-13 23:57:55 +01:00
% stop right now
2018-09-13 13:35:37 +01:00
progress(FX,X,_G,X_Norm,G_Norm,Step,_N,Iteration,Ls,0) :-
X0 <== X[0],
X1 <== X[1],
2018-10-05 10:26:34 +01:00
format('~d. Iteration : (x0,x1)=(~4f,~4f) f(X)=~4f |X|=~4f |X\'|=~4f Step=~4f Ls=~4f~n',[Iteration,X0,X1,FX,X_Norm,G_Norm,Step,Ls]).
2013-06-13 23:57:55 +01:00
demo :-
format('Optimizing the function f(x0,x1) = (x0-2)^2 + (x1-1)^2~n',[]),
2018-10-05 10:26:34 +01:00
lbfgs_initialize(2,X,0,Solver),
2013-06-13 23:57:55 +01:00
StartX0 is random*1000-500,
StartX1 is random*1000-500,
2018-10-05 10:26:34 +01:00
2013-06-13 23:57:55 +01:00
format('We start the search at the random position (x0,x1)=(~5f,~5f)~2n',[StartX0,StartX1]),
2018-09-13 13:35:37 +01:00
X[0] <== StartX0,
2018-10-05 10:26:34 +01:00
X[1] <== StartX1,
lbfgs_run(Solver,BestF,Status),
2018-09-13 13:35:37 +01:00
BestX0 <== X[0],
BestX1 <== X[1],
2018-10-05 10:26:34 +01:00
optimizer_finalize(Solver),
2013-06-13 23:57:55 +01:00
format('~2nOptimization done~nWe found a minimum at f(~f,~f)=~f~2nLBFGS Status=~w~n',[BestX0,BestX1,BestF,Status]).