【问题标题】:Getting TypeError: '(slice(None, None, None), 0)' is an invalid key获取 TypeError: '(slice(None, None, None), 0)' is an invalid key
【发布时间】:2019-08-12 23:18:30
【问题描述】:

试图绘制 k-NN 分类器的决策边界,但无法这样做得到TypeError: '(slice(None, None, None), 0)' is an invalid key

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

【问题讨论】:

  • 错误发生在哪里?我假设在 clf.fit。如果有,X_train 和 y_train 是如何定义的?
  • X 是什么类型?不管它是什么都不支持 numpy 扩展索引。
  • 我在绘制协方差矩阵时也遇到了同样的错误。我想知道是否有人提出了解决方案?

标签: python machine-learning knn


【解决方案1】:

您需要使用iloc/loc 来访问df。尝试将 iloc 添加到 X 所以X.iloc[:, 0]

【讨论】:

  • 你能举个例子吗?
【解决方案2】:

你必须创建数组

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 然后应用这个

【讨论】:

    【解决方案3】:

    我通过将 pandas 数据框转换为 numpy 数组来修复它。得到了here的帮助

    【讨论】:

      【解决方案4】:

      由于您尝试直接作为数组访问,因此您遇到了这个问题。试试这个:

      from sklearn.impute import SimpleImputer
      imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean',verbose=0)
      imputer = imputer.fit(X.iloc[:, 1:3])
      X.iloc[:, 1:3] = imputer.transform(X.iloc[:, 1:3])
      

      使用iloc/loc 将解决问题。

      【讨论】:

        【解决方案5】:
        from sklearn.impute import SimpleImputer
        
        imputer = SimpleImputer(missing_values= np.nan, strategy= 'mean')
        
        imputer = imputer.fit(X.iloc[:, 1:3])
        X = imputer.transform(X.iloc[:, 1:3])
        

        【讨论】:

        • 你应该试试这个 #Take the care of missing data from sklearn.impute import SimpleImputer imputer = SimpleImputer(missing_values= np.nan, strategy= 'mean') imputer = imputer.fit(X.iloc[ :, 1:3]) X = imputer.transform(X.iloc[:, 1:3])
        【解决方案6】:

        我遇到了同样的问题

        X = dataset.iloc[:,:-1]
        

        然后我添加了.values 属性,之后它就没有问题了

        X = dataset.iloc[:,:-1].values
        

        【讨论】:

          【解决方案7】:

          尝试在上面编写的代码之前运行此代码。

          x_min = x_min.values
          x_min = x_min.astype('float32')
          x_max = x_max.values
          y_test1 = x_max.astype('float32')
          

          【讨论】:

            【解决方案8】:

            我将我的输入改为一个 numpy 数组,并且它起作用了。我仍然无法使用 Pandas 数据框输入对这个问题进行排序。如果您的情况紧急,我建议您将输入更改为 numpy 并继续前进。

            【讨论】:

              【解决方案9】:

              当您尝试使用 pandas 获取数据集时,请使用以下代码:

              dataset = pd.read_csv("path or file name")
              x = dataset.iloc[:,:-1].values
              y = dataset.iloc[:,-1].values
              

              【讨论】:

                【解决方案10】:

                您使用哪个库来加载数据集?
                如果您使用 Pandas 库加载数据集,则需要向数据框添加基于索引的选择 (iloc) 函数以访问值,例如

                import pandas as pd
                data=pd.read_csv('../filename.csv')
                X=data.iloc[:,0:8]
                y=data.iloc[:,8] 
                

                针对您的问题:

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

                如果您使用 NumPy 库加载数据集,则可以直接将值作为数组访问,例如

                from numpy import loadtxt
                data=loadtxt('../filename.csv',delimiter=',')
                X=data[:,0:8]
                y=data[:,8]
                

                针对您的问题:

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

                【讨论】:

                  【解决方案11】:

                  我在使用时遇到了同样的问题

                  features = data.iloc[:,:-1]
                  si = SimpleImputer(missing_values = np.nan, strategy = 'mean')
                  si.fit(features[:, 1:])
                  

                  然后我通过调用 .values() 函数/方法到 iloc 的输出解决了这个问题,然后作为 numpy.ndarray 它工作了!

                  features = data.iloc[:,:-1].values()
                  si = SimpleImputer(missing_values = np.nan, strategy = 'mean')
                  si.fit(features[:, 1:])
                  

                  【讨论】:

                    【解决方案12】:

                    导入数据集时,使用 .values。

                    变化:

                    X = dataset.iloc[:, 1:3]
                    

                    收件人:

                    X = dataset.iloc[:, 1:3].values
                    

                    【讨论】:

                    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
                    猜你喜欢
                    • 1970-01-01
                    • 2020-03-19
                    • 2019-09-11
                    • 2020-11-19
                    • 1970-01-01
                    • 1970-01-01
                    • 2023-03-30
                    • 2019-07-31
                    • 2018-11-29
                    相关资源
                    最近更新 更多