Search code examples
pythonmachine-learningnlpnamed-entity-recognitionflair

AttributeError: 'str' object has no attribute 'is_context_set'


I am trying to implement flair to obtain ner tags for a piece of text (doing this in colab). Encountered this error while trying tagger.predict(text). What should I do to resolve this?

Here's my code:

from flair.data import Sentence
from flair.models import SequenceTagger

text = "Apple is headquartered in Cupertino, California."
tagger = SequenceTagger.load("flair/ner-english")

tagger.predict(text)

Here's what I got:

2023-09-01 09:00:29,790 SequenceTagger predicts: Dictionary with 20 tags: <unk>, O, S-ORG, S-MISC, B-PER, E-PER, S-LOC, B-ORG, E-ORG, I-PER, S-PER, B-MISC, I-MISC, E-MISC, I-ORG, B-LOC, E-LOC, I-LOC, <START>, <STOP>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-02be6f83cf90> in <cell line: 8>()
      6 
      7 
----> 8 tagger.predict(text)
      9 print(text)
     10 print('The following NER tags are found:')

1 frames
/usr/local/lib/python3.10/dist-packages/flair/models/sequence_tagger_model.py in predict(self, sentences, mini_batch_size, return_probabilities_for_all_classes, verbose, label_name, return_loss, embedding_storage_mode, force_token_predictions)
    454                 sentences = [sentences]
    455 
--> 456             Sentence.set_context_for_sentences(cast(List[Sentence], sentences))
    457 
    458             # filter empty sentences

/usr/local/lib/python3.10/dist-packages/flair/data.py in set_context_for_sentences(cls, sentences)
   1087         previous_sentence = None
   1088         for sentence in sentences:
-> 1089             if sentence.is_context_set():
   1090                 continue
   1091             sentence._previous_sentence = previous_sentence

AttributeError: 'str' object has no attribute 'is_context_set'

Solution

  • Turn your text into a Sentence first so the underlying code has access to the necessary functions and modify the sentence object.

    from flair.data import Sentence
    from flair.models import SequenceTagger
    
    text = "Apple is headquartered in Cupertino, California."
    sentence = Sentence(text) # <---
    tagger = SequenceTagger.load("flair/ner-english")
    
    tagger.predict(sentence ) # <---
    print(sentence)
    ...