MATLAB Answers

Sampling from Posterior Distribution of GPR Model from fitrgp()

21 views (last 30 days)
I can get a gprMdl via:
N = 100;
x = linspace(-10,10,N)';
y = 1 + x*5e-2 + sin(x)./x + 0.2*randn(N,1);
gprMdl = fitrgp(x,y,'FitMethod','Exact','PredictMethod','Exact');
and the posterior covariance matrix via:
kfcn = gprMdl.Impl.Kernel.makeKernelAsFunctionOfXNXM(gprMdl.Impl.ThetaHat)
K = kfcn(x(1:5,:),x(1:7,:))
How can I go about sampling a model from the posterior distribution of gprMdl?
To clarify, I mean like the curves from the 2nd tile of:
Being able to do this is a matter of being able to finish up a graduate program, so any help is much appreciated!
  1 Comment
Sterling Baird
Sterling Baird on 6 Jan 2021
Perhaps all I need is to use the mean from predict and the covariance matrix from the undocumented function along with mvnrnd, similar to what's described in:
Though I'm not sure if this is sampling from the posterior..

Sign in to comment.

Accepted Answer

Gautam Pendse
Gautam Pendse on 7 Jan 2021
Hi Sterling,
Here's an example illustrating how to sample from the posterior distribution of a GPR model. The code uses an undocumented function predictExactWithCov. If you have categorical predictors, you would need to convert them to dummy variables before using that function.
Hope this helps,
function testPosteriorCovarianceGP()
% 1. Some dummy data.
X = [-10,-8,-5,-1,1,3,7,10]';
N = numel(X);
y = 1 - X*5e-2 + sin(X)./X + 1e-4*randn(N,1);
M = 1000;
Xnew = linspace(-10,10,M)';
% 2. Fit a GPR model.
gpr = fitrgp(X,y,'Sigma',0.01,'SigmaLowerBound',1e-6);
% 3. Access the posterior covariance matrix by calling the undocumented
% predictExactWithCov method on the gpr.Impl object. Vectors ynew can be
% simulated from a Normal distribution with mean pred and covariance covmat
% using cholcov or svd and randn.
alpha = 0.05;
[pred,covmat,ci] = predictExactWithCov(gpr.Impl,Xnew,alpha);
hold on;
T = cholcov(covmat);
numSamples = 50;
ynew = pred + T'*randn(M,numSamples);
hold on;
Jitin Malhotra
Jitin Malhotra on 25 Jun 2021
@Gautam Pendse, I din't understand what exactly you did and how i should use it on my data. If possible can you please provide more details about this undocumented function? predictExactWithCov(gpr.Impl,Xnew,alpha);
My main motive is to calculate CI_width and CI_var, which is basically the 95% confidence interval width and variance acc. to given formulae
well I got my model as output from regression learner app, How should I move forward on this?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!