You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:24:40