我正在尝试将高斯过程回归的预测平均数据绘制成 3-D 等高线。我关注了Plot 3D Contour from an Image using extent with Matplotlib 和 mplot3d example code: 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()
运行上面的代码后,控制台出现如下错误:
我想要 x 轴和 y 轴作为二维平面,预测值在 z 轴上。sample plot如下:
我的代码有什么问题?
谢谢!
请您参考如下方法:
您提到的具体错误来自您的 y_train,这可能是一个拼写错误。应该是:
y_train_ : array-like, shape = (n_samples, [n_output_dims])
根据您的 x_train,您有 3 个样本。所以你的 y_train 应该有形状 (3, 1) 而不是 (1, 3)。
绘图部分还有其他错误:
add_subplot应该在projection = '3d'之前有一个位置。Z应与等值线图的X和Y具有相同的形状。- 因为 2,你的
x和y应该匹配xvalues和yvalues。
总而言之,您可能需要进行以下更改:
...
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)
...
只提两点:
这些更改后您将获得的绘图将与您显示的图形不匹配。您问题中的图形是曲面图而不是等高线图。您可以使用
ax.plot_surface获得该类型的绘图。我想你已经知道了。但以防万一,您的绘图不会像示例绘图那样平滑,因为您的
np.meshgrid是稀疏的。
