获取 TypeError: '(slice(None, None, None), 0)' 是一个无效的键。

58
尝试绘制k-NN分类器的决策边界,但无法完成,出现“TypeError: '(slice(None, None, None), 0)'是无效的键”的错误。

尝试绘制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

错误发生在哪里?我猜测是在clf.fit。如果是这样,那么X_train和y_train是如何定义的? - Jim Parker
1
X是什么类型?无论它是什么类型,都不支持numpy的扩展索引。 - Dan D.
我也遇到了同样的错误,当绘制协方差矩阵时。我想知道是否有人找到了解决方案? - YatShan
13个回答

63

由于您试图直接作为数组访问,因此出现了该问题。请尝试以下方法:

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将解决此问题。


45

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


7
可以举个例子吗? - Amir Shabani
我们知道为什么需要使用 iloc 吗? - PeJota

19

我也遇到了以下问题。

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

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

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

7

我通过将pandas dataframe转换为numpy数组来修复了它。从这里获得帮助。


6
导入数据集时,请使用“.values”。

更改:

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

致:

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

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

6

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

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

4

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

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:])

2

您使用了哪个库来加载数据集?
如果您使用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

1
使用 .values 来访问数据框的值。例如:
df = df[['column_name']].values

希望这能有所帮助。您可以根据自己的需求在任何情况下使用它。


1

你需要创建数组

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将数据框转换为数组,然后应用此操作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接