Loading...
Searching...
No Matches
BayesianModelAveraging.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
6
7#include <algorithm>
8#include <cmath>
9#include <exception>
10#include <stdexcept>
11
13#ifdef USE_OPENMP
14#include <omp.h>
15#endif
16
17namespace gpr {
18
19void BayesianModelAveraging::setGrid(double log_ls_min, double log_ls_max,
20 int n_ls, double log_noise_min,
21 double log_noise_max, int n_noise)
22{
23 if (n_ls < 2 || n_noise < 2 || !std::isfinite(log_ls_min) ||
24 !std::isfinite(log_ls_max) || !std::isfinite(log_noise_min) ||
25 !std::isfinite(log_noise_max) || log_ls_min > log_ls_max ||
26 log_noise_min > log_noise_max) {
27 throw std::invalid_argument("invalid model averaging grid");
28 }
29 log_ls_grid_.resize(n_ls);
30 for (int i = 0; i < n_ls; ++i) {
31 log_ls_grid_[i] =
32 log_ls_min + (log_ls_max - log_ls_min) * i / (n_ls - 1);
33 }
34
35 log_noise_grid_.resize(n_noise);
36 for (int i = 0; i < n_noise; ++i) {
37 log_noise_grid_[i] =
38 log_noise_min + (log_noise_max - log_noise_min) * i / (n_noise - 1);
39 }
40
41 weights_.clear();
42 grid_params_.clear();
43 for (double log_ls: log_ls_grid_) {
44 for (double log_noise: log_noise_grid_) {
45 grid_params_.emplace_back(log_ls, log_noise);
46 }
47 }
48}
49
50void BayesianModelAveraging::fit(const Eigen::VectorXd& y,
51 KernelBuilder kernel_builder, bool use_tp,
52 double tp_a, double tp_b)
53{
54 if (grid_params_.empty() || y.size() == 0 || !y.allFinite()) {
55 throw std::invalid_argument(
56 "model averaging needs a grid and finite targets");
57 }
58 weights_.clear();
59 std::exception_ptr failure;
60 std::vector<double> log_likelihoods(grid_params_.size());
61 const auto n_params = static_cast<int>(grid_params_.size());
62
63#ifdef USE_OPENMP
64#pragma omp parallel for schedule(dynamic)
65#endif
66 for (int idx = 0; idx < n_params; ++idx) {
67 try {
68 double log_ls = grid_params_[idx].first;
69 double log_noise = grid_params_[idx].second;
70 double ls = std::pow(10.0, log_ls);
71 double noise_var = std::pow(10.0, log_noise);
72
73 // A builder may set shared kernel state before it assembles
74 // the matrices (runBMAGrid writes the length scale, sigma2 and
75 // the distance scratch), so one grid point builds at a time.
76 EigenMatrix K_XX;
77 std::exception_ptr build_failure;
78#ifdef USE_OPENMP
79#pragma omp critical(gpr_model_averaging_builder)
80#endif
81 {
82 try {
83 K_XX = std::get<0>(kernel_builder(ls, noise_var));
84 } catch (...) {
85 build_failure = std::current_exception();
86 }
87 }
88 if (build_failure) std::rethrow_exception(build_failure);
89
90 if (K_XX.rows() != y.size() || K_XX.cols() != y.size() ||
91 !K_XX.allFinite()) {
92 throw std::invalid_argument(
93 "kernel matrix must match the finite targets");
94 }
95
96 // Eigendecompose
97 Eigen::SelfAdjointEigenSolver<EigenMatrix> solver(K_XX);
98 Eigen::VectorXd D = solver.eigenvalues();
99 EigenMatrix U = solver.eigenvectors();
100
102 fl.setEigendecomposition(D, U, y);
103
104 if (use_tp) {
105 log_likelihoods[idx] = fl.evaluateTP(noise_var, tp_a, tp_b);
106 } else {
107 log_likelihoods[idx] = fl.evaluateGP(noise_var);
108 }
109 } catch (...) {
110#ifdef USE_OPENMP
111#pragma omp critical(gpr_model_averaging_error)
112#endif
113 {
114 if (!failure) failure = std::current_exception();
115 }
116 }
117 }
118
119 if (failure) std::rethrow_exception(failure);
120
121 // Convert to posterior weights via log-sum-exp
122 double max_ll =
123 *std::min_element(log_likelihoods.begin(), log_likelihoods.end());
124 weights_.resize(grid_params_.size());
125 double sum_w = 0.0;
126 for (size_t i = 0; i < weights_.size(); ++i) {
127 // NLML: lower is better, so weight = exp(-NLML)
128 weights_[i] = std::exp(-(log_likelihoods[i] - max_ll));
129 sum_w += weights_[i];
130 }
131 for (auto& w: weights_) {
132 w /= sum_w;
133 }
134}
135
137 const Eigen::VectorXd& y, KernelBuilder kernel_builder) const
138{
139 if (weights_.empty() || weights_.size() != grid_params_.size() ||
140 y.size() == 0 || !y.allFinite()) {
141 throw std::invalid_argument(
142 "model averaging needs a successful fit and finite targets");
143 }
144 BMAPrediction result;
145 bool first = true;
146
147 Eigen::VectorXd weighted_mean;
148 Eigen::VectorXd weighted_sq; // E[mu^2 + var]
149
150 for (size_t idx = 0; idx < grid_params_.size(); ++idx) {
151 if (weights_[idx] < 1e-15) continue; // skip negligible weights
152
153 double log_ls = grid_params_[idx].first;
154 double log_noise = grid_params_[idx].second;
155 double ls = std::pow(10.0, log_ls);
156 double noise_var = std::pow(10.0, log_noise);
157
158 auto [K_XX, K_cross, k_diag] = kernel_builder(ls, noise_var);
159
160 if (K_XX.rows() != y.size() || K_XX.cols() != y.size() ||
161 K_cross.cols() != y.size() || k_diag.size() != K_cross.rows() ||
162 !K_XX.allFinite() || !K_cross.allFinite() || !k_diag.allFinite()) {
163 throw std::invalid_argument(
164 "invalid model averaging prediction covariance");
165 }
166
167 // Add noise to K_XX
168 K_XX.diagonal().array() += noise_var;
169
170 // Cholesky solve for prediction
171 Eigen::LLT<EigenMatrix> llt(K_XX);
172 Eigen::VectorXd alpha = llt.solve(y);
173
174 // Mean: K_cross * alpha
175 Eigen::VectorXd mu = K_cross * alpha;
176
177 // Variance: k_diag - diag(K_cross * K_XX^{-1} * K_cross^T)
178 EigenMatrix V = llt.solve(K_cross.transpose());
179 Eigen::VectorXd var =
180 k_diag -
181 (K_cross.array() * V.transpose().array()).rowwise().sum().matrix();
182 var = var.cwiseMax(0.0); // numerical floor
183
184 if (first) {
185 weighted_mean = weights_[idx] * mu;
186 weighted_sq = weights_[idx] * (var + mu.array().square().matrix());
187 first = false;
188 } else {
189 weighted_mean += weights_[idx] * mu;
190 weighted_sq += weights_[idx] * (var + mu.array().square().matrix());
191 }
192 }
193
194 result.mean = weighted_mean;
195 // BMA variance: E[var + mu^2] - E[mu]^2
196 result.variance = weighted_sq - weighted_mean.array().square().matrix();
197 result.variance = result.variance.cwiseMax(0.0);
198 result.n_models = static_cast<int>(grid_params_.size());
199
200 return result;
201}
202
203} // namespace gpr
Full Bayesian posterior marginal GP/TP (FBPMGP).
@ y
Definition Enums.h:28
Eigendecomposition-based log marginal likelihood evaluation.
void fit(const Eigen::VectorXd &y, KernelBuilder kernel_builder, bool use_tp=false, double tp_a=1e-20, double tp_b=1e-20)
Evaluate likelihoods on the grid and compute posterior weights.
BMAPrediction predict(const Eigen::VectorXd &y, KernelBuilder kernel_builder) const
BMA-averaged prediction at test points.
std::function< std::tuple< EigenMatrix, EigenMatrix, Eigen::VectorXd >( double lengthscale, double noise)> KernelBuilder
Build function: given (lengthscale, noise) -> covariance matrix K.
void setGrid(double log_ls_min, double log_ls_max, int n_ls, double log_noise_min, double log_noise_max, int n_noise)
Configure the hyperparameter grid.
double evaluateGP(double noise_variance) const
GP negative log marginal likelihood at given noise level.
double evaluateTP(double noise_variance, double a, double b) const
TP negative log marginal likelihood at given noise level.
void setEigendecomposition(const Eigen::VectorXd &eigenvalues, const EigenMatrix &eigenvectors, const Eigen::VectorXd &targets)
Cache the eigendecomposition of K_XX for repeated noise sweeps.
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
Prediction result from Bayesian model averaging.