def predict(self, X_pred, covariance=False):
"""Leverage Bayesian posterior inference to compute the predicted mean
and variance of a given set of inputs given the available training data.
Notice that it is necessary to first fit the Gaussian process model
before posterior inference can be performed.
"""
# Compute the cross covariance between training and the requested
# inference locations. Also compute the covariance matrix of the
# observed inputs and the covariance at the inference locations.
if type(self.kernel) == SumKernel:
K_pred = self.kernel.cov(X_pred, include_noise=False)
else:
K_pred = self.kernel.cov(X_pred)
K_cross = self.kernel.cov(X_pred, self.X)
v = spla.solve_triangular(self.L, K_cross.T, lower=True)
# Posterior inference. Notice that we add a small amount of noise to the
# diagonal for regulatization purposes.
mean = K_cross.dot(self.alpha)
cov = self.predict_prefactor * (
K_pred - v.T.dot(v) + 1e-8 * np.eye(K_pred.shape[0])
)
# Compute the diagonal of the covariance matrix if we wish to disregard
# all of the covariance information and only focus on the variances at
# the given inputs.
if covariance:
return mean, cov
else:
return mean, np.sqrt(np.diag(cov))
评论列表
文章目录