使用贝叶斯岭回归进行曲线拟合

Beginner

This tutorial is from open-source community. Access the source code

简介

本实验展示了如何使用贝叶斯岭回归对带有噪声的正弦数据拟合多项式曲线。我们将生成带有噪声的正弦数据,使用三次多项式进行拟合,并绘制真实曲线和预测曲线。通过这些模型的对数边际似然(L),我们可以确定哪一个模型更好。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

生成带噪声的正弦数据

我们首先生成带噪声的正弦数据。

import numpy as np

def func(x):
    return np.sin(2 * np.pi * x)

size = 25
rng = np.random.RandomState(1234)
x_train = rng.uniform(0.0, 1.0, size)
y_train = func(x_train) + rng.normal(scale=0.1, size=size)
x_test = np.linspace(0.0, 1.0, 100)

用三次多项式拟合

我们使用三次多项式对数据进行拟合。

from sklearn.linear_model import BayesianRidge

n_order = 3
X_train = np.vander(x_train, n_order + 1, increasing=True)
X_test = np.vander(x_test, n_order + 1, increasing=True)
reg = BayesianRidge(tol=1e-6, fit_intercept=False, compute_score=True)

绘制带有对数边际似然(L)的真实曲线和预测曲线

我们绘制带有对数边际似然(L)的真实曲线和预测曲线。

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2, figsize=(8, 4))
for i, ax in enumerate(axes):
    ## 具有不同初始值对的贝叶斯岭回归
    if i == 0:
        init = [1 / np.var(y_train), 1.0]  ## 默认值
    elif i == 1:
        init = [1.0, 1e-3]
        reg.set_params(alpha_init=init[0], lambda_init=init[1])
    reg.fit(X_train, y_train)
    ymean, ystd = reg.predict(X_test, return_std=True)

    ax.plot(x_test, func(x_test), color="blue", label="sin(2πx)")
    ax.scatter(x_train, y_train, s=50, alpha=0.5, label="observation")
    ax.plot(x_test, ymean, color="red", label="predict mean")
    ax.fill_between(
        x_test, ymean - ystd, ymean + ystd, color="pink", alpha=0.5, label="predict std"
    )
    ax.set_ylim(-1.3, 1.3)
    ax.legend()
    title = "α_init={:.2f}, λ_init={}".format(init[0], init[1])
    if i == 0:
        title += " (Default)"
    ax.set_title(title, fontsize=12)
    text = "α={:.1f}\nλ={:.3f}\nL={:.1f}".format(
        reg.alpha_, reg.lambda_, reg.scores_[-1]
    )
    ax.text(0.05, -1.0, text, fontsize=12)

plt.tight_layout()
plt.show()

总结

贝叶斯岭回归是一种强大的曲线拟合技术,可用于将数据拟合到多项式曲线上。通过对正则化参数的不同初始值进行迭代,我们可以找到给定数据的最佳拟合。