径向基函数核

7、径向基函数核

import matplotlib.pyplot as plt

import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['axes.unicode_minus'] = False

def plot_gpr_samples(gpr_model, n_samples, ax):


    x = np.linspace(0, 5, 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 in enumerate(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])


rng = np.random.RandomState(4)

X_train = rng.uniform(0, 5, 10).reshape(-1, 1)

y_train = np.sin((X_train[:, 0] - 2.5) ** 2)

n_samples = 5

from sklearn.gaussian_process import GaussianProcessRegressor

from sklearn.gaussian_process.kernels import RBF

kernel = 1.0 * RBF(length_scale=1.0, length_scale_bounds=(1e-1, 10.0))

gpr = GaussianProcessRegressor(kernel=kernel, random_state=0)

fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(10, 8))

# 先测图

plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[0])

axs[0].set_title("先验分布样本")

# 后测图

gpr.fit(X_train, y_train)

plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[1])

axs[1].scatter(X_train[:, 0], y_train, color="red", zorder=10, label="Observations")

axs[1].legend(bbox_to_anchor=(1.05, 1.5), loc="upper left")

axs[1].set_title("后验分布样本")

fig.suptitle("径向基函数核", fontsize=18)

plt.tight_layout()


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 很多机器学习的问题都会涉及到有着几千甚至数百万维的特征的训练实例。这不仅让训练过程变得非常缓慢,同时还很难找到一个...
    城市中迷途小书童阅读 9,252评论 0 2
  • 5-11、高斯核函数RBF import numpy as np import matplotlib.pyplot...
    凌晨思索阅读 4,979评论 0 0
  • 今天,我们将更深入地学习和实现8个顶级Python机器学习算法。 让我们开始Python编程中的机器学习算法之旅。...
    栀子花_ef39阅读 12,654评论 0 62
  • # -*- coding: utf-8 -*- """ Created on Wed Oct 13 17:05:4...
    sonia_xy阅读 3,192评论 0 0
  • 假设你去随机问很多人一个很复杂的问题,然后把它们的答案合并起来。通常情况下你会发现这个合并的答案比一个专家的答案要...
    城市中迷途小书童阅读 7,604评论 0 1