python:画图fill_between()

import numpy as np
from scipy.optimize import minimize
from scipy.spatial.distance import pdist, cdist, squareform


class Kernel:
    # RBF核函数
    def __init__(self, theta):
        self.theta = theta

    def __call__(self, X, Y=None):
        if Y is None:
            dists = pdist(X / self.theta, metric='sqeuclidean')
            K = np.exp(-0.5 * dists)
            K = squareform(K)
            np.fill_diagonal(K, 1)
        else:
            dists = cdist(X / self.theta, Y / self.theta, metric='sqeuclidean')
            K = np.exp(-0.5 * dists)
        return K


class GPR:
    def __init__(self):
        self.K = None
        self.X = None
        self.y = None

    def log_marginal_likelihood(self, theta):
        # 计算对数边缘似然函数
        K = Kernel(theta)
        sigma = K(self.X)
        log_likelihood = np.log(np.linalg.det(sigma)) + \
                         self.y @ np.linalg.inv(sigma) @ self.y + \
                         sigma.shape[0] * np.log(2 * np.pi)
        return - 0.5 * log_likelihood

    def fit(self, X, y):
        # 训练,获取核函数最优参数
        self.X = X
        self.y = y

        def obj_func(theta):
            return - self.log_marginal_likelihood(theta)

        theta_opt = minimize(obj_func, np.array([1.0]), method='BFGS')
        self.K = Kernel(theta_opt.x[0])

    def predict(self, X_pred):
        # 预测,获取y*的条件概率分布
        K_pred = self.K(X_pred)
        K_train = self.K(self.X)
        K_pred_train = self.K(self.X, X_pred)
        K_inv = np.linalg.inv(K_train)
        mu = K_pred_train.T @ K_inv @ self.y
        sigma = K_pred - K_pred_train.T @ K_inv @ K_pred_train
        return mu, np.diagonal(sigma)


if __name__ == '__main__':
    import matplotlib.pyplot as plt

    gpr = GPR()

    # 生成样本数据
    coefs = [6, -2.5, -2.4, -0.1, 0.2, 0.03]


    def f(x):
        total = 0
        for exp, coef in enumerate(coefs):
            total += coef * (x ** exp)
        return total


    xs = np.linspace(-5.0, 3.5, 100)
    ys = f(xs)

    X_train = np.array([-4, -1.5, 0, 1.5, 2.5, 2.7])
    y_train = f(X_train)

    X_train = X_train.reshape(-1, 1)
    X_pred = np.linspace(-8, 7, 80).reshape((-1, 1))

    gpr.fit(X_train, y_train)
    y_pred, y_std = gpr.predict(X_pred)

    plt.plot(xs, ys, color='k', linewidth=2, label='True')
    plt.scatter(X_train, y_train, color='b', marker='*', linewidths=3, label='Train_data')
    plt.plot(X_pred, y_pred, color='r', label='Pred')

    plt.fill_between(X_pred.reshape(1, -1)[0], y_pred - y_std, y_pred + y_std, color='darkorange',
                     alpha=0.2)
    plt.legend()
    plt.show()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeniuHe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值