如何在tensorflow keras中使用CRF?

时间:2019-10-22 06:18:28

标签: tensorflow keras crf

代码如下:

import tensorflow as tf
from keras_contrib.layers import CRF
from tensorflow import keras

def create_model(max_seq_len, adapter_size=64):
    """Creates a classification model."""

    # adapter_size = 64  # see - arXiv:1902.00751

    # create the bert layer
    with tf.io.gfile.GFile(bert_config_file, "r") as reader:
        bc = StockBertConfig.from_json_string(reader.read())
        bert_params = map_stock_config_to_params(bc)
        bert_params.adapter_size = adapter_size
        bert = BertModelLayer.from_params(bert_params, name="bert")

    input_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name="input_ids")
    # token_type_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name="token_type_ids")
    # output         = bert([input_ids, token_type_ids])
    bert_output = bert(input_ids)
    print("bert_output.shape: {}".format(bert_output.shape))  # (?, 100, 768)

    crf = CRF(len(tag2idx))
    logits = crf(bert_output)
    model = keras.Model(inputs=input_ids, outputs=logits)
    model.build(input_shape=(None, max_seq_len))

    # load the pre-trained model weights
    load_stock_weights(bert, bert_ckpt_file)

    # freeze weights if adapter-BERT is used
    if adapter_size is not None:
        freeze_bert_layers(bert)

    model.compile('adam', loss=crf.loss_function, metrics=[crf.accuracy])

    model.summary()

    return model

我正在使用tensorflow keras,也使用keras_contrib包来执行NER。似乎tensorflow keras软件包不能与keras_contrib软件包一起很好地工作。

回溯信息如下:

Traceback (most recent call last):
  File "F:/_gitclone3/bert_examples/bert_ner_example_eval.py", line 120, in <module>
    model = create_model(max_seq_len, adapter_size=adapter_size)
  File "F:/_gitclone3/bert_examples/bert_ner_example_eval.py", line 101, in create_model
    logits = crf(bert_output)
  File "C:\Users\yuexiang\Anaconda3\lib\site-packages\keras\engine\base_layer.py", line 443, in __call__
    previous_mask = _collect_previous_mask(inputs)
  File "C:\Users\yuexiang\Anaconda3\lib\site-packages\keras\engine\base_layer.py", line 1311, in _collect_previous_mask
    mask = node.output_masks[tensor_index]
AttributeError: 'Node' object has no attribute 'output_masks'

如何将CRF与tensorflow keras一起使用?

2 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,花了很多时间试图使事情正常进行。这是使用python 3.6.5对我有用的东西:

序列:

pip install seqeval==0.0.5

凯拉斯:

pip install keras==2.2.4

Keras-contrib(2.0.8):

git clone https://www.github.com/keras-team/keras-contrib.git

cd keras-contrib

python setup.py install

TensorFlow:

pip install tensorflow==1.14.0

执行pip list以确保您已经实际安装了这些版本(例如pip seqeval可能会自动更新您的keras)

然后在您的代码中导入,如下所示:

from keras.models import *
from keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectional, Input
from keras_contrib.layers import CRF
#etc.

希望这会有所帮助,祝您好运!

答案 1 :(得分:1)

您可以尝试使用tensorflow附加组件(如果您使用的是Tensorflow版本2)。 您可以尝试tf-crf-layer(如果您使用的是tensorflow == 1.15.0)