为何我的Multinomial_Regression代码会触发KeyError异常?
KeyError: 1异常排查求助
运行以下代码时触发KeyError:1异常:
arguments = {'Epoch':6000, 'LearningRate':0.005} SoftmaxRegression = Multinomial_Regression(X_train,y_train,arguments) SoftmaxRegression.fit(X_train,y_train)
报错堆栈信息:
KeyError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3360 try: -> 3361 return self._engine.get_loc(casted_key) 3362 except KeyError as err: 7 frames pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 1 The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3361 return self._engine.get_loc(casted_key) 3362 except KeyError as err: -> 3363 raise KeyError(key) from err 3364 3365 if is_scalar(key) and isna(key) and not self.hasnans: KeyError: 1
其中Multinomial_Regression是参考从零实现多分类逻辑回归的代码构建的自定义类,以下是排查方向:
- 检查
y_train的结构:如果是pandas的Series或DataFrame,查看其索引/列名,确认是否存在键1。可通过y_train.index(Series)或y_train.columns(DataFrame)查看具体索引信息。 - 自定义类可能默认输入的标签是numpy数组格式,若传入的是pandas对象,代码中类似
y[1]的索引操作会被pandas解析为查找索引键而非位置索引,导致找不到键1。 - 检查
Multinomial_Regression的fit方法内部,是否存在对标签数据进行整数索引的逻辑,比如尝试访问第1类标签或第1列数据,而当前y_train的索引结构不匹配。 - 临时解决方案:将
X_train和y_train转换为numpy数组后传入,比如使用X_train.to_numpy()、y_train.to_numpy()(pandas 0.24+版本),规避pandas索引逻辑带来的问题。
内容的提问来源于stack exchange,提问作者ifcheprogrammer
相关产品推荐
相关产品推荐

