能带曲线绘制python_用matplotlib在python中绘制曲线决策边界

这可以通过网格化参数空间并将每个网格点设置为最近点的值来实现。然后在这个网格上绘制等高线图。在

但也有许多变化,例如将其设置为距离加权平均值;或平滑最终轮廓等

以下是查找初始轮廓的示例:

import numpy as np

import matplotlib.pyplot as plt

# get the data as numpy arrays

xys = np.array(np.matrix('2,300;4,600;7,300;5,500;5,400;6,400;3,400;4,500;1,200;3,400;7,700;3,550;2.5,650'))

vals = np.array(np.matrix('0;1;1;1;0;1;0;0;0;0;1;1;0'))[:,0]

N = len(vals)

# some basic spatial stuff

xs = np.linspace(min(xys[:,0])-2, max(xys[:,0])+1, 10)

ys = np.linspace(min(xys[:,1])-100, max(xys[:,1])+100, 10)

xr = max(xys[:,0]) - min(xys[:,0]) # ranges so distances can weight x and y equally

yr = max(xys[:,1]) - min(xys[:,1])

X, Y = np.meshgrid(xs, ys) # meshgrid for contour and distance calcs

# set each gridpoint to the value of the closest data point:

Z = np.zeros((len(xs), len(ys), N))

for n in range(N):

Z[:,:,n] = ((X-xys[n,0])/xr)**2 + ((Y-xys[n,1])/yr)**2 # stack arrays of distances to each points

z = np.argmin(Z, axis=2) # which data point is the closest to each grid point

v = vals[z] # set the grid value to the data point value

# do the contour plot (use only the level 0.5 since values are 0 and 1)

plt.contour(X, Y, v, cmap=plt.cm.gray, levels=[.5]) # contour the data point values

# now plot the data points

pos=np.where(vals==1)

neg=np.where(vals==0)

plt.plot(xys[pos,0], xys[pos,1], 'ro')

plt.plot(xys[neg,0], xys[neg,1], 'bo')

plt.show()

你可能感兴趣的:(能带曲线绘制python)