matplot(XX, t(YY), type="l", col=c(rep("grey", nrow(XX))), lty=1, xlab="x", ylab="f(x)", las =1, main ="Prediction with Uncertainty")points(X, y, pch=20, cex=2)lines(XX, t(YY)[, 1], col=3, lty =1)lines(XX, mup, lwd=2, col ="blue", lty=2)lines(XX, q1, lwd=2, lty=2, col=2)lines(XX, q2, lwd=2, lty=2, col=2)
2 Python implementation
Code
import matplotlib.pyplot as pltimport numpy as npfrom sklearn.gaussian_process import GaussianProcessRegressorfrom sklearn.gaussian_process.kernels import RBF
Code
def plot_gpr_samples(gpr_model, n_samples, ax):"""Plot samples drawn from the Gaussian process model. If the Gaussian process model is not trained then the drawn samples are drawn from the prior distribution. Otherwise, the samples are drawn from the posterior distribution. Be aware that a sample here corresponds to a function. Parameters ---------- gpr_model : `GaussianProcessRegressor` A :class:`~sklearn.gaussian_process.GaussianProcessRegressor` model. n_samples : int The number of samples to draw from the Gaussian process distribution. ax : matplotlib axis The matplotlib axis where to plot the samples. """ x = np.linspace(0, 2* np.pi, 100) X = x.reshape(-1, 1) y_mean, y_std = gpr_model.predict(X, return_std=True) y_samples = gpr_model.sample_y(X, n_samples)for idx, single_prior inenumerate(y_samples.T): ax.plot( x, single_prior, linestyle="--", alpha=0.7, label=f"Sampled function #{idx +1}", ) ax.plot(x, y_mean, color="black", label="Mean") ax.fill_between( x, y_mean - y_std, y_mean + y_std, alpha=0.1, color="black", label=r"$\pm$ 1 std. dev.", ) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_ylim([-3, 3])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.