如何修复分类数据集MNIST中的以下错误:

2024-04-25 21:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我将mnist指定为:

mnist = fetch_openml('mnist_784', version = 1)

在浏览MNIST数据集时,分配以下内容后:

X, y = mnist["data"], mnist["target"]

我试图获取一个实例的特征向量,将其重塑为28×28数组, 在此之前,我分配:

some_digit = X[0] 

我得到了一个错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
c:\users\kanishk\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

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

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

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-8-348a6e96ae02> in <module>
----> 1 some_digit = X[0]

c:\users\kanishk\appdata\local\programs\python\python39\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   3022             if self.columns.nlevels > 1:
   3023                 return self._getitem_multilevel(key)
-> 3024             indexer = self.columns.get_loc(key)
   3025             if is_integer(indexer):
   3026                 indexer = [indexer]

c:\users\kanishk\appdata\local\programs\python\python39\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083 
   3084         if tolerance is not None:

KeyError: 0

我怎么修理它


Tags: keyinselfpandasgetindexusersappdata
1条回答
网友
1楼 · 发布于 2024-04-25 21:27:41

看起来您的Xpandas.DataFrame,在DataFrame代码中X[0]搜索名为0的列,但X没有

如果要获取编号为0的行,则可能需要X.iloc[0]


顺便说一句:

当我跑的时候

from sklearn.datasets import fetch_openml

mnist = fetch_openml('mnist_784', version=1)

X, y = mnist["data"], mnist["target"]
print(type(X), X.shape)  # <class 'numpy.ndarray'> (70000, 784)

some_digit = X[0]
print(type(some_digit), some_digit.shape)  # <class 'numpy.ndarray'> (784,)

然后我得到X作为numpy.arrayX[0]给我期望值

也许在某个地方您将Xnumpy.array转换为pandas.DataFrame,现在您必须使用不同的方法来访问数据

相关问题 更多 >