SecondOrderTrustRegion.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. * NICE-Core - efficient algebra and computer vision methods
  3. * - liboptimization - An optimization/template for new NICE libraries
  4. * See file License for license information.
  5. */
  6. /*****************************************************************************/
  7. #include "core/optimization/gradientBased/SecondOrderTrustRegion.h"
  8. #ifdef NICE_USELIB_LINAL
  9. #include <LinAl/linal.h>
  10. #include <LinAl/algorithms.h>
  11. #endif
  12. #include <core/basics/Exception.h>
  13. #include <core/basics/Log.h>
  14. namespace NICE {
  15. SecondOrderTrustRegion::~SecondOrderTrustRegion() {
  16. }
  17. #ifdef NICE_USELIB_LINAL
  18. typedef LinAl::VectorCC<double> LinAlVector;
  19. typedef LinAl::MatrixCF<double> LinAlMatrix;
  20. /**
  21. * assume input and output to be quadratic and of same size.
  22. * also assume them to be symmetric
  23. * (only upper (?) triangular matrix will be used).
  24. * Exception, if not positive (semi?) definite
  25. */
  26. void choleskyDecompose(const LinAlMatrix& input, LinAlMatrix& output) {
  27. // FIXME checks missing (quadratic, same size)
  28. const int size = input.rows();
  29. int i,j,k;
  30. double sum;
  31. for (i=0;i<size;i++) {
  32. bool divide=true;
  33. for (j=0;j<i;j++) output(j,i)=0.0;
  34. for (;j<size;j++) {
  35. sum=input(i,j);
  36. for (k=i-1;k>=0;k--) sum -= output(i,k)*output(j,k);
  37. if (i == j) {
  38. // The following applies if A, with rounding errors, is not positive definite
  39. if (isZero(sum, 1e-16)) {
  40. output(i,i)=0.0;
  41. divide=false;
  42. } else if (sum<0.0) {
  43. // input is (numerically) not positive definite.
  44. fthrow(Exception, "Choloskey decomposition failed." << sum);
  45. }
  46. output(i,i)=sqrt(sum);
  47. } else {
  48. if (!divide) output(j,i)=0.0;
  49. else output(j,i)=sum/output(i,i);
  50. }
  51. }
  52. }
  53. }
  54. /**
  55. * Compute the inner product of \c v1 and \c v2.
  56. * @param v1 First parameter vector
  57. * @param v2 Second parameter vector
  58. * @return The inner product of \c v1 and \c v2
  59. */
  60. inline double dotProduct(const LinAlVector& v1,
  61. const LinAlVector& v2) {
  62. double result = 0.0;
  63. for (int i = 0; i < v1.rows(); i++) {
  64. result += v1(i) * v2(i);
  65. }
  66. return result;
  67. }
  68. /**
  69. * Compute the squared Euclidian norm of vector \c v.
  70. * @param v Parameter vector
  71. * @return The squared Euclidian norm of \c v
  72. */
  73. inline double normSquared(const LinAlVector& v) {
  74. double result = 0.0;
  75. for (int i = 0; i < v.rows(); i++) {
  76. const double entry = v(i);
  77. result += entry * entry;
  78. }
  79. return result;
  80. }
  81. /**
  82. * Compute the Euclidian norm of vector \c v.
  83. * @copydoc normSquared()
  84. */
  85. inline double norm(const LinAlVector& v) {
  86. return sqrt(normSquared(v));
  87. }
  88. /**
  89. * Compute \f$\mathrm{v1}^T \cdot \mathrm{ma} \cdot \mathrm{v2}\f$.
  90. * @param v1 First vector
  91. * @param ma Matrix
  92. * @param v2 Second vector
  93. * @return \f$\mathrm{v1}^T \cdot \mathrm{ma} \cdot \mathrm{v2}\f$
  94. */
  95. inline double productVMV(const LinAlVector& v1,
  96. const LinAlMatrix& ma,
  97. const LinAlVector& v2) {
  98. double result = 0.0;
  99. for (int i = 0; i < ma.rows(); i++) {
  100. double productEntry = 0.0;
  101. for (int j = 0; j < ma.cols(); j++) {
  102. productEntry += ma(i, j) * v2(j);
  103. }
  104. result += v1(i) * productEntry;
  105. }
  106. return result;
  107. }
  108. /**
  109. * Compute \f$\mathrm{v1}^T \cdot \mathrm{ma} \cdot \mathrm{v2}\f$.
  110. * @param v1 First vector
  111. * @param ma Matrix
  112. * @param v2 Second vector
  113. * @return \f$\mathrm{v1}^T \cdot \mathrm{ma} \cdot \mathrm{v2}\f$
  114. */
  115. inline double productVMV(const Vector& v1,
  116. const Matrix& ma,
  117. const Vector& v2) {
  118. double result = 0.0;
  119. for (unsigned int i = 0; i < ma.rows(); i++) {
  120. double productEntry = 0.0;
  121. for (unsigned int j = 0; j < ma.cols(); j++) {
  122. productEntry += ma(i, j) * v2[j];
  123. }
  124. result += v1[i] * productEntry;
  125. }
  126. return result;
  127. }
  128. #endif
  129. void SecondOrderTrustRegion::doOptimize(OptimizationProblemSecond& problem) {
  130. #ifdef NICE_USELIB_LINAL
  131. bool previousStepSuccessful = true;
  132. double previousError = problem.objective();
  133. problem.computeGradientAndHessian();
  134. double delta = computeInitialDelta(problem.gradientCached(), problem.hessianCached());
  135. double normOldPosition = 0.0;
  136. // iterate
  137. for (int iteration = 0; iteration < maxIterations; iteration++) {
  138. // Log::debug() << "iteration, objective: " << iteration << ", "
  139. // << problem.objective() << std::endl;
  140. if (previousStepSuccessful && iteration > 0) {
  141. problem.computeGradientAndHessian();
  142. }
  143. // gradient-norm stopping condition
  144. if (problem.gradientNormCached() < epsilonG) {
  145. Log::debug() << "SecondOrderTrustRegion stopped: gradientNorm "
  146. << iteration << std::endl;
  147. break;
  148. }
  149. LinAlVector gradient(problem.gradientCached().linalCol());
  150. LinAlVector negativeGradient(gradient);
  151. negativeGradient.multiply(-1.0);
  152. double lambda;
  153. int lambdaMinIndex = -1;
  154. // FIXME will this copy the matrix? no copy needed here!
  155. LinAlMatrix hessian(problem.hessianCached().linal());
  156. LinAlMatrix l(hessian);
  157. try {
  158. //l.CHdecompose(); // FIXME
  159. choleskyDecompose(hessian, l);
  160. lambda = 0.0;
  161. } catch (...) { //(LinAl::BLException& e) { // FIXME
  162. const LinAlVector& eigenValuesHessian = LinAl::eigensym(hessian);
  163. // find smallest eigenvalue
  164. lambda = std::numeric_limits<double>::infinity();
  165. for (unsigned int i = 0; i < problem.dimension(); i++) {
  166. const double eigenValue = eigenValuesHessian(i);
  167. if (eigenValue < lambda) {
  168. lambda = eigenValue;
  169. lambdaMinIndex = i;
  170. }
  171. }
  172. const double originalLambda = lambda;
  173. lambda = -lambda * (1.0 + epsilonLambda);
  174. l = hessian;
  175. for (unsigned int i = 0; i < problem.dimension(); i++) {
  176. l(i, i) += lambda;
  177. }
  178. try {
  179. //l.CHdecompose(); // FIXME
  180. LinAlMatrix temp(l);
  181. choleskyDecompose(temp, l);
  182. } catch (...) { // LinAl::BLException& e) { // FIXME
  183. /*
  184. * Cholesky factorization failed, which should theortically not be
  185. * possible (can still happen due to numeric problems,
  186. * also note that there seems to be a bug in CHdecompose()).
  187. * Try a really great lambda as last attempt.
  188. */
  189. // lambda = -originalLambda * (1.0 + epsilonLambda * 100.0)
  190. // + 2.0 * epsilonM;
  191. lambda = fabs(originalLambda) * (1.0 + epsilonLambda * 1E5)
  192. + 1E3 * epsilonM;
  193. // lambda = fabs(originalLambda);// * 15.0;
  194. l = hessian;
  195. for (unsigned int i = 0; i < problem.dimension(); i++) {
  196. l(i, i) += lambda;
  197. }
  198. try {
  199. //l.CHdecompose(); // FIXME
  200. LinAlMatrix temp(l);
  201. choleskyDecompose(temp, l);
  202. } catch (...) { // (LinAl::BLException& e) { // FIXME
  203. // Cholesky factorization failed again, give up.
  204. l = hessian;
  205. for (unsigned int i = 0; i < problem.dimension(); i++) {
  206. l(i, i) += lambda;
  207. }
  208. const LinAlVector& eigenValuesL = LinAl::eigensym(l);
  209. Log::detail()
  210. << "l.CHdecompose: exception" << std::endl
  211. //<< e.what() << std::endl // FIXME
  212. << "lambda=" << lambda << std::endl
  213. << "l" << std::endl << l
  214. << "hessian" << std::endl << hessian
  215. << "gradient" << std::endl << gradient
  216. << "eigenvalues hessian" << std::endl << eigenValuesHessian
  217. << "eigenvalues l" << std::endl << eigenValuesL
  218. << std::endl;
  219. return;
  220. }
  221. }
  222. }
  223. // FIXME will the copy the vector? copy is needed here
  224. LinAlVector step(negativeGradient);
  225. l.CHsubstitute(step);
  226. double normStepSquared = normSquared(step);
  227. double normStep = sqrt(normStepSquared);
  228. // exact: if normStep <= delta
  229. if (normStep - delta <= tolerance) {
  230. // exact: if lambda == 0 || normStep == delta
  231. if (std::fabs(lambda) < tolerance
  232. || std::fabs(normStep - delta) < tolerance) {
  233. // done
  234. } else {
  235. LinAlMatrix eigenVectors(problem.dimension(), problem.dimension());
  236. eigensym(hessian, eigenVectors);
  237. double a = 0.0;
  238. double b = 0.0;
  239. double c = 0.0;
  240. for (unsigned int i = 0; i < problem.dimension(); i++) {
  241. const double ui = eigenVectors(i, lambdaMinIndex);
  242. const double si = step(i);
  243. a += ui * ui;
  244. b += si * ui;
  245. c += si * si;
  246. }
  247. b *= 2.0;
  248. c -= delta * delta;
  249. const double sq = sqrt(b * b - 4.0 * a * c);
  250. const double root1 = 0.5 * (-b + sq) / a;
  251. const double root2 = 0.5 * (-b - sq) / a;
  252. LinAlVector step1(step);
  253. LinAlVector step2(step);
  254. for (unsigned int i = 0; i < problem.dimension(); i++) {
  255. step1(i) += root1 * eigenVectors(i, lambdaMinIndex);
  256. step2(i) += root2 * eigenVectors(i, lambdaMinIndex);
  257. }
  258. const double psi1
  259. = dotProduct(gradient, step1)
  260. + 0.5 * productVMV(step1, hessian, step1);
  261. const double psi2
  262. = dotProduct(gradient, step2)
  263. + 0.5 * productVMV(step2, hessian, step2);
  264. if (psi1 < psi2) {
  265. step = step1;
  266. } else {
  267. step = step2;
  268. }
  269. }
  270. } else {
  271. for (unsigned int subIteration = 0;
  272. subIteration < maxSubIterations;
  273. subIteration++) {
  274. if (std::fabs(normStep - delta) <= kappa * delta) {
  275. break;
  276. }
  277. // NOTE specialized algorithm may be more effifient than solvelineq
  278. // (l is lower triangle!)
  279. // Only lower triangle values of l are valid (other implicitly = 0.0),
  280. // but solvelineq doesn't know that -> explicitly set to 0.0
  281. for (int i = 0; i < l.rows(); i++) {
  282. for (int j = i + 1; j < l.cols(); j++) {
  283. l(i, j) = 0.0;
  284. }
  285. }
  286. LinAlVector y(step.size());
  287. try {
  288. y = solvelineq(l, step);
  289. } catch (LinAl::Exception& e) {
  290. // FIXME if we end up here, something is pretty wrong!
  291. // give up the whole thing
  292. Log::debug() << "SecondOrderTrustRegion stopped: solvelineq failed "
  293. << iteration << std::endl;
  294. return;
  295. }
  296. lambda += (normStep - delta) / delta
  297. * normStepSquared / normSquared(y);
  298. l = hessian;
  299. for (unsigned int i = 0; i < problem.dimension(); i++) {
  300. l(i, i) += lambda;
  301. }
  302. try {
  303. //l.CHdecompose(); // FIXME
  304. LinAlMatrix temp(l);
  305. choleskyDecompose(temp, l);
  306. } catch (...) { // (LinAl::BLException& e) { // FIXME
  307. Log::detail()
  308. << "l.CHdecompose: exception" << std::endl
  309. // << e.what() << std::endl // FIXME
  310. << "lambda=" << lambda << std::endl
  311. << "l" << std::endl << l
  312. << std::endl;
  313. return;
  314. }
  315. step = negativeGradient;
  316. l.CHsubstitute(step);
  317. normStepSquared = normSquared(step);
  318. normStep = sqrt(normStepSquared);
  319. }
  320. }
  321. // computation of step is complete, convert to NICE::Vector
  322. Vector stepLimun(step);
  323. // minimal change stopping condition
  324. if (changeIsMinimal(stepLimun, problem.position())) {
  325. Log::debug() << "SecondOrderTrustRegion stopped: change is minimal "
  326. << iteration << std::endl;
  327. break;
  328. }
  329. if (previousStepSuccessful) {
  330. normOldPosition = problem.position().normL2();
  331. }
  332. // set new region parameters (to be verified later)
  333. problem.applyStep(stepLimun);
  334. // compute reduction rate
  335. const double newError = problem.objective();
  336. //Log::debug() << "newError: " << newError << std::endl;
  337. const double errorReduction = newError - previousError;
  338. const double psi = problem.gradientCached().scalarProduct(stepLimun)
  339. + 0.5 * productVMV(step, hessian, step);
  340. double rho;
  341. if (std::fabs(psi) <= epsilonRho
  342. && std::fabs(errorReduction) <= epsilonRho) {
  343. rho = 1.0;
  344. } else {
  345. rho = errorReduction / psi;
  346. }
  347. // NOTE psi and errorReduction checks added to the algorithm
  348. // described in Ferid Bajramovic's Diplomarbeit
  349. if (rho < eta1 || psi >= 0.0 || errorReduction > 0.0) {
  350. previousStepSuccessful = false;
  351. problem.unapplyStep(stepLimun);
  352. delta = alpha2 * normStep;
  353. } else {
  354. previousStepSuccessful = true;
  355. previousError = newError;
  356. if (rho >= eta2) {
  357. const double newDelta = alpha1 * normStep;
  358. if (newDelta > delta) {
  359. delta = newDelta;
  360. }
  361. } // else: don't change delta
  362. }
  363. // delta stopping condition
  364. if (delta < epsilonDelta * normOldPosition) {
  365. Log::debug() << "SecondOrderTrustRegion stopped: delta too small "
  366. << iteration << std::endl;
  367. break;
  368. }
  369. }
  370. #else // no linal
  371. fthrow(Exception,
  372. "SecondOrderTrustRegion needs LinAl. Please recompile with LinAl");
  373. #endif
  374. }
  375. /*
  376. void SecondOrderTrustRegion::doOptimizeFirst(OptimizationProblemFirst& problem) {
  377. bool previousStepSuccessful = true;
  378. double previousError = problem.objective();
  379. problem.computeGradient();
  380. double delta = computeInitialDelta(problem.gradientNorm());
  381. double normOldPosition = 0.0;
  382. // iterate
  383. for (int iteration = 0; iteration < maxIterations; iteration++) {
  384. if (iteration > 0) {
  385. problem.computeGradient();
  386. }
  387. // gradient-norm stopping condition
  388. if (problem.gradientNorm() < epsilonG) {
  389. break;
  390. }
  391. // compute step
  392. Vector step(problem.gradient());
  393. step /= (-delta / problem.gradientNorm());
  394. // minimal change stopping condition
  395. if (changeIsMinimal(step, problem)) {
  396. break;
  397. }
  398. if (previousStepSuccessful) {
  399. normOldPosition = problem.position().normL2();
  400. }
  401. // set new region parameters (to be verified later)
  402. problem.applyStep(step);
  403. // compute reduction rate
  404. const double newError = problem.objective();
  405. //Log::debug() << "newError: " << newError << std::endl;
  406. const double errorReduction = newError - previousError;
  407. const double psi = problem.gradient().scalarProduct(step);
  408. double rho;
  409. if (std::fabs(psi) <= epsilonRho
  410. && std::fabs(errorReduction) <= epsilonRho) {
  411. rho = 1.0;
  412. } else {
  413. rho = errorReduction / psi;
  414. }
  415. // NOTE psi check should not really be needed
  416. if (rho < eta1 || psi >= 0.0) {
  417. previousStepSuccessful = false;
  418. problem.unapplyStep(step);
  419. delta = alpha2 * step.normL2();
  420. } else {
  421. previousStepSuccessful = true;
  422. previousError = newError;
  423. if (rho >= eta2) {
  424. const double newDelta = alpha1 * step.normL2();
  425. if (newDelta > delta) {
  426. delta = newDelta;
  427. }
  428. } // else: don't change delta
  429. }
  430. // delta stopping condition
  431. if (delta < epsilonDelta * normOldPosition) {
  432. break;
  433. }
  434. }
  435. }
  436. */
  437. double SecondOrderTrustRegion::computeInitialDelta(
  438. const Vector& gradient,
  439. const Matrix& hessian) {
  440. #ifdef NICE_USELIB_LINAL
  441. const double norm = gradient.normL2();
  442. const double gHg = productVMV(gradient, hessian, gradient);
  443. double result;
  444. if (isZero(norm)) {
  445. result = 1.0;
  446. } else if (isZero(gHg) || gHg < 0) {
  447. result = norm / 10.0;
  448. } else {
  449. result = norm * norm / gHg;
  450. }
  451. if (result < deltaMin) {
  452. result = deltaMin;
  453. }
  454. return result;
  455. #else
  456. fthrow(Exception,
  457. "SecondOrderTrustRegion needs LinAl. Please recompile with LinAl");
  458. #endif
  459. }
  460. }; // namespace NICE