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

调用Keras的model.fit()时出现KeyError: 0错误的求助

Keras训练NLP序列模型时出现KeyError: 0错误

模型架构

from keras.models import Sequential
from keras import layers
from keras.layers import Embedding, Flatten, Dense

embedding_dim = 500

model = Sequential()

model.add(layers.Embedding(input_dim = vocab_size, 
                           output_dim = embedding_dim, input_shape = (2,)))
model.add(layers.Flatten())
model.add(layers.Dense(10, activation = 'relu'))
model.add(layers.Dense(6, activation = 'softmax'))
model.compile(optimizer = 'adam',
              loss = 'categorical_crossentropy',
              metrics = METRICS)

早停机制与类别权重配置

early_stopping = tf.keras.callbacks.EarlyStopping(
    monitor = 'val_loss', 
    verbose = 1,
    patience = 10,
    mode = 'max',
    restore_best_weights = True)

class_weight = {0: 3.,
                1: 2.,
                2: 1.5,
                3: 1.,
                4: 3.,
                5: 3.
                }

训练调用代码

history = model.fit(X_train, y_train,
                    epochs = 100,
                    verbose = 2,
                    validation_data = (X_val, y_val),
                    batch_size = 10,
                    class_weight = class_weight,
                    callbacks = [early_stopping]
                   )

错误信息

初始错误

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[74], line 9
      1 class_weight = {1: 3.,
      2                 2: 2.,
      3                 3: 1.5,
   (...)
      6                 6: 3.
      7                 }
----> 9 history = model.fit(X_train, y_train,
     10                     epochs = 100,
     11                     verbose = 2,
     12                     validation_data = (X_val, y_val),
     13                     batch_size = 10,
     14                     class_weight = class_weight,
     15                     callbacks = [early_stopping]
     16                    )

File ~\AppData\Local\anaconda3\Lib\site-packages\keras\src\utils\traceback_utils.py:122, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    119     filtered_tb = _process_traceback_frames(e.__traceback__)
    120     # To get the full stack trace, call:
    121     # `keras.config.disable_traceback_filtering()`
--> 122     raise e.with_traceback(filtered_tb) from None
    123 finally:
    124     del filtered_tb

File ~\AppData\Local\anaconda3\Lib\site-packages\pandas\core\series.py:1040, in Series.__getitem__(self, key)
   1037     return self._values[key]
   1039 elif key_is_scalar:
-> 1040     return self._get_value(key)
   1042 # Convert generator to list before going through hashable part
   1043 # (We will iterate through the generator there to check for slices)
   1044 if is_iterator(key):

File ~\AppData\Local\anaconda3\Lib\site-packages\pandas\core\series.py:1156, in Series._get_value(self, label, takeable)
   1153     return self._values[label]
   1155 # Similar to Index.get_value, but we do not fall back to positional
-> 1156 loc = self.index.get_loc(label)
   1158 if is_integer(loc):
   1159     return self._values[loc]

File ~\AppData\Local\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3798, in Index.get_loc(self, key)
   3793     if isinstance(casted_key, slice) or (
   3794         isinstance(casted_key, abc.Iterable)
   3795         and any(isinstance(x, slice) for x in casted_key)
   3796     ):
   3797         raise InvalidIndexError(key)
-> 3798     raise KeyError(key) from err
   3799 except TypeError:
   3800     # If we have a listlike key, _check_indexing_error will raise
   3801     #  InvalidIndexError. Otherwise we fall through and re-raise
   3802     #  the TypeError.
   3803     self._check_indexing_error(key)

KeyError: 0

禁用Traceback过滤后的错误

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~\AppData\Local\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3791, in Index.get_loc(self, key)
   3790 try:
-> 3791     return self._engine.get_loc(casted_key)
   3792 except KeyError as err:

File index.pyx:152, in pandas._libs.index.IndexEngine.get_loc()

File index.pyx:181, in pandas._libs.index.IndexEngine.get_loc()

File pandas\_libs\hashtable_class_helper.pxi:2606, in pandas._libs.hashtable.Int64HashTable.get_item()

File pandas\_libs\hashtable_class_helper.pxi:2630, in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception

排查情况

已尝试更新Keras版本,问题未解决;错误指向pandas的Index.get_loc()函数,但无法定位具体根源。

解决建议

  • 修正类别权重的键匹配问题:从错误栈可见,实际传入fit的class_weight字典键是1-6,但你定义的是0-5,而训练数据中存在类别0,导致找不到对应权重。执行print(y_train.unique())确认所有实际类别,确保class_weight包含所有出现的类别,无缺失或多余键。
  • 转换标签数据类型:如果y_train是pandas Series,转为numpy数组避免索引问题:y_train = y_train.values,同理处理y_val。
  • 修正早停mode参数:监控val_loss时,loss越小模型性能越好,需将mode设为'min',原配置的'max'会导致早停逻辑错误。

内容的提问来源于stack exchange,提问作者Alex K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:10:14