Loading...
Searching...
No Matches
levenberg_marquardt_step.h
Go to the documentation of this file.
1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 Artificial Intelligence Techniques, S.L. and Roberto López González
3
4#pragma once
5
7
8#include <Eigen/QR>
9#include <algorithm>
10#include <cmath>
11#include <stdexcept>
12
13namespace opennn::detail
14{
15
16// Solve (curvature + damping*I) step = -gradient, then ask the caller whether
17// to accept it. See Madsen, Nielsen and Tingleff (2004), section 3.2, eq. (3.13).
18// Inputs stay immutable across trials; only an accepted trial may be committed
19// by the caller. OpenNN's multiplicative damping schedule is preserved.
20template<typename Accept>
21bool find_damped_step(const MatrixR& curvature, const VectorR& gradient,
22 float& damping, float factor, float lower, float upper,
23 Eigen::Ref<VectorR> step, Accept&& accept)
24{
25 if (!std::isfinite(factor) || factor <= 1.0f)
26 throw std::invalid_argument("LevenbergMarquardt: damping factor must be finite and greater than one.");
27
28 if (!curvature.allFinite() || !gradient.allFinite()) return false;
29
30 MatrixR system(curvature.rows(), curvature.cols());
31 for (;;)
32 {
33 system = curvature;
34 system.diagonal().array() += damping;
35 step = system.colPivHouseholderQr().solve(-gradient);
36
37 if (step.allFinite() && accept(step))
38 {
39 damping = std::clamp(damping / factor, lower, upper);
40 return true;
41 }
42
43 const float next = std::clamp(damping * factor, lower, upper);
44 const bool exhausted = next >= upper || next <= damping;
45 damping = next;
46 if (exhausted) return false;
47 }
48}
49
50}
Definition opennn_types.h:204
bool find_damped_step(const MatrixR &curvature, const VectorR &gradient, float &damping, float factor, float lower, float upper, Eigen::Ref< VectorR > step, Accept &&accept)
Definition levenberg_marquardt_step.h:21
Eigen::Matrix< float, Eigen::Dynamic, 1 > VectorR
Definition opennn_types.h:335
Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic, Layout > MatrixR
Definition opennn_types.h:331