1. import numpy as np
    2. import matplotlib.pyplot as plt
    3. p=[[1,0.3,2,1],[2,0.3,1,1]]
    4. n=[[1.5,1.7,2,1.5],[2,1.5,2,2.5]]
    5. p=np.array(p)
    6. n=np.array(n)
    7. def divide(dist,k,X,Y):
    8. ans_p=[np.sort(dist(p[0]-X[i],p[1]-Y[i]))for i in range(len(X))]
    9. ans_n=[np.sort(dist(n[0]-X[i],n[1]-Y[i]))for i in range(len(X))]
    10. t=[ans_p[i][int((k-1)/2)]>ans_n[i][int((k-1)/2)]for i in range(len(ans_p))]
    11. return np.array(t)
    12. def dist1(x,y):
    13. return abs(x)+abs(y)
    14. def dist2(x,y):
    15. return np.sqrt(x*x+y*y)
    16. def plot(dist,k,ax):
    17. N=200
    18. X=np.linspace(-0,3,N)
    19. Y=X
    20. X,Y=np.meshgrid(X,Y)
    21. X=X.reshape(1,N*N)[0]
    22. Y=Y.reshape(1,N*N)[0]
    23. predict=divide(dist,3,X,Y)
    24. ax.contourf(X.reshape(N,N),Y.reshape(N,N),predict.reshape(N,N),cmap=plt.cm.Spectral,alpha=0.3)
    25. ax.plot(p[0],p[1],'rx')
    26. ax.plot(n[0],n[1],'bo')
    27. plt.text(0.5,2.5,"k="+str(k))
    28. # plot(dist1,3,plt)
    29. plot(dist2,3,plt)
    30. plt.show()

    曼哈顿距离.jpg
    欧式距离.jpg