如何在matplotlib中从训练集的每个点到表面绘制一条垂直线
How to draw a perpendicular line from each point of a training set to surface plane in matplotlib
我正在使用 matplotlib。我有一个带有表面平面和训练数据集的线性回归模型。
我需要绘制从每个数据点到表面平面的正交距离,看起来与此类似:
这是我的代码片段:
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)
如有任何帮助,我们将不胜感激。
我们可以用一些简单的数学事实来解决这个问题:
- 平面上两个向量的叉积是一个垂直于平面的向量。
- 两个向量的点积测量每个向量沿与另一个向量相同的方向行进的距离。
首先,我们可以使用以下代码找到垂直于平面的向量:
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-'
)
希望对您有所帮助!
我正在使用 matplotlib。我有一个带有表面平面和训练数据集的线性回归模型。
我需要绘制从每个数据点到表面平面的正交距离,看起来与此类似:
这是我的代码片段:
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)
如有任何帮助,我们将不胜感激。
我们可以用一些简单的数学事实来解决这个问题:
- 平面上两个向量的叉积是一个垂直于平面的向量。
- 两个向量的点积测量每个向量沿与另一个向量相同的方向行进的距离。
首先,我们可以使用以下代码找到垂直于平面的向量:
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-'
)
希望对您有所帮助!