You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

高斯过程在简单一维问题中输出无效结果,请求排查解决

问题分析与解决方法

你的代码存在致命的数据覆盖错误,导致模型根本没在你预期的f(x)=x sinx数据集上训练,这是结果不符合预期的核心原因。

核心错误点

你先生成了目标数据集:

X = np.linspace(start=0, stop=10, num=1_000).reshape(-1, 1)
y = np.squeeze(X * np.sin(X))

但紧接着用两行未定义的变量覆盖了X和y:

X = np.array(df)
y = labels

df和labels在代码中从未定义,模型训练的不是你想要的函数数据,自然输出混乱的预测结果。

修正后的完整代码

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF

# 生成预期的数据集
X_orig = np.linspace(start=0, stop=10, num=1_000).reshape(-1, 1)
y = np.squeeze(X_orig * np.sin(X_orig))

# 标准化特征(保留原始X用于画图)
scaler = StandardScaler()
X = scaler.fit_transform(X_orig)

noise_std = 0.75
rng = np.random.RandomState(1)
y_train_noisy = y + rng.normal(loc=0.0, scale=noise_std, size=y.shape)

# 定义核函数与GPR模型
kernel = 1 * RBF()
gaussian_process = GaussianProcessRegressor(
    kernel=kernel, alpha=noise_std**2, n_restarts_optimizer=9
)
gaussian_process.fit(X, y_train_noisy)
mean_prediction, std_prediction = gaussian_process.predict(X, return_std=True)

# 画图(用原始X_orig保证x轴显示正常的0-10范围)
plt.plot(X_orig, y, label=r"$f(x) = x \sin(x)$", linestyle="dotted")
plt.errorbar(
    X_orig,
    y_train_noisy,
    noise_std,
    linestyle="None",
    color="tab:blue",
    marker=".",
    markersize=5,
    label="Observations",
)
plt.plot(X_orig, mean_prediction, label="Mean prediction")
plt.fill_between(
    X_orig.ravel(),
    mean_prediction - 1.96 * std_prediction,
    mean_prediction + 1.96 * std_prediction,
    color="tab:orange",
    alpha=0.5,
    label=r"95% confidence interval",
)
plt.legend()
plt.xlabel("$x$")
plt.ylabel("$f(x)$")
plt.title("Gaussian process regression on a noisy dataset")
plt.show()

额外说明

  1. 补充了matplotlib.pyplot的导入(原代码遗漏)
  2. 保留原始特征X_orig,标准化后用原始X轴画图,避免显示标准化后的数值(更直观)
  3. RBF核的参数会被GPR自动优化,n_restarts_optimizer=9会帮你找到更优的核参数,确保拟合出平滑的预测曲线

运行修正后的代码,你会得到符合预期的平滑预测曲线,且95%置信区间会合理包裹观测数据。

内容的提问来源于stack exchange,提问作者Jannis997

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:05:56