在 Python 中绘制 3D 边界决策

Plot a 3D Boundary Decision in Python

我正在尝试绘制 3D 决策边界,但它似乎并不像它看起来那样工作,看看它是怎样的:

我希望它显示为此处的示例:

我不知道怎么解释,但在上面的例子中它看起来像一个"wall"。这就是我想在我的代码中做的。

然后按照我的代码:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_title('Hello World')
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(-1, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

w = [3,2,1]

x = 1
y = 1
z = 1

x_plan = (- w[1] * y - w[2] * z) / w[0]
y_plan = (- w[0] * x - w[2] * z) / w[1]
z_plan = (- w[0] * x - w[1] * y) / w[2]

ax.plot3D([x_plan, 1, 1], [1, y_plan, 1], [1, 1, z_plan], "lightblue")

plt.show()

P.S.: 我正在使用:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

我认为问题应该出在计算上,否则出在:

ax.plot3D([x_plan, 1, 1], [1, y_plan, 1], [1, 1, z_plan], "lightblue")

P.S.2: 我知道我的 Boundary Decision 没有正确分离数据,但目前这对我来说是一个细节,稍后我会修复它。

要绘制 3d 表面,您实际上需要使用 plt3d.plot_surfacesee reference

例如,这段代码将生成以下图像(注意 plt3d.plot_surface 行的注释):

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

def randrange(n, vmin, vmax):
    '''
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 10

for c, m, zlow, zhigh in [('r', 'o', 0, 100)]:
    xs = randrange(n, 0, 50)
    ys = randrange(n, 0, 50)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

for c, m, zlow, zhigh in [('b', '^', 0, 100)]:
    xs = randrange(n, 60, 100)
    ys = randrange(n, 60, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, c=c, marker=m)


ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

xm,ym = np.meshgrid(xs, ys)

ax.plot_surface(xm, ym, xm, color='green', alpha=0.5) # Data values as 2D arrays as stated in reference - The first 3 arguments is what you need to change in order to turn your plane into a boundary decision plane.  

plt.show()