Loading...
Searching...
No Matches
RandomFourierFeatures.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 <cmath>
8#include <random>
9
10namespace gpr {
11
13 int input_dim, int seed)
14 : n_features_(n_features),
15 lengthscale_(lengthscale),
16 input_dim_(input_dim),
17 seed_(seed),
18 W_(n_features, input_dim),
19 b_(n_features),
20 scale_factor_(std::sqrt(2.0 / n_features))
21{
22 generateWeights();
23}
24
26{
27 lengthscale_ = l;
28 generateWeights();
29}
30
31void RandomFourierFeatures::generateWeights()
32{
33 std::mt19937 rng(static_cast<unsigned>(seed_));
34
35 // w_i ~ N(0, 1/l^2), i.e. standard normal scaled by 1/l
36 std::normal_distribution<double> normal(0.0, 1.0 / lengthscale_);
37 for (int i = 0; i < n_features_; ++i) {
38 for (int j = 0; j < input_dim_; ++j) {
39 W_(i, j) = normal(rng);
40 }
41 }
42
43 // b_i ~ Uniform(0, 2*pi)
44 std::uniform_real_distribution<double> uniform(0.0, 2.0 * M_PI);
45 for (int i = 0; i < n_features_; ++i) {
46 b_(i) = uniform(rng);
47 }
48}
49
50Eigen::VectorXd RandomFourierFeatures::transform(const Eigen::VectorXd& x) const
51{
52 // phi(x)_i = sqrt(2/D) * cos(w_i^T x + b_i)
53 Eigen::VectorXd u = W_ * x + b_;
54 return scale_factor_ * u.array().cos().matrix();
55}
56
58{
59 // U = X * W^T + ones * b^T, shape (n_samples x n_features)
60 EigenMatrix U = X * W_.transpose();
61 U.rowwise() += b_.transpose();
62 // Phi = sqrt(2/D) * cos(U)
63 return scale_factor_ * U.array().cos().matrix();
64}
65
67{
69 return Phi * Phi.transpose();
70}
71
72} // namespace gpr
@ x
Definition Enums.h:28
Random Fourier Features approximation for the squared exponential kernel.
void setLengthscale(double l)
Change the lengthscale and regenerate random weights.
EigenMatrix transformBatch(const EigenMatrix &X) const
Compute feature vectors for all rows of X.
RandomFourierFeatures(int n_features, double lengthscale, int input_dim, int seed=42)
Construct and initialize RFF weights from a seeded RNG.
Eigen::VectorXd transform(const Eigen::VectorXd &x) const
Compute the feature vector phi(x) for a single input.
EigenMatrix approximateKernel(const EigenMatrix &X) const
Approximate the kernel matrix K ~ Phi * Phi^T.
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
STL namespace.