BI-LSTM-CRF模型训练NER任务时触发AttributeError问题求助
解决BI-LSTM-CRF训练中的
AttributeError: 'Tensor' object has no attribute '_keras_history'问题 这个错误通常是因为你使用的CRF损失函数和评估指标没有正确绑定到你的CRF层实例,导致Tensor缺失Keras所需的历史追踪信息。下面是具体的解决方案:
1. 确认CRF层的正确导入与依赖
首先,确保你使用的是TensorFlow Addons中的CRF层(这是官方推荐的兼容tf.keras的实现),而不是旧的keras-contrib包(该包已停止维护,容易出现兼容性问题)。
如果还没安装TensorFlow Addons,先在Colab中执行:
!pip install tensorflow-addons
然后在代码中导入:
import tensorflow_addons as tfa
2. 修改模型编译逻辑,绑定CRF层的内置损失与指标
你之前直接调用losses.crf_loss和metrics.crf_accuracy,这些全局函数没有和你的crf_layer实例关联,导致计算时Tensor丢失了_keras_history属性。正确的做法是使用CRF层自带的loss和accuracy方法:
修改后的完整模型代码:
input_layer = layers.Input(shape=(MAX_SENTENCE,)) model = layers.Embedding(WORD_COUNT, DENSE_EMBEDDING, embeddings_initializer="uniform", input_length=MAX_SENTENCE)(input_layer) model = layers.Bidirectional(layers.LSTM(LSTM_UNITS, recurrent_dropout=LSTM_DROPOUT, return_sequences=True))(model) model = layers.TimeDistributed(layers.Dense(DENSE_UNITS, activation="relu"))(model) # 使用tensorflow-addons的CRF层 crf_layer = tfa.layers.CRF(units=TAG_COUNT) output_layer = crf_layer(model) ner_model = Model(input_layer, output_layer) opt = tf.keras.optimizers.Adam(learning_rate=0.001) # 关键:使用CRF层内置的loss和accuracy ner_model.compile(optimizer=opt, loss=crf_layer.loss, metrics=[crf_layer.accuracy]) ner_model.summary()
3. 额外检查:版本兼容性
确保你的TensorFlow版本和TensorFlow Addons版本匹配,比如:
- TensorFlow 2.10.x 对应 TensorFlow Addons 0.18.x
- TensorFlow 2.11.x 对应 TensorFlow Addons 0.19.x
- TensorFlow 2.12+ 可以使用最新的TensorFlow Addons版本
如果版本不匹配,可能会引发其他隐性问题,建议执行以下命令确保版本兼容:
!pip install tensorflow==2.10 tensorflow-addons==0.18.0
这样修改后,你的模型应该能正常拟合训练数据,不会再触发_keras_history相关的错误。
内容的提问来源于stack exchange,提问作者Alassane
相关产品推荐
相关产品推荐

