【问题标题】:Plot a 3D Boundary Decision in Python在 Python 中绘制 3D 边界决策
【发布时间】:2017-10-09 04:19:02
【问题描述】:

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

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

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

然后按照我的代码:

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()

PS:我正在使用:

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

【问题讨论】:

  • "P.S.2:我知道我的边界决策没有正确分离数据,但目前这对我来说是一个细节,稍后我会修复它。"这是否意味着您只想知道一种在图形中绘制像“墙”一样的 3D 表面的方法?
  • 是的!正是……
  • 好的!所以请检查我的答案是否适合你。
  • 如果您还没有找到它们,我建议您阅读这些:12

标签: python python-2.7 matplotlib mplot3d


【解决方案1】:

要绘制 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()

【讨论】:

  • @QuestionsOverflow 那么您是否正在绘制a*x+b*y+c*z+d=0 平面?正确分离数据后应该很容易知道。
猜你喜欢
  • 2016-07-13
  • 2014-02-26
  • 2014-11-27
  • 2011-07-19
  • 2014-01-20
  • 2013-10-03
  • 2021-07-30
  • 2018-12-31
相关资源
最近更新 更多