MATLAB: Sampling from Posterior Distribution of GPR Model from fitrgp()

fitrgpgaussian process regression

I can get a gprMdl via:
rng(0,'twister');
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!

Best Answer

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,
Gautam
function testPosteriorCovarianceGP()
% 1. Some dummy data.
rng(0,'twister');
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);
figure(1);
plot(Xnew,pred,'b');
hold on;
plot(Xnew,ci(:,1),'m');
plot(Xnew,ci(:,2),'g');
plot(X,y,'ko','MarkerFaceColor','k');
xlabel('x');
ylabel('y');
figure(2);
T = cholcov(covmat);
numSamples = 50;
ynew = pred + T'*randn(M,numSamples);
plot(Xnew,ynew);
hold on;
plot(X,y,'ko','MarkerFaceColor','k');
xlabel('x');
ylabel('y');
end