Получение TypeError: '(slice (None, None, None), 0)' является недопустимым ключом - PullRequest
4 голосов
/ 22 марта 2019

Пытается построить решение Граница классификатора k-NN, но не может этого сделать, получив TypeError: '(slice (None, None, None), 0)' - недопустимый ключ`

    h = .01  # step size in the mesh

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

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

        # 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("4-Class classification (k = %i, weights = '%s')"
                  % (n_neighbors, weights))

    plt.show()

Получил это при запуске, не очень уверен, что это значит, не думаю, что у clf.fit есть проблема, но я не уверен

  TypeError                                 Traceback (most recent call last)
<ipython-input-394-bef9b05b1940> in <module>
     12         # Plot the decision boundary. For that, we will assign a color to each
     13         # point in the mesh [x_min, x_max]x[y_min, y_max].
---> 14         x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
     15         y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
     16         xx, yy = np.meshgrid(np.arange(x_min, x_max, h),

~\Miniconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

~\Miniconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2654                                  'backfill or nearest lookups')
   2655             try:
-> 2656                 return self._engine.get_loc(key)
   2657             except KeyError:
   2658                 return self._engine.get_loc(self._maybe_cast_indexer(key))

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

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

Ответы [ 2 ]

1 голос
/ 19 мая 2019

вам нужно использовать iloc / loc для доступа к df, попробуйте добавить iloc к X, чтобы X.iloc [:, 0]

0 голосов
/ 09 июля 2019

Вы должны создать массив

x_min, x_max = X [:, 0] .min () - 1, X [:, 0] .max () + 1 y_min, y_max = X [:, 1] .min () - 1, X [:, 1] .max () + 1

Это присутствует в кадре данных

, вам необходимо сначала преобразовать кадр данных в массивс помощью этого dataframe.values ​​затем примените этот

...