如何在matplotlib中从训练集的每个点到曲面绘制垂直线

2024-04-26 04:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用matplotlib。我有一个下面的线性回归模型,带有一个曲面和训练数据集

我需要绘制从每个数据点到曲面平面的正交距离,看起来类似于: enter image description here

以下是我的代码片段:

nx, ny = (100, 100)

x1 = np.linspace(-3, 10.0, nx)
x2 = np.linspace(0, 15.0, ny)

x_plane, y_plane = np.meshgrid(x1, x2)

XY = np.stack((x_plane.ravel(), y_plane.ravel()),axis =1)

z_plane = np.array([normal_equation(x,y) for x,y in XY]).reshape(x_plane.shape)

fig = plt.figure(figsize=(10, 8))
ax  = fig.gca(projection = '3d')

ax.scatter(X2, X1, Y, color='r')
ax.plot_surface(x_plane, y_plane, z_plane, color='b', alpha=0.4)
ax.set_xlabel('x1')
ax.set_ylabel('x2')
ax.set_zlabel('y')
ax.set_zlim(-10, 5)

任何帮助都将不胜感激


Tags: 数据npfigaxcolorx1x2nx
1条回答
网友
1楼 · 发布于 2024-04-26 04:34:26

我们可以用一些简单的数学事实来解决这个问题:

  • 平面上两个向量的叉积是垂直于平面的向量
  • 两个向量的点积测量每个向量沿与另一个向量相同的方向移动的距离

首先,我们可以使用以下代码找到垂直于平面的向量:

perpendicular = np.cross(
  (0, 1, normal_equation(0, 1) - normal_equation(0, 0)),
  (1, 0, normal_equation(1, 0) - normal_equation(0, 0))
)
normal = perpendicular / np.linalg.norm(perpendicular)

(注意:我们假设平面不是垂直的,它不应该是线性回归)

第二,我们需要沿着这个法向量追溯到平面上的每个点

plane_point = np.array([0, 0, normal_equation(0, 0)])
dot_prods = [
  np.dot(np.array(u) - plane_point, normal)
  for u in zip(X2, X1, Y)
]
closest_points = [
  np.array([X2[i], X1[i], Y[i]]) - normal * dot_prods[i]
  for i in range(len(Y))
]

最后,我们可以在这些点之间绘制连接

for i in range(len(Y)):
  ax.plot(
    [closest_points[i][0], X2[i]],
    [closest_points[i][1], X1[i]],
    [closest_points[i][2], Y[i]],
    'k-'
)

我希望这有帮助

相关问题 更多 >