การสร้าง named entity แบบกำหนดเองใน spaCy
หาก named entity ที่มีอยู่ใน spaCy ไม่เพียงพอ สามารถสร้างขึ้นมาเองได้โดยใช้คลาส EntityRuler() ของ spaCy
EntityRuler() ช่วยให้สร้าง entity แบบกำหนดเองและเพิ่มเข้าไปใน spaCy pipeline ได้
เริ่มต้นด้วยการสร้าง instance ของ EntityRuler() และส่ง pipeline ปัจจุบัน nlp เข้าไป
จากนั้นเรียกใช้ add_patterns() บน instance นั้น พร้อมส่งดิกชันนารีที่ระบุ pattern ของข้อความที่ต้องการติดป้ายกำกับด้วย entity
เมื่อกำหนด pattern เรียบร้อยแล้ว ให้เพิ่มเข้าไปใน nlp pipeline โดยใช้ add_pipe()
เนื่องจาก Acme เป็นบริษัทเทคโนโลยี จึงกำหนดให้ pattern "smartphone" ติดป้ายกำกับด้วย entity tag "PRODUCT"
มีการ import spaCy และสร้าง doc ไว้แล้ว โดยมีข้อความที่ถอดเสียงจากไฟล์ call_4_channel_2.wav ไฟล์)
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Spoken Language Processing ด้วย Python
คำแนะนำการฝึกหัด
- Import
EntityRulerจากspacy.pipeline - เพิ่ม
"smartphone"เป็นค่าสำหรับ key"pattern" - เพิ่ม instance ของ
EntityRuler()ที่ชื่อrulerเข้าไปในnlppipeline - แสดงผล attribute ของ entity ที่อยู่ใน
doc
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import EntityRuler class
from spacy.pipeline import ____
# Create EntityRuler instance
ruler = EntityRuler(nlp)
# Define pattern for new entity
ruler.add_patterns([{"label": "PRODUCT", "pattern": ____}])
# Update existing pipeline
nlp.add_pipe(____, before="ner")
# Test new entity
for entity in doc.____:
print(entity.text, entity.label_)