如何在三维等高线图中绘制回归预测数据?

3

我正在尝试将高斯过程回归的预测平均数据绘制成3D等高线图。我遵循了使用Matplotlib和extent从图像绘制3D等高线图mplot3d示例代码:contour3d_demo3.py线程。以下是我的代码:

import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm

x_train = np.array([[0,0],[2,2],[3,3]])
y_train = np.array([[200,321,417]])

xvalues = np.array([0,1,2,3])
yvalues = np.array([0,1,2,3])

a,b = np.meshgrid(xvalues,yvalues)
positions = np.vstack([a.ravel(), b.ravel()])
x_test = (np.array(positions)).T

kernel = C(1.0, (1e-3, 1e3)) * RBF(10)

gp = GaussianProcessRegressor(kernel=kernel)

gp.fit(x_train, y_train)

y_pred_test = gp.predict(x_test)

fig = plt.figure()
ax = fig.add_subplot(projection = '3d')
x=y=np.arange(0,3,1)
X, Y = np.meshgrid(x,y)
Z = y_pred_test
cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()

在运行上述代码后,我在控制台上得到以下错误:

enter image description here

我希望将x轴和y轴作为二维平面,将预测值放在z轴上。 样例图 如下:

enter image description here

我的代码有什么问题?

谢谢!

1个回答

1
你提到的具体错误来自于你的 y_train,可能是一个打字错误。应该是:

y_train_ : array-like, shape = (n_samples, [n_output_dims])

根据你的 x_train,你有 3 个样本。所以你的 y_train 应该有形状为 (3, 1) 而不是 (1, 3)
你在绘图部分还有其他错误:
  1. add_subplot 在使用 projection = '3d' 之前应该有一个位置。
  2. 轮廓图的 Z 应该与 XY 具有相同的形状。
  3. 由于第二点,你的 xy 应该与 xvaluesyvalues 匹配。
综上,你可能需要进行以下更改:
...

y_train = np.array([200,321,417])

...

ax = fig.add_subplot(111, projection = '3d')
x=y=np.arange(0,4,1)
...
Z = y_pred_test.reshape(X.shape)

...

只是提两件事情:

  1. 在这些更改后,您将获得的绘图与您显示的图形不匹配。您问题中的图形是曲面图而不是等高线图。您可以使用 ax.plot_surface 获取该类型的图。

  2. 我认为您已经知道了这一点。但以防万一,由于您的 np.meshgrid 是稀疏的,因此您的绘图不会像样本绘图那样平滑。


它起作用了,非常感谢。在表面图中,我需要给出一些颜色区分,例如高数据的红色,最低的蓝色,以及中等数据的绿色/黄色。我该怎么做?有什么想法吗? - santobedi
1
@santobedi 你可以从这里或者这里开始。 - Y. Luo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接