Loading...
Searching...
No Matches
ScalarHyperparameterFit.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
16
17#ifndef GPR_BO_SCALAR_HYPERPARAMETER_FIT_H_
18#define GPR_BO_SCALAR_HYPERPARAMETER_FIT_H_
19
20#include <Eigen/Dense>
21#include <cmath>
22#include <cstdint>
23#include <limits>
24#include <stdexcept>
25#include <vector>
26
28#include "gpr/linalg/Backend.h"
29
30namespace gpr {
31namespace bo {
32
36 Eigen::VectorXd length_scales;
37 double signal_variance = 1.0;
40 double noise_variance = 0.0;
41};
42
46 Eigen::MatrixXd x;
47 Eigen::VectorXd y;
50 Eigen::VectorXd noise_variances;
52 Eigen::MatrixXd basis;
56 std::vector<bool> categorical;
57};
58
61inline Eigen::Index scalarParameterCount(const ScalarLikelihoodData& data)
62{
63 return data.x.cols() + 1 + (data.noise_variances.size() == 0 ? 1 : 0);
64}
65
66namespace detail {
67
68inline void requireLikelihoodInputs(const ScalarLikelihoodData& data,
69 const ScalarHyperparameters& hyper)
70{
71 const Eigen::Index n = data.x.rows();
72 if (n == 0 || data.x.cols() == 0 || data.y.size() != n) {
73 throw std::invalid_argument("likelihood observations are invalid");
74 }
75 if (data.noise_variances.size() != 0 && data.noise_variances.size() != n) {
76 throw std::invalid_argument(
77 "observation noise count differs from observations");
78 }
79 if (data.basis.cols() != 0 && data.basis.rows() != n) {
80 throw std::invalid_argument("mean basis rows differ from observations");
81 }
82 if (hyper.length_scales.size() != data.x.cols()) {
83 throw std::invalid_argument("length scales do not match the vector");
84 }
85 if (!data.categorical.empty() &&
86 static_cast<Eigen::Index>(data.categorical.size()) != data.x.cols()) {
87 throw std::invalid_argument(
88 "categorical flags do not match the length scales");
89 }
90 for (Eigen::Index dim = 0; dim < hyper.length_scales.size(); ++dim) {
91 if (!(hyper.length_scales[dim] > 0.0) ||
92 !std::isfinite(hyper.length_scales[dim])) {
93 throw std::invalid_argument("length scale must be positive");
94 }
95 }
96 if (!(hyper.signal_variance > 0.0) ||
97 !std::isfinite(hyper.signal_variance)) {
98 throw std::invalid_argument("signal variance must be positive");
99 }
100 if (data.noise_variances.size() == 0 &&
101 (!(hyper.noise_variance >= 0.0) ||
102 !std::isfinite(hyper.noise_variance))) {
103 throw std::invalid_argument("noise variance must be non-negative");
104 }
105}
106
107} // namespace detail
108
125 const ScalarHyperparameters& hyper,
126 Eigen::VectorXd* gradient = nullptr)
127{
128 detail::requireLikelihoodInputs(data, hyper);
129 const Eigen::Index n = data.x.rows();
130 const Eigen::Index dimension = data.x.cols();
131 const Eigen::Index basis_count = data.basis.cols();
132 const bool shared_noise = data.noise_variances.size() == 0;
133 const double failed = -std::numeric_limits<double>::infinity();
134 const RadialShape radial(data.radial, hyper.signal_variance);
135
136 // Separation of rows i and j on one axis, in length-scale units.
137 auto scaledDelta = [&](Eigen::Index i, Eigen::Index j, Eigen::Index dim) {
138 const double delta =
139 !data.categorical.empty() &&
140 data.categorical[static_cast<std::size_t>(dim)]
141 ? (data.x(i, dim) != data.x(j, dim) ? 1.0 : 0.0)
142 : data.x(i, dim) - data.x(j, dim);
143 return delta / hyper.length_scales[dim];
144 };
145 auto squaredDistance = [&](Eigen::Index i, Eigen::Index j) {
146 double squared = 0.0;
147 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
148 const double scaled = scaledDelta(i, j, dim);
149 squared += scaled * scaled;
150 }
151 return squared;
152 };
153
154 EigenMatrix signal(n, n);
155 for (Eigen::Index j = 0; j < n; ++j) {
156 for (Eigen::Index i = j; i < n; ++i) {
157 const double value = radial(squaredDistance(i, j));
158 signal(i, j) = value;
159 signal(j, i) = value;
160 }
161 }
162 EigenMatrix covariance = signal;
163 for (Eigen::Index i = 0; i < n; ++i) {
164 covariance(i, i) +=
165 shared_noise ? hyper.noise_variance : data.noise_variances[i];
166 }
167 EigenMatrix factor;
168 if (!covariance.allFinite() || !gpr::linalg::cholesky(covariance, factor)) {
169 return failed;
170 }
171 const EigenMatrix identity = EigenMatrix::Identity(n, n);
172 // P starts as K^-1 and loses the span of the basis below.
174 factor, gpr::linalg::forward_solve_mat(factor, identity));
175 projector = 0.5 * (projector + projector.transpose()).eval();
176 double basis_log_determinant = 0.0;
177 if (basis_count > 0) {
178 const Eigen::MatrixXd precision_basis = projector * data.basis;
179 Eigen::MatrixXd information = data.basis.transpose() * precision_basis;
180 information = 0.5 * (information + information.transpose()).eval();
181 const Eigen::LLT<Eigen::MatrixXd> information_factor(information);
182 if (information_factor.info() != Eigen::Success) return failed;
183 const Eigen::MatrixXd lower = information_factor.matrixL();
184 basis_log_determinant = 2.0 * lower.diagonal().array().log().sum();
185 projector -= precision_basis *
186 information_factor.solve(precision_basis.transpose());
187 }
188 const Eigen::VectorXd alpha = projector * data.y;
189 const double two_pi = 2.0 * std::acos(-1.0);
190 const double value =
191 -0.5 * data.y.dot(alpha) - gpr::linalg::log_det_cholesky(factor) -
192 0.5 * basis_log_determinant -
193 0.5 * static_cast<double>(n - basis_count) * std::log(two_pi);
194 if (!std::isfinite(value)) return failed;
195 if (gradient == nullptr) return value;
196
197 // weight = a a^T - P, so each derivative is 1/2 sum_ij weight_ij dK_ij.
198 const EigenMatrix weight = alpha * alpha.transpose() - projector;
199 gradient->setZero(scalarParameterCount(data));
200 for (Eigen::Index j = 0; j < n; ++j) {
201 for (Eigen::Index i = j + 1; i < n; ++i) {
202 const double slope = radial.derivative(squaredDistance(i, j));
203 for (Eigen::Index dim = 0; dim < dimension; ++dim) {
204 const double scaled = scaledDelta(i, j, dim);
205 // d r^2 / d log(l_dim) = -2 (delta_dim / l_dim)^2, and the
206 // pair (i, j) appears twice in the symmetric sum.
207 (*gradient)[dim] +=
208 weight(i, j) * slope * (-2.0 * scaled * scaled);
209 }
210 }
211 }
212 (*gradient)[dimension] = 0.5 * weight.cwiseProduct(signal).sum();
213 if (shared_noise) {
214 (*gradient)[dimension + 1] =
215 0.5 * hyper.noise_variance * weight.diagonal().sum();
216 }
217 return value;
218}
219
223 Eigen::VectorXd length_scale_lower;
224 Eigen::VectorXd length_scale_upper;
229};
230
235 int starts = 8;
236 int max_iterations = 200;
238 double tolerance = 1e-6;
239 std::uint64_t seed = 0x5ca1ab1eULL;
241};
242
246 double log_marginal_likelihood = -std::numeric_limits<double>::infinity();
247 int starts = 0;
251 int evaluations = 0;
252};
253
263
278 const ScalarHyperparameters& initial,
279 const ScalarFitConfig& config = {});
280
281} // namespace bo
282} // namespace gpr
283
284#endif // GPR_BO_SCALAR_HYPERPARAMETER_FIT_H_
Linear algebra abstraction layer for GPR hot-path operations.
Stationary scalar covariance: a radial function of a squared distance.
One of SquaredExponential, Matern32 and Matern52 behind a tag.
double derivative(double squared_distance) const
Right-hand derivative of operator() with respect to its argument.
RadialKind
Radial shape of a stationary kernel, selected at run time.
ScalarFitBounds defaultScalarFitBounds(const ScalarLikelihoodData &data)
Default box of the fit, from the spread of the observations.
Eigen::Index scalarParameterCount(const ScalarLikelihoodData &data)
Number of fitted parameters: the length scales, the signal variance and, without per-row variances,...
double scalarLogMarginalLikelihood(const ScalarLikelihoodData &data, const ScalarHyperparameters &hyper, Eigen::VectorXd *gradient=nullptr)
Log marginal likelihood log p(y | X, theta) and its gradient.
ScalarFitResult fitScalarHyperparameters(const ScalarLikelihoodData &data, const ScalarHyperparameters &initial, const ScalarFitConfig &config)
Maximize the log marginal likelihood over the hyperparameters.
EigenMatrix back_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L,...
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
double log_det_cholesky(const EigenMatrix &L)
Half log-determinant from Cholesky factor.
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
Cholesky decomposition (LAPACK equivalent: dpotrf).
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Box of the fit in natural units. An empty vector or a non-positive scalar selects the default of defa...
Settings of fitScalarHyperparameters().
double tolerance
Gradient-norm tolerance of the L-BFGS runs.
Result of fitScalarHyperparameters().
ScalarHyperparameters hyperparameters
int evaluations
Likelihood evaluations summed over the starts.
int converged_starts
Starts whose L-BFGS run met its tolerance.
Hyperparameters of a stationary scalar GP.
Eigen::VectorXd length_scales
One length scale per axis.
Observations the marginal likelihood is evaluated on.
Eigen::MatrixXd basis
Row i is phi(x_i)^T of the mean basis. Zero columns: zero mean.
Eigen::MatrixXd x
Row i is the parameter vector of observation i.