簡體   English   中英

嘗試繪制 KNN 的決策邊界時出錯

[英]Error while trying to graph a decision boundary for a KNN

我有一個帶有 2 個變量的 csv 數據框(一個輸入數據框,用 X 表示)和另一個由我的目標變量組成的 numpy 數組。

這看起來像這樣:

>X

    Duration  Grand Mean
0        142  383.076805
1        334  182.067833
2         97  232.677513
3        220  448.385085
4        127  251.524975
5        121  156.828771
>y
[13 11 11 13 12 11 11 13 12 11 12 13 11 12 12 13 13 12 13 12 11 13 13 12
 12 13 13 13 12 13 13 11 13 13 11 13 11 12 13 13 13 11 11 12 13 13 12 12
 12 11]

我沒有包含這個特定練習的數據框,因為我得到的錯誤對於我使用的任何 csv 文件都是非常普遍的,所以我認為問題本質上與我使用的方法有關。

所以,我試過:

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

n_neighbors = 15




h = .02  # step size in the mesh

# Create color maps
cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ListedColormap(['darkorange', 'c', 'darkblue'])

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,
                edgecolor='k', s=20)
    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()

帶有以下錯誤消息:

TypeError: '(slice(None, None, None), 0)' is an invalid key

我在這個主題上看到過類似的帖子,但我無法得到該問題的答案對我有用。

您的錯誤是由於您對 pandas df切片的方式(您這樣做就像是一個明顯錯誤的 numpy 數組)。

一種可能的糾正方法,請放置以下行:

X = X.values

在您的代碼頂部,您就可以開始了。

證明

X = pd.DataFrame(np.random.randn(100,2), columns=["Duration","Grand Mean"])
X = X.values # <--- put this line
y = np.random.choice([11,12,13],100,True,[.33,.33,.34])

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

n_neighbors = 15

h = .02  # step size in the mesh

# Create color maps
cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ListedColormap(['darkorange', 'c', 'darkblue'])

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,
                edgecolor='k', s=20)
    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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM