|
|
@@ -1,29 +1,24 @@
|
|
|
/**
|
|
|
- * The original version of this file originates from SMILE:
|
|
|
- * https://github.com/haifengl/smile
|
|
|
+ * The original version of this file originates from SMILE: https://github.com/haifengl/smile
|
|
|
*/
|
|
|
|
|
|
/*******************************************************************************
|
|
|
- * Copyright (c) 2010-2020 Haifeng Li. All rights reserved.
|
|
|
- *
|
|
|
- * Smile is free software: you can redistribute it and/or modify
|
|
|
- * it under the terms of the GNU Lesser General Public License as
|
|
|
- * published by the Free Software Foundation, either version 3 of
|
|
|
- * the License, or (at your option) any later version.
|
|
|
- *
|
|
|
- * Smile 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 Lesser General Public License for more details.
|
|
|
- *
|
|
|
- * You should have received a copy of the GNU Lesser General Public License
|
|
|
- * along with Smile. If not, see <https://www.gnu.org/licenses/>.
|
|
|
+ * Copyright (c) 2010-2020 Haifeng Li. All rights reserved. Smile is free software: you can redistribute it and/or
|
|
|
+ * modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation,
|
|
|
+ * either version 3 of the License, or (at your option) any later version. Smile 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 Lesser General Public License for more details. You should have received a copy of the GNU
|
|
|
+ * Lesser General Public License along with Smile. If not, see <https://www.gnu.org/licenses/>.
|
|
|
******************************************************************************/
|
|
|
|
|
|
package de.jplag.clustering.algorithm;
|
|
|
|
|
|
+import static java.lang.Math.abs;
|
|
|
+import static java.lang.Math.max;
|
|
|
+import static java.lang.Math.min;
|
|
|
+import static java.lang.Math.sqrt;
|
|
|
+
|
|
|
import java.util.ArrayList;
|
|
|
-import java.util.Arrays;
|
|
|
import java.util.Comparator;
|
|
|
import java.util.List;
|
|
|
import java.util.stream.Collectors;
|
|
|
@@ -37,60 +32,43 @@ import org.apache.commons.math3.linear.MatrixUtils;
|
|
|
import org.apache.commons.math3.linear.RealMatrix;
|
|
|
import org.apache.commons.math3.util.Pair;
|
|
|
|
|
|
-import static java.lang.Math.abs;
|
|
|
-import static java.lang.Math.max;
|
|
|
-import static java.lang.Math.min;
|
|
|
-import static java.lang.Math.sqrt;
|
|
|
-
|
|
|
/**
|
|
|
- * The Broyden–Fletcher–Goldfarb–Shanno (BFGS) algorithm is an iterative
|
|
|
- * method for solving unconstrained nonlinear optimization problems.
|
|
|
+ * The Broyden–Fletcher–Goldfarb–Shanno (BFGS) algorithm is an iterative method for solving unconstrained nonlinear
|
|
|
+ * optimization problems.
|
|
|
* <p>
|
|
|
- * The BFGS method belongs to quasi-Newton methods, a class of hill-climbing
|
|
|
- * optimization techniques that seek a stationary point of a (preferably
|
|
|
- * twice continuously differentiable) function. For such problems,
|
|
|
- * a necessary condition for optimality is that the gradient be zero.
|
|
|
- * Newton's method and the BFGS methods are not guaranteed to converge
|
|
|
- * unless the function has a quadratic Taylor expansion near an optimum.
|
|
|
- * However, BFGS has proven to have good performance even for non-smooth
|
|
|
- * optimizations.
|
|
|
+ * The BFGS method belongs to quasi-Newton methods, a class of hill-climbing optimization techniques that seek a
|
|
|
+ * stationary point of a (preferably twice continuously differentiable) function. For such problems, a necessary
|
|
|
+ * condition for optimality is that the gradient be zero. Newton's method and the BFGS methods are not guaranteed to
|
|
|
+ * converge unless the function has a quadratic Taylor expansion near an optimum. However, BFGS has proven to have good
|
|
|
+ * performance even for non-smooth optimizations.
|
|
|
* <p>
|
|
|
- * In quasi-Newton methods, the Hessian matrix of second derivatives is
|
|
|
- * not computed. Instead, the Hessian matrix is approximated using
|
|
|
- * updates specified by gradient evaluations (or approximate gradient
|
|
|
- * evaluations). Quasi-Newton methods are generalizations of the secant
|
|
|
- * method to find the root of the first derivative for multidimensional
|
|
|
- * problems. In multi-dimensional problems, the secant equation does not
|
|
|
- * specify a unique solution, and quasi-Newton methods differ in how they
|
|
|
- * constrain the solution. The BFGS method is one of the most popular
|
|
|
- * members of this class.
|
|
|
+ * In quasi-Newton methods, the Hessian matrix of second derivatives is not computed. Instead, the Hessian matrix is
|
|
|
+ * approximated using updates specified by gradient evaluations (or approximate gradient evaluations). Quasi-Newton
|
|
|
+ * methods are generalizations of the secant method to find the root of the first derivative for multidimensional
|
|
|
+ * problems. In multi-dimensional problems, the secant equation does not specify a unique solution, and quasi-Newton
|
|
|
+ * methods differ in how they constrain the solution. The BFGS method is one of the most popular members of this class.
|
|
|
* <p>
|
|
|
- * Like the original BFGS, the limited-memory BFGS (L-BFGS) uses an
|
|
|
- * estimation to the inverse Hessian matrix to steer its search
|
|
|
- * through variable space, but where BFGS stores a dense <code>n × n</code>
|
|
|
- * approximation to the inverse Hessian (<code>n</code> being the number of
|
|
|
- * variables in the problem), L-BFGS stores only a few vectors
|
|
|
- * that represent the approximation implicitly. Due to its resulting
|
|
|
- * linear memory requirement, the L-BFGS method is particularly well
|
|
|
- * suited for optimization problems with a large number of variables
|
|
|
- * (e.g., > 1000). Instead of the inverse Hessian <code>H_k</code>, L-BFGS
|
|
|
- * maintains * a history of the past <code>m</code> updates of the position
|
|
|
- * <code>x</code> and gradient <code>∇f(x)</code>, where generally the
|
|
|
- * history size <code>m</code> can be small (often <code>m < 10</code>).
|
|
|
- * These updates are used to implicitly do operations requiring the
|
|
|
- * <code>H_k</code>-vector product.
|
|
|
- *
|
|
|
+ * Like the original BFGS, the limited-memory BFGS (L-BFGS) uses an estimation to the inverse Hessian matrix to steer
|
|
|
+ * its search through variable space, but where BFGS stores a dense <code>n × n</code> approximation to the inverse
|
|
|
+ * Hessian (<code>n</code> being the number of variables in the problem), L-BFGS stores only a few vectors that
|
|
|
+ * represent the approximation implicitly. Due to its resulting linear memory requirement, the L-BFGS method is
|
|
|
+ * particularly well suited for optimization problems with a large number of variables (e.g., > 1000). Instead of the
|
|
|
+ * inverse Hessian <code>H_k</code>, L-BFGS maintains * a history of the past <code>m</code> updates of the position
|
|
|
+ * <code>x</code> and gradient <code>∇f(x)</code>, where generally the history size <code>m</code> can be small (often
|
|
|
+ * <code>m < 10</code>). These updates are used to implicitly do operations requiring the <code>H_k</code>-vector
|
|
|
+ * product.
|
|
|
* <h2>References</h2>
|
|
|
* <ol>
|
|
|
- * <li>Roger Fletcher. Practical methods of optimization.</li>
|
|
|
- * <li>D. Liu and J. Nocedal. On the limited memory BFGS method for large scale optimization. Mathematical Programming B 45 (1989) 503-528.</li>
|
|
|
- * <li>Richard H. Byrd, Peihuang Lu, Jorge Nocedal and Ciyou Zhu. A limited memory algorithm for bound constrained optimization.</li>
|
|
|
+ * <li>Roger Fletcher. Practical methods of optimization.</li>
|
|
|
+ * <li>D. Liu and J. Nocedal. On the limited memory BFGS method for large scale optimization. Mathematical Programming B
|
|
|
+ * 45 (1989) 503-528.</li>
|
|
|
+ * <li>Richard H. Byrd, Peihuang Lu, Jorge Nocedal and Ciyou Zhu. A limited memory algorithm for bound constrained
|
|
|
+ * optimization.</li>
|
|
|
* </ol>
|
|
|
- *
|
|
|
* @author Haifeng Li
|
|
|
*/
|
|
|
public class BFGS {
|
|
|
- //private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BFGS.class);
|
|
|
+ // private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BFGS.class);
|
|
|
/** A number close to zero, between machine epsilon and its square root. */
|
|
|
private static final double EPSILON = Double.valueOf(System.getProperty("smile.bfgs.epsilon", "1E-10"));
|
|
|
/** The convergence criterion on function value. */
|
|
|
@@ -99,57 +77,45 @@ public class BFGS {
|
|
|
private static final double STPMX = 100.0;
|
|
|
|
|
|
/**
|
|
|
- * Minimize a function along a search direction by find a step which satisfies
|
|
|
- * a sufficient decrease condition and a curvature condition.
|
|
|
+ * Minimize a function along a search direction by find a step which satisfies a sufficient decrease condition and a
|
|
|
+ * curvature condition.
|
|
|
* <p>
|
|
|
- * At each stage this function updates an interval of uncertainty with
|
|
|
- * endpoints <code>stx</code> and <code>sty</code>. The interval of
|
|
|
- * uncertainty is initially chosen so that it contains a
|
|
|
- * minimizer of the modified function
|
|
|
+ * At each stage this function updates an interval of uncertainty with endpoints <code>stx</code> and <code>sty</code>.
|
|
|
+ * The interval of uncertainty is initially chosen so that it contains a minimizer of the modified function
|
|
|
* <p>
|
|
|
+ *
|
|
|
* <pre>
|
|
|
* f(x+stp*s) - f(x) - ftol*stp*(gradf(x)'s).
|
|
|
* </pre>
|
|
|
- * If a step is obtained for which the modified function
|
|
|
- * has a nonpositive function value and nonnegative derivative,
|
|
|
- * then the interval of uncertainty is chosen so that it
|
|
|
- * contains a minimizer of <code>f(x+stp*s)</code>.
|
|
|
+ *
|
|
|
+ * If a step is obtained for which the modified function has a nonpositive function value and nonnegative derivative,
|
|
|
+ * then the interval of uncertainty is chosen so that it contains a minimizer of <code>f(x+stp*s)</code>.
|
|
|
* <p>
|
|
|
- * The algorithm is designed to find a step which satisfies
|
|
|
- * the sufficient decrease condition
|
|
|
+ * The algorithm is designed to find a step which satisfies the sufficient decrease condition
|
|
|
* <p>
|
|
|
+ *
|
|
|
* <pre>
|
|
|
* f(x+stp*s) <= f(X) + ftol*stp*(gradf(x)'s),
|
|
|
* </pre>
|
|
|
+ *
|
|
|
* and the curvature condition
|
|
|
* <p>
|
|
|
+ *
|
|
|
* <pre>
|
|
|
* abs(gradf(x+stp*s)'s)) <= gtol*abs(gradf(x)'s).
|
|
|
* </pre>
|
|
|
- * If <code>ftol</code> is less than <code>gtol</code> and if, for example,
|
|
|
- * the function is bounded below, then there is always a step which
|
|
|
- * satisfies both conditions. If no step can be found which satisfies both
|
|
|
- * conditions, then the algorithm usually stops when rounding
|
|
|
- * errors prevent further progress. In this case <code>stp</code> only
|
|
|
- * satisfies the sufficient decrease condition.
|
|
|
- *
|
|
|
+ *
|
|
|
+ * If <code>ftol</code> is less than <code>gtol</code> and if, for example, the function is bounded below, then there is
|
|
|
+ * always a step which satisfies both conditions. If no step can be found which satisfies both conditions, then the
|
|
|
+ * algorithm usually stops when rounding errors prevent further progress. In this case <code>stp</code> only satisfies
|
|
|
+ * the sufficient decrease condition.
|
|
|
* @param xold on input this contains the base point for the line search.
|
|
|
- *
|
|
|
- * @param fold on input this contains the value of the objective function
|
|
|
- * at <code>x</code>.
|
|
|
- *
|
|
|
- * @param g on input this contains the gradient of the objective function
|
|
|
- * at <code>x</code>.
|
|
|
- *
|
|
|
+ * @param fold on input this contains the value of the objective function at <code>x</code>.
|
|
|
+ * @param g on input this contains the gradient of the objective function at <code>x</code>.
|
|
|
* @param p the search direction.
|
|
|
- *
|
|
|
- * @param x on output, it contains <code>xold + γ*p</code>, where
|
|
|
- * γ > 0 is the step length.
|
|
|
- *
|
|
|
- * @param stpmax specify upper bound for the step in the line search so that
|
|
|
- * we do not try to evaluate the function in regions where it is
|
|
|
- * undefined or subject to overflow.
|
|
|
- *
|
|
|
+ * @param x on output, it contains <code>xold + γ*p</code>, where γ > 0 is the step length.
|
|
|
+ * @param stpmax specify upper bound for the step in the line search so that we do not try to evaluate the function in
|
|
|
+ * regions where it is undefined or subject to overflow.
|
|
|
* @return the new function value.
|
|
|
*/
|
|
|
private static double linesearch(MultivariateFunction func, double[] xold, double fold, double[] g, double[] p, double[] x, double stpmax) {
|
|
|
@@ -181,7 +147,8 @@ public class BFGS {
|
|
|
}
|
|
|
|
|
|
if (slope >= 0) {
|
|
|
- //throw new IllegalArgumentException("Line Search: the search direction is not a descent direction, which may be caused by roundoff problem.");
|
|
|
+ // throw new IllegalArgumentException("Line Search: the search direction is not a descent direction, which may be caused
|
|
|
+ // by roundoff problem.");
|
|
|
}
|
|
|
|
|
|
// Calculate minimum step.
|
|
|
@@ -252,34 +219,22 @@ public class BFGS {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * This method solves the bound constrained minimization problem
|
|
|
- * using the L-BFGS-B method. The L-BFGS-B algorithm extends L-BFGS
|
|
|
- * to handle simple box constraints on variables; that is, constraints
|
|
|
- * of the form li ≤ xi ≤ ui where li and ui are per-variable constant
|
|
|
- * lower and upper bounds, respectively (for each xi, either or both
|
|
|
- * bounds may be omitted). The method works by identifying fixed and
|
|
|
- * free variables at every step (using a simple gradient method),
|
|
|
- * and then using the L-BFGS method on the free variables only to
|
|
|
- * get higher accuracy, and then repeating the process.
|
|
|
- *
|
|
|
+ * This method solves the bound constrained minimization problem using the L-BFGS-B method. The L-BFGS-B algorithm
|
|
|
+ * extends L-BFGS to handle simple box constraints on variables; that is, constraints of the form li ≤ xi ≤ ui where li
|
|
|
+ * and ui are per-variable constant lower and upper bounds, respectively (for each xi, either or both bounds may be
|
|
|
+ * omitted). The method works by identifying fixed and free variables at every step (using a simple gradient method),
|
|
|
+ * and then using the L-BFGS method on the free variables only to get higher accuracy, and then repeating the process.
|
|
|
* @param func the function to be minimized.
|
|
|
- *
|
|
|
- * @param m the number of corrections used in the L-BFGS update.
|
|
|
- * Values of <code>m</code> less than 3 are not recommended;
|
|
|
- * large values of <code>m</code> will result in excessive
|
|
|
- * computing time. <code>3 <= m <= 7</code> is recommended.
|
|
|
- * A common choice for m is m = 5.
|
|
|
- *
|
|
|
- * @param x on initial entry this must be set by the user to the values
|
|
|
- * of the initial estimate of the solution vector. On exit with
|
|
|
- * <code>iflag = 0</code>, it contains the values of the variables
|
|
|
- * at the best point found (usually a solution).
|
|
|
- *
|
|
|
+ * @param m the number of corrections used in the L-BFGS update. Values of <code>m</code> less than 3 are not
|
|
|
+ * recommended; large values of <code>m</code> will result in excessive computing time. <code>3 <= m <= 7</code>
|
|
|
+ * is recommended. A common choice for m is m = 5.
|
|
|
+ * @param x on initial entry this must be set by the user to the values of the initial estimate of the solution vector.
|
|
|
+ * On exit with <code>iflag = 0</code>, it contains the values of the variables at the best point found (usually a
|
|
|
+ * solution).
|
|
|
* @param l the lower bound.
|
|
|
* @param u the upper bound.
|
|
|
* @param gtol the convergence tolerance on zeroing the gradient.
|
|
|
* @param maxIter the maximum number of iterations.
|
|
|
- *
|
|
|
* @return the minimum value of the function.
|
|
|
*/
|
|
|
public static double minimize(DifferentiableMultivariateFunction func, int m, double[] x, double[] l, double[] u, double gtol, int maxIter) {
|
|
|
@@ -318,7 +273,7 @@ public class BFGS {
|
|
|
double[] p = new double[n];
|
|
|
double[] g = new double[n];
|
|
|
double[] cauchy = new double[n];
|
|
|
- double f = func.g(x, g);
|
|
|
+ double f = func.g(x, g);
|
|
|
|
|
|
double[] x_old = new double[n];
|
|
|
double[] g_old = new double[n];
|
|
|
@@ -327,7 +282,7 @@ public class BFGS {
|
|
|
double stpmax = STPMX * max(norm(x), n);
|
|
|
|
|
|
for (int iter = 1; iter <= maxIter; iter++) {
|
|
|
- double f_old = f;
|
|
|
+ double f_old = f;
|
|
|
System.arraycopy(x, 0, x_old, 0, n);
|
|
|
System.arraycopy(g, 0, g_old, 0, n);
|
|
|
|
|
|
@@ -349,7 +304,7 @@ public class BFGS {
|
|
|
|
|
|
for (double xi : x) {
|
|
|
if (Double.isNaN(xi) || Double.isInfinite(xi)) {
|
|
|
- //logger.warn("L-BFGS-B: bad x produced by line search, return previous good x");
|
|
|
+ // logger.warn("L-BFGS-B: bad x produced by line search, return previous good x");
|
|
|
System.arraycopy(x_old, 0, x, 0, n);
|
|
|
return f_old;
|
|
|
}
|
|
|
@@ -358,18 +313,18 @@ public class BFGS {
|
|
|
// STEP 5: compute gradient update current guess and function information
|
|
|
f = func.g(x, g);
|
|
|
if (Double.isNaN(f) || Double.isInfinite(f)) {
|
|
|
- //logger.warn("L-BFGS-B: bad f(x) produced by line search, return previous good x");
|
|
|
+ // logger.warn("L-BFGS-B: bad f(x) produced by line search, return previous good x");
|
|
|
System.arraycopy(x_old, 0, x, 0, n);
|
|
|
return f_old;
|
|
|
}
|
|
|
|
|
|
if (gnorm(x, g, l, u) < gtol) {
|
|
|
- //logger.info(String.format("L-BFGS-B converges on gradient after %d iterations: %.5f", iter, f));
|
|
|
+ // logger.info(String.format("L-BFGS-B converges on gradient after %d iterations: %.5f", iter, f));
|
|
|
return f;
|
|
|
}
|
|
|
|
|
|
if (iter % 100 == 0) {
|
|
|
- //logger.info(String.format("L-BFGS-B: the function value after %3d iterations: %.5f", iter, f));
|
|
|
+ // logger.info(String.format("L-BFGS-B: the function value after %3d iterations: %.5f", iter, f));
|
|
|
}
|
|
|
|
|
|
// prepare for next iteration
|
|
|
@@ -384,8 +339,8 @@ public class BFGS {
|
|
|
double test = abs(sy);
|
|
|
if (test > EPSILON * yy) {
|
|
|
if (yHistory.size() >= m) {
|
|
|
- yHistory.remove (0);
|
|
|
- sHistory.remove (0);
|
|
|
+ yHistory.remove(0);
|
|
|
+ sHistory.remove(0);
|
|
|
}
|
|
|
|
|
|
yHistory.add(y);
|
|
|
@@ -395,8 +350,8 @@ public class BFGS {
|
|
|
if (iter <= m) {
|
|
|
Y = new Matrix(n, h);
|
|
|
S = new Matrix(n, h);
|
|
|
- W = new Matrix(n, 2*h);
|
|
|
- M = new Matrix(2*h, 2*h);
|
|
|
+ W = new Matrix(n, 2 * h);
|
|
|
+ M = new Matrix(2 * h, 2 * h);
|
|
|
}
|
|
|
|
|
|
// STEP 7
|
|
|
@@ -409,7 +364,7 @@ public class BFGS {
|
|
|
Y.set(i, j, yj[i]);
|
|
|
S.set(i, j, sj[i]);
|
|
|
W.set(i, j, yj[i]);
|
|
|
- W.set(i, h+j, sj[i] * theta);
|
|
|
+ W.set(i, h + j, sj[i] * theta);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -418,33 +373,34 @@ public class BFGS {
|
|
|
for (int j = 0; j < h; j++) {
|
|
|
M.set(j, j, -SY.get(j, j));
|
|
|
for (int i = 0; i <= j; i++) {
|
|
|
- M.set(h+i, j, 0.0);
|
|
|
- M.set(j, h+i, 0.0);
|
|
|
+ M.set(h + i, j, 0.0);
|
|
|
+ M.set(j, h + i, 0.0);
|
|
|
}
|
|
|
|
|
|
- for (int i = j+1; i < h; i++) {
|
|
|
- M.set(h+i, j, SY.get(i, j));
|
|
|
- M.set(j, h+i, SY.get(i, j));
|
|
|
+ for (int i = j + 1; i < h; i++) {
|
|
|
+ M.set(h + i, j, SY.get(i, j));
|
|
|
+ M.set(j, h + i, SY.get(i, j));
|
|
|
}
|
|
|
|
|
|
for (int i = 0; i < h; i++) {
|
|
|
- M.set(h+i, h+j, theta * SS.get(i, j));
|
|
|
+ M.set(h + i, h + j, theta * SS.get(i, j));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- //M.uplo(UPLO.LOWER);
|
|
|
+ // M.uplo(UPLO.LOWER);
|
|
|
M = M.inverse();
|
|
|
}
|
|
|
|
|
|
- //logger.debug("L-BFGS-B iteration {} moves from {} to {} where f(x) = {}", iter, Arrays.toString(x_old), Arrays.toString(x), f);
|
|
|
+ // logger.debug("L-BFGS-B iteration {} moves from {} to {} where f(x) = {}", iter, Arrays.toString(x_old),
|
|
|
+ // Arrays.toString(x), f);
|
|
|
|
|
|
if (abs(f_old - f) < TOLF) {
|
|
|
- //logger.info(String.format("L-BFGS-B converges on f(x) after %d iterations: %.5f", iter, f));
|
|
|
+ // logger.info(String.format("L-BFGS-B converges on f(x) after %d iterations: %.5f", iter, f));
|
|
|
return f;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- //logger.warn(String.format("L-BFGS-B reaches maximum %d iterations: %.5f", maxIter, f));
|
|
|
+ // logger.warn(String.format("L-BFGS-B reaches maximum %d iterations: %.5f", maxIter, f));
|
|
|
return f;
|
|
|
}
|
|
|
|
|
|
@@ -465,8 +421,8 @@ public class BFGS {
|
|
|
|
|
|
/**
|
|
|
* Algorithm CP: Computation of the Generalized Cauchy Point. See page 8.
|
|
|
- * @param x the parameter vector
|
|
|
- * @param g the gradient vector
|
|
|
+ * @param x the parameter vector
|
|
|
+ * @param g the gradient vector
|
|
|
*/
|
|
|
private static double[] cauchy(double[] x, double[] g, double[] cauchy, double[] l, double[] u, double theta, Matrix W, Matrix M) {
|
|
|
int n = x.length;
|
|
|
@@ -474,24 +430,24 @@ public class BFGS {
|
|
|
double[] d = new double[n];
|
|
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
- t[i] = g[i] == 0 ? Double.MAX_VALUE
|
|
|
- : (g[i] < 0 ? (x[i] - u[i]) / g[i]
|
|
|
- : (x[i] - l[i]) / g[i]);
|
|
|
- if (t[i] != 0.0) d[i] = -g[i];
|
|
|
+ t[i] = g[i] == 0 ? Double.MAX_VALUE : (g[i] < 0 ? (x[i] - u[i]) / g[i] : (x[i] - l[i]) / g[i]);
|
|
|
+ if (t[i] != 0.0)
|
|
|
+ d[i] = -g[i];
|
|
|
}
|
|
|
|
|
|
int[] index = sortWithIndex(t);
|
|
|
double[] p = W.tv(d);
|
|
|
double[] c = new double[p.length];
|
|
|
double fPrime = -dot(d, d);
|
|
|
- double fDoublePrime = max(-theta * fPrime - M.xAx(p), EPSILON);
|
|
|
- double f_dp_orig = fDoublePrime;
|
|
|
- double dt_min = -fPrime / fDoublePrime;
|
|
|
- double t_old = 0.0;
|
|
|
+ double fDoublePrime = max(-theta * fPrime - M.xAx(p), EPSILON);
|
|
|
+ double f_dp_orig = fDoublePrime;
|
|
|
+ double dt_min = -fPrime / fDoublePrime;
|
|
|
+ double t_old = 0.0;
|
|
|
|
|
|
int i = 0;
|
|
|
for (; i < n; i++) {
|
|
|
- if (t[index[i]] >= 0) break;
|
|
|
+ if (t[index[i]] >= 0)
|
|
|
+ break;
|
|
|
}
|
|
|
|
|
|
double dt = i < n ? t[i] : 0;
|
|
|
@@ -500,25 +456,24 @@ public class BFGS {
|
|
|
double tb = t[i];
|
|
|
dt = tb - t_old;
|
|
|
|
|
|
- cauchy[b] = d[b] > 0 ? u[b] :
|
|
|
- (d[b] < 0 ? l[b] : cauchy[b]);
|
|
|
+ cauchy[b] = d[b] > 0 ? u[b] : (d[b] < 0 ? l[b] : cauchy[b]);
|
|
|
double zb = cauchy[b] - x[b];
|
|
|
for (int j = 0; j < c.length; j++) {
|
|
|
c[j] += p[j] * dt;
|
|
|
}
|
|
|
|
|
|
double gb = g[b];
|
|
|
- double[] wbt = W.row(b);
|
|
|
- fPrime += dt * fDoublePrime + gb * gb + theta * gb * zb - gb * dot(wbt, M.mv(c));
|
|
|
+ double[] wbt = W.row(b);
|
|
|
+ fPrime += dt * fDoublePrime + gb * gb + theta * gb * zb - gb * dot(wbt, M.mv(c));
|
|
|
fDoublePrime -= theta * gb * gb + 2.0 * gb * dot(wbt, M.mv(p)) + gb * gb * M.xAx(wbt);
|
|
|
- fDoublePrime = max(fDoublePrime, EPSILON * f_dp_orig);
|
|
|
+ fDoublePrime = max(fDoublePrime, EPSILON * f_dp_orig);
|
|
|
for (int j = 0; j < p.length; j++) {
|
|
|
p[j] += wbt[j] * gb;
|
|
|
}
|
|
|
|
|
|
- d[b] = 0;
|
|
|
- dt_min = -fPrime / fDoublePrime;
|
|
|
- t_old = tb;
|
|
|
+ d[b] = 0;
|
|
|
+ dt_min = -fPrime / fDoublePrime;
|
|
|
+ t_old = tb;
|
|
|
}
|
|
|
|
|
|
dt_min = max(dt_min, 0.0);
|
|
|
@@ -538,13 +493,13 @@ public class BFGS {
|
|
|
|
|
|
/**
|
|
|
* Minimization of the subspace of free variables. See Section 5 on page 9.
|
|
|
- * @param x the parameter vector
|
|
|
- * @param g the gradient vector
|
|
|
- * @param cauchy the cauchy points
|
|
|
- * @param c vector obtained from gcp() used to initialize the subspace
|
|
|
- * minimization process
|
|
|
+ * @param x the parameter vector
|
|
|
+ * @param g the gradient vector
|
|
|
+ * @param cauchy the cauchy points
|
|
|
+ * @param c vector obtained from gcp() used to initialize the subspace minimization process
|
|
|
*/
|
|
|
- private static double[] subspaceMinimization(double[] x, double[] g, double[] cauchy, double[] c, double[] l, double[] u, double theta, Matrix W, Matrix M) {
|
|
|
+ private static double[] subspaceMinimization(double[] x, double[] g, double[] cauchy, double[] c, double[] l, double[] u, double theta, Matrix W,
|
|
|
+ Matrix M) {
|
|
|
int n = x.length;
|
|
|
double thetaInverse = 1.0 / theta;
|
|
|
ArrayList<Integer> freeVarIdx = new ArrayList<>();
|
|
|
@@ -572,7 +527,7 @@ public class BFGS {
|
|
|
}
|
|
|
|
|
|
Matrix WZ = W.row(freeVar);
|
|
|
- double[] v = M.mv(WZ.tv(r));
|
|
|
+ double[] v = M.mv(WZ.tv(r));
|
|
|
Matrix N = WZ.ata().mul(-thetaInverse);
|
|
|
N = M.mm(N);
|
|
|
int n1 = N.nrows();
|
|
|
@@ -590,7 +545,7 @@ public class BFGS {
|
|
|
du[i] = -thetaInverse * (r[i] + wzv[i] * thetaInverse);
|
|
|
}
|
|
|
double alphaStar = findAlpha(cauchy, du, l, u, freeVar);
|
|
|
- double[] dStar = new double[freeVarCount];
|
|
|
+ double[] dStar = new double[freeVarCount];
|
|
|
for (int i = 0; i < freeVarCount; i++) {
|
|
|
dStar[i] = du[i] * alphaStar;
|
|
|
}
|
|
|
@@ -605,9 +560,9 @@ public class BFGS {
|
|
|
|
|
|
/**
|
|
|
* Find the alpha* parameter, a positive scalar. See Equation 5.8 on page 11.
|
|
|
- * @param cauchy cauchy point
|
|
|
- * @param du intermediate results used to find alpha*
|
|
|
- @param freeVar the indices of free variable
|
|
|
+ * @param cauchy cauchy point
|
|
|
+ * @param du intermediate results used to find alpha*
|
|
|
+ * @param freeVar the indices of free variable
|
|
|
*/
|
|
|
private static double findAlpha(double[] cauchy, double[] du, double[] l, double[] u, int[] freeVar) {
|
|
|
double alphaStar = 1.0;
|
|
|
@@ -615,17 +570,16 @@ public class BFGS {
|
|
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
int fi = freeVar[i];
|
|
|
- alphaStar = du[i] > 0 ? min(alphaStar, (u[fi] - cauchy[fi]) / du[i])
|
|
|
- : min(alphaStar, (l[fi] - cauchy[fi]) / du[i]);
|
|
|
+ alphaStar = du[i] > 0 ? min(alphaStar, (u[fi] - cauchy[fi]) / du[i]) : min(alphaStar, (l[fi] - cauchy[fi]) / du[i]);
|
|
|
}
|
|
|
|
|
|
return alphaStar;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * Returns the infinity norm of gradient.
|
|
|
- * @param x the parameter vector
|
|
|
- * @param g the gradient vector
|
|
|
+ * Returns the infinity norm of gradient.
|
|
|
+ * @param x the parameter vector
|
|
|
+ * @param g the gradient vector
|
|
|
*/
|
|
|
private static double gnorm(double[] x, double[] g, double[] l, double[] u) {
|
|
|
double norm = 0.0;
|
|
|
@@ -633,8 +587,10 @@ public class BFGS {
|
|
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
double gi = g[i];
|
|
|
- if (gi < 0) gi = max(x[i] - u[i], gi);
|
|
|
- else gi = min(x[i] - l[i], gi);
|
|
|
+ if (gi < 0)
|
|
|
+ gi = max(x[i] - u[i], gi);
|
|
|
+ else
|
|
|
+ gi = min(x[i] - l[i], gi);
|
|
|
norm = max(norm, abs(gi));
|
|
|
}
|
|
|
|
|
|
@@ -643,14 +599,16 @@ public class BFGS {
|
|
|
|
|
|
/**
|
|
|
* Clamps the values of v to stay within the pre-defined bounds.
|
|
|
- * @param v the vector to be adjusted
|
|
|
+ * @param v the vector to be adjusted
|
|
|
*/
|
|
|
private static void clampToBound(double[] v, double[] l, double[] u) {
|
|
|
int n = v.length;
|
|
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
- if (v[i] > u[i]) v[i] = u[i];
|
|
|
- else if (v[i] < l[i]) v[i] = l[i];
|
|
|
+ if (v[i] > u[i])
|
|
|
+ v[i] = u[i];
|
|
|
+ else if (v[i] < l[i])
|
|
|
+ v[i] = l[i];
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -666,19 +624,17 @@ public class BFGS {
|
|
|
public interface DifferentiableMultivariateFunction extends MultivariateFunction {
|
|
|
/** A number close to zero, between machine epsilon and its square root. */
|
|
|
double EPSILON = Double.parseDouble(System.getProperty("smile.gradient.epsilon", "1E-8"));
|
|
|
-
|
|
|
+
|
|
|
/**
|
|
|
- * Computes the value and gradient at x. The default implementation
|
|
|
- * uses finite differences to calculate the gradient. When possible,
|
|
|
- * the subclass should compute the gradient analytically.
|
|
|
- *
|
|
|
+ * Computes the value and gradient at x. The default implementation uses finite differences to calculate the gradient.
|
|
|
+ * When possible, the subclass should compute the gradient analytically.
|
|
|
* @param x a real vector.
|
|
|
* @param gradient the output variable of gradient.
|
|
|
* @return the function value.
|
|
|
*/
|
|
|
default double g(double[] x, double[] gradient) {
|
|
|
double fx = f(x);
|
|
|
-
|
|
|
+
|
|
|
int n = x.length;
|
|
|
double[] xh = new double[n];
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
@@ -690,21 +646,19 @@ public class BFGS {
|
|
|
}
|
|
|
xh[i] = xi + h; // trick to reduce finite-precision error.
|
|
|
h = xh[i] - xi;
|
|
|
-
|
|
|
+
|
|
|
double fh = f(xh);
|
|
|
xh[i] = xi;
|
|
|
gradient[i] = (fh - fx) / h;
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
return fx;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
private static int[] sortWithIndex(double[] array) {
|
|
|
- List<Pair<Integer, Double>> sortedPairs = IntStream.range(0, array.length)
|
|
|
- .mapToObj(idx -> Pair.create(idx, array[idx]))
|
|
|
- .sorted(Comparator.comparingDouble(Pair::getValue))
|
|
|
- .collect(Collectors.toList());
|
|
|
+ List<Pair<Integer, Double>> sortedPairs = IntStream.range(0, array.length).mapToObj(idx -> Pair.create(idx, array[idx]))
|
|
|
+ .sorted(Comparator.comparingDouble(Pair::getValue)).collect(Collectors.toList());
|
|
|
double[] sortedDoubles = sortedPairs.stream().mapToDouble(Pair::getValue).toArray();
|
|
|
int[] sortedIndices = sortedPairs.stream().mapToInt(Pair::getKey).toArray();
|
|
|
System.arraycopy(sortedDoubles, 0, array, 0, array.length);
|
|
|
@@ -772,10 +726,10 @@ public class BFGS {
|
|
|
public Matrix ata() {
|
|
|
Matrix C = new Matrix(d.transpose().multiply(d));
|
|
|
// C.mm(TRANSPOSE, 1this, NO_TRANSPOSE, this);
|
|
|
- //C.uplo(LOWER);
|
|
|
+ // C.uplo(LOWER);
|
|
|
return C;
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
/**
|
|
|
* Returns {@code A[i,j]}.
|
|
|
* @param i the row index.
|
|
|
@@ -804,9 +758,8 @@ public class BFGS {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * Returns the quadratic form {@code x' * A * x}.
|
|
|
- * The left upper sub-matrix of A is used in the computation based
|
|
|
- * on the size of x.
|
|
|
+ * Returns the quadratic form {@code x' * A * x}. The left upper sub-matrix of A is used in the computation based on the
|
|
|
+ * size of x.
|
|
|
* @param x the vector.
|
|
|
* @return the quadratic form.
|
|
|
*/
|
|
|
@@ -843,10 +796,10 @@ public class BFGS {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * Returns the matrix of selected rows. Negative index -i means the i-th row from the end.
|
|
|
- * @param rows the row indices.
|
|
|
- * @return the sub-matrix.
|
|
|
- */
|
|
|
+ * Returns the matrix of selected rows. Negative index -i means the i-th row from the end.
|
|
|
+ * @param rows the row indices.
|
|
|
+ * @return the sub-matrix.
|
|
|
+ */
|
|
|
public Matrix row(int... rows) {
|
|
|
double[][] data = new double[rows.length][n];
|
|
|
|
|
|
@@ -877,6 +830,6 @@ public class BFGS {
|
|
|
public DecompositionSolver lu() {
|
|
|
return new LUDecomposition(d).getSolver();
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
}
|
|
|
}
|