写一段高斯过程建模代码
时间: 2023-03-29 07:01:23 浏览: 98
高斯背景建模代码
我可以回答这个问题。以下是一段高斯过程建模的代码示例:
```python
import numpy as np
from scipy.spatial.distance import cdist
class GaussianProcess:
def __init__(self, kernel, noise=1e-10):
self.kernel = kernel
self.noise = noise
self.X = None
self.y = None
self.K = None
self.K_inv = None
def fit(self, X, y):
self.X = X
self.y = y
self.K = self.kernel(X, X) + self.noise * np.eye(len(X))
self.K_inv = np.linalg.inv(self.K)
def predict(self, X_star):
K_star = self.kernel(self.X, X_star)
y_star_mean = K_star.T @ self.K_inv @ self.y
K_star_star = self.kernel(X_star, X_star)
y_star_var = np.diag(K_star_star - K_star.T @ self.K_inv @ K_star)
return y_star_mean, y_star_var
def rbf_kernel(X1, X2, l=1., sigma_f=1.):
dists = cdist(X1 / l, X2 / l, metric='sqeuclidean')
return sigma_f ** 2 * np.exp(-.5 * dists)
# Example usage
X = np.array([[.], [1.], [2.]])
y = np.sin(X)
gp = GaussianProcess(kernel=rbf_kernel)
gp.fit(X, y)
X_star = np.linspace(-1., 3., 100).reshape(-1, 1)
y_star_mean, y_star_var = gp.predict(X_star)
```
阅读全文