用Python绘制3D边界决策

时间:2017-05-10 13:23:24

标签: python python-2.7 matplotlib mplot3d

我试图绘制一个3D决策界限,但它似乎没有像它看起来那样工作,看看它是怎样的:

enter image description here

我希望它在此示例中显示:

enter image description here

我不知道如何解释,但在上面的例子中,它看起来像一个"墙"。这就是我想在我的代码中做的事情。

然后按照我的代码:

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:我知道我的边界决定没有正确地分离数据,但此刻这对我来说是一个细节,稍后我会修复它。

1 个答案:

答案 0 :(得分:0)

要绘制三维表面,您实际需要使用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()

enter image description here