在 Matplotlib 中绘制 k-NN 决策边界图

问题描述 投票:0回答:3

如何为 k 最近邻分类器的决策边界着色,如下所示: 我已经使用散点图成功绘制了 3 个类别的数据(左图)。

图片来源:http://cs231n.github.io/classification/

python matplotlib plot
3个回答
13
投票

要绘制决策边界,您需要制作一个网格。您可以使用

np.meshgrid
来执行此操作。
np.meshgrid
需要 X 和 Y 的最小值和最大值以及网格步长大小参数。有时,谨慎的做法是使最小值略低于 x 和 y 的最小值,并使最大值略高。

 xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

然后,您可以像这样向分类器提供网格网格

Z=clf.predict(np.c_[xx.ravel(), yy.ravel()])
,您需要将其输出重塑为与原始网格网格相同的格式
Z = Z.reshape(xx.shape)
。最后,当您制作绘图时,您需要调用
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
这将使决策边界在绘图中可见。

下面是实现此目的的完整示例,位于 http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html#sphx-glr-auto-examples-neighbors-plot-classification-py

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets

n_neighbors = 15

# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2]  # we only take the first two features. We could
                      # avoid this ugly slicing by using a two-dim dataset
y = iris.target

h = .02  # step size in the mesh

# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

for weights in ['uniform', 'distance']:
    # we create an instance of Neighbours Classifier and fit the data.
    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    clf.fit(X, y)

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"
              % (n_neighbors, weights))

plt.show()

这会输出以下两张图


0
投票
X = iris.data[:, :2]  # we only take the first two features. We could
                      # avoid this ugly slicing by using a two-dim dataset

如果我将此 X 作为 3 维数据集,以下代码会发生什么变化:

for weights in ['uniform', 'distance']:
    # we create an instance of Neighbours Classifier and fit the data.
    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    clf.fit(X, y)

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"
              % (n_neighbors, weights))

plt.show()

0
投票

我尝试@error的答案,但在pytorch中,它没有等效的KNeighborsClassifier。数据准备和绘图是相同的代码。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import datasets
import torch

n_neighbors = 15

# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2]  # we only take the first two features. We could
                      # avoid this ugly slicing by using a two-dim dataset
y = iris.target

h = .02  # step size in the mesh

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                      np.arange(y_min, y_max, h))

def euclidean_distance(p1, p2):
  return torch.sqrt(torch.sum(torch.square(p1 - p2), dim=1))

def get_nearest_neighbors(query_point, data, k):
  distances = euclidean_distance(query_point.unsqueeze(0), data)
  _, indices = torch.topk(distances, k, largest=False)
  return indices.squeeze()

def classify(query_point, data, k):
  neighbors_indices = get_nearest_neighbors(query_point, data, k)
  nearest_neighbor_classes = y[neighbors_indices]
  counts = np.bincount(nearest_neighbor_classes)
  classification = np.argmax(counts)
  return classification

data = torch.tensor(X)

Z = [[classify(torch.tensor([x, y]), data, n_neighbors) for x, y in zip(row_x, row_y)] for row_x, row_y in zip(xx, yy)]
Z = torch.tensor(Z)
Z = Z.reshape(xx.shape)

cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("3-Class classification (k = %i, weights = '%s')"
          % (n_neighbors, "distance"))
plt.show()

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.