17#ifndef __math_check_gradient_h__
18#define __math_check_gradient_h__
26 template <
class Function>
29 Eigen::Matrix<typename Function::value_type, Eigen::Dynamic, 1> x,
31 bool show_hessian =
false,
32 Eigen::Matrix<typename Function::value_type, Eigen::Dynamic, 1> conditioner = Eigen::Matrix<typename Function::value_type, Eigen::Dynamic, 1>())
35 const size_t N = function.size();
36 Eigen::Matrix<value_type, Eigen::Dynamic, 1> g (N);
38 CONSOLE (
"checking gradient for cost function over " +
str(N) +
39 " parameters of type " + DataType::from<value_type>().specifier());
41 CONSOLE (
"cost function suggests initial step size = " +
str(step_size));
42 CONSOLE (
"cost function suggests initial position at [ " +
str(g.transpose()) +
"]");
44 CONSOLE (
"checking gradient at position [ " +
str(x.transpose()) +
"]:");
45 Eigen::Matrix<value_type, Eigen::Dynamic, 1> g0 (N);
48 CONSOLE (
" gradient from cost function = [ " +
str(g0.transpose()) +
"]");
50 Eigen::Matrix<value_type, Eigen::Dynamic, 1> g_fd (N);
51 Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> hessian;
54 if (conditioner.size()){
55 assert (conditioner.size() == (ssize_t) N &&
"conditioner size must equal number of parameters");
56 for (
size_t n = 0; n < N; ++n)
57 conditioner[n] = std::sqrt(conditioner[n]);
61 for (
size_t n = 0; n < N; ++n) {
64 if (conditioner.size()){
65 assert (conditioner.size() == (ssize_t) N &&
"conditioner size must equal number of parameters");
66 inc *= conditioner[n];
72 if (conditioner.size())
73 g.cwiseProduct(conditioner);
79 g_fd[n] = (f1-f2) / (2.0*inc);
82 if (conditioner.size())
83 g.cwiseProduct(conditioner);
89 CONSOLE (
"gradient by central finite difference = [ " +
str(g_fd.transpose()) +
"]");
90 CONSOLE (
"normalised dot product = " +
str(g_fd.dot(g0) / g_fd.squaredNorm()));
93 hessian /= 4.0*increment;
94 for (
size_t j = 0; j < N; ++j) {
96 for (i = 0; i < j; ++i)
97 hessian(i,j) = hessian(j,i);
99 hessian(i,j) += hessian(j,i);
#define MAT(variable)
Prints a matrix name and in the following line its formatted value.
MR::default_type value_type
default_type condition_number(const M &data)
Eigen::Matrix< typename Function::value_type, Eigen::Dynamic, Eigen::Dynamic > check_function_gradient(Function &function, Eigen::Matrix< typename Function::value_type, Eigen::Dynamic, 1 > x, typename Function::value_type increment, bool show_hessian=false, Eigen::Matrix< typename Function::value_type, Eigen::Dynamic, 1 > conditioner=Eigen::Matrix< typename Function::value_type, Eigen::Dynamic, 1 >())
std::string str(const T &value, int precision=0)