spaCy EntityRuler

spaCy로 배우는 자연어 처리

Azadeh Mobasher

Principal Data Scientist

spaCy EntityRuler

 

  • EntityRuler는 명명 개체를 Doc 컨테이너에 추가함
  • 단독 또는 EntityRecognizer와 함께 사용 가능
  • 정확히 일치하는 문자열에 대한 구문(문자열) 패턴:
{"label": "ORG", "pattern": "Microsoft"}
  • 각 토큰을 딕셔너리로 기술하는 토큰 패턴(리스트):
{"label": "GPE", "pattern": [{"LOWER": "san"}, {"LOWER": "francisco"}]}
spaCy로 배우는 자연어 처리

spaCy 파이프라인에 EntityRuler 추가

 

  • .add_pipe() 메서드 사용
  • 패턴 목록은 .add_patterns() 메서드로 추가

 

nlp = spacy.blank("en")
entity_ruler = nlp.add_pipe("entity_ruler")
patterns = [{"label": "ORG", "pattern": "Microsoft"},
            {"label": "GPE", "pattern": [{"LOWER": "san"}, {"LOWER": "francisco"}]}]
entity_ruler.add_patterns(patterns)
spaCy로 배우는 자연어 처리

spaCy 파이프라인에 EntityRuler 추가

 

  • .entsEntityLinker 구성 요소의 결과를 저장함

 

doc = nlp("Microsoft is hiring software developer in San Francisco.")
print([(ent.text, ent.label_) for ent in doc.ents])
[('Microsoft', 'ORG'), ('San Francisco', 'GPE')]
spaCy로 배우는 자연어 처리

EntityRuler 동작 예시

 

  • spaCy 파이프라인 구성 요소와 통합
  • 명명 개체 인식기 향상

  • EntityRuler 없는 spaCy 모델:

nlp = spacy.load("en_core_web_sm")

doc = nlp("Manhattan associates is a company in the U.S.")
print([(ent.text, ent.label_) for ent in doc.ents])
>>> [('Manhattan', 'GPE'), ('U.S.', 'GPE')]
spaCy로 배우는 자연어 처리

EntityRuler 동작 예시

 

  • 기존 ner 구성 요소 뒤에 EntityRuler 추가:
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", after='ner')
patterns = [{"label": "ORG", "pattern": [{"lower": "manhattan"}, {"lower": "associates"}]}]
ruler.add_patterns(patterns)

doc = nlp("Manhattan associates is a company in the U.S.")
print([(ent.text, ent.label_) for ent in doc.ents])
>>> [('Manhattan', 'GPE'), ('U.S.', 'GPE')]
spaCy로 배우는 자연어 처리

EntityRuler 동작 예시

 

  • 기존 ner 구성 요소 앞에 EntityRuler 추가:
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", before='ner')
patterns = [{"label": "ORG", "pattern": [{"lower": "manhattan"}, {"lower": "associates"}]}]
ruler.add_patterns(patterns)

doc = nlp("Manhattan associates is a company in the U.S.")
print([(ent.text, ent.label_) for ent in doc.ents])
>>> [('Manhattan associates', 'ORG'), ('U.S.', 'GPE')]
spaCy로 배우는 자연어 처리

연습해 봅시다!

spaCy로 배우는 자연어 처리

Preparing Video For Download...