Software Engineer Encyclopedia
0%
Domain 10 · Python, Machine Learning & Data Engineering · Topic 10.7

معالجة اللغة الطبيعية

Natural Language Processing Engineering

From classical text features to transformer-based NLP systems, evaluation and deployment.

  • Intermediate
  • ~12 min read
  • 14 sections
  • 1 code examples
  • 1 diagrams
  • 5 questions
  • Priority L2 · Important
  • Python · scikit-learn · Hugging Face Transformers

بعد الدرس ده هتقدر

  • تبني text classifier بـ TF-IDF وتقارن word وcharacter features.
  • تختبر متانة الموديل على نص فيه أخطاء وتحلل الأخطاء حالة بحالة.
  • تشرح الـ distributional hypothesis وتبني word embeddings من co-occurrence.

المتطلبات قبل ما تبدأ

أساسيات البرمجة والـ complexity. مش محتاج خبرة Python سابقة.

مستوى التعمق المطلوب

PRACTICALافهم NLP التقليدي والحديث، واختر التقنية حسب المهمة والبيانات والقيود.

01

أهداف التعلم والمتطلبات

Learning objectives and prerequisites
Basics

بعد الدرس، تقدر تختار تمثيل النص المناسب، تبني baseline لتصنيف النصوص، تشرح الفرق بين lexical features و embeddings، وتقيّم أخطاء NLP بدل الاكتفاء بنسبة Accuracy. افترض معرفة Python و Pandas ومبادئ ML والتقسيم الصحيح للبيانات.

  • تمييز tokenization و normalization و stemming و lemmatization.
  • فهم TF-IDF و word embeddings و contextual embeddings.
  • بناء text-classification pipeline قابلة للتقييم وإعادة الإنتاج.
  • فهم NER و semantic similarity و information extraction.
02

من النص للـ vectors

Text representation pipeline
Basics
Raw textAR / EN mixedNormalizealef, tashkeel, digitsTokenizewords / subwordsSparse: TF-IDF / BM25exact terms, codes, namesDense: embeddingsmeaning, paraphrase
Normalize, tokenize, represent: sparse (TF-IDF/BM25) and dense (embeddings) answer different questions
03

لماذا NLP؟

The representation problem
Basics

النص الخام سلسلة رموز، بينما معظم خوارزميات ML تحتاج تمثيلًا عدديًا. preprocessing يحول النص دون أن يمحو إشارات مهمة. مثلًا تحويل كل شيء إلى lowercase قد يضر مهام تمييز أسماء المنتجات أو الرموز الحساسة لحالة الأحرف. لا توجد preprocessing recipe صحيحة لكل المهام.

ابدأ بتحديد المهمة: classification يختار label، NER يحدد spans، retrieval يبحث عن نص قريب دلاليًا، extraction يحول نصًا إلى حقول. اختلاف الهدف يغير البيانات والـ metric والـ model.

04

التمثيل التقليدي: Bag of Words و TF-IDF

Sparse lexical features
Deep dive

Bag of Words يمثل المستند بتكرارات الكلمات ويتجاهل ترتيبها غالبًا. TF-IDF يخفض وزن الكلمات الشائعة في مجموعة المستندات ويرفع الكلمات المميزة نسبيًا. الناتج sparse high-dimensional vector، ويمكن استخدامه مع Logistic Regression أو Linear SVM كـ baseline قوي وسريع.

انتبه إلى leakage: fit للـ vectorizer يجب أن يحدث داخل training fold فقط. استخدم Pipeline حتى يتعلم vocabulary و IDF من التدريب، ثم يطبق التحويل على validation/test دون إعادة fit.

PythonLeakage-safe text classification pipeline
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

texts = ["delivery was fast", "package arrived late", "great support", "support never replied"]
labels = [1, 0, 1, 0]
X_train, X_test, y_train, y_test = train_test_split(
    texts, labels, test_size=0.5, random_state=7, stratify=labels
)
model = Pipeline([
    ("tfidf", TfidfVectorizer(ngram_range=(1, 2), min_df=1)),
    ("classifier", LogisticRegression(class_weight="balanced"))
])
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test), zero_division=0))

العينة هنا صغيرة للتوضيح وليست benchmark صالحًا. في مشروع حقيقي اجمع بيانات ممثلة، وافصل حسب customer أو الزمن إذا كان ذلك يعكس الاستخدام الفعلي.

05

Tokenization و Stemming و Lemmatization

Language-aware preprocessing
Basics

Tokenization يقسم النص إلى وحدات. قد تكون الكلمات أو subwords أو characters؛ subword tokenization يقلل مشكلة الكلمات غير المعروفة لكنه يجعل عدد tokens مختلفًا عن عدد الكلمات. Stemming يقطع النهايات بقواعد تقريبية، بينما lemmatization يحاول الوصول إلى الصيغة المعجمية مع الاستفادة من اللغة والسياق.

في العربية، التطبيع قد يتعامل مع أشكال الألف والتشكيل والـى/ي، لكن كل تغيير قد يدمج كلمات مختلفة أو يزيل معنى. احتفظ بالنص الأصلي، وجرّب normalization كتحويل قابل للقياس لا كحقيقة مطلقة.

06

Word Embeddings و Contextual Embeddings

From static vectors to contextual meaning
Deep dive

Word2Vec يتعلم تمثيلات كلمات من سياقاتها؛ GloVe يعتمد إحصاءات co-occurrence. التمثيل static يجعل للكلمة vector واحدًا نسبيًا، حتى لو اختلف معناها. Transformer contextual embeddings تعتمد على الجملة، فتختلف تمثيلات الكلمة حسب السياق.

لا تفترض أن cosine similarity وحدها تعني تطابقًا دلاليًا أو صحة. اختبر retrieval على مجموعة استعلامات وأحكام relevance. في semantic search اختَر embedding model ملائمًا للغة والمجال، وراقب normalization والأبعاد وإصدار النموذج.

Word Embeddings من الصفر: المعنى من الجيرة

الفكرة اللي ورا كل الـ embeddings: الكلمة بتتعرّف بالكلمات اللي بتظهر جنبها (distributional hypothesis). Word2Vec بيتعلم ده بشبكة صغيرة بتتوقع الجيران؛ الطريقة هنا بتوصل لنتيجة قريبة رياضيًا بعدّ الجيران مباشرة ثم ضغط المصفوفة.

Pythonembeddings_from_counts.py — dense word vectors from a co-occurrence matrixExecuted ✓
import numpy as np
rng = np.random.default_rng(3)

# ---- a toy corpus where meaning lives in CONTEXT: each "frame" accepts one group of words ----
GROUPS = {
    "animal":  ["cat", "dog", "horse", "rabbit"],
    "vehicle": ["car", "truck", "bus", "van"],
    "food":    ["bread", "rice", "soup", "cheese"],
}
FRAMES = {
    "animal":  ["the {} sleeps on the grass", "she feeds the {} every morning", "the {} runs in the field", "a small {} drinks water"],
    "vehicle": ["he drives the {} to work", "the {} needs new tyres", "park the {} near the road", "the {} uses too much fuel"],
    "food":    ["we eat {} for dinner", "she cooks {} with salt", "the {} tastes fresh today", "buy some {} from the market"],
}
sentences = []
for _ in range(3000):
    g = rng.choice(list(GROUPS))
    sentences.append(rng.choice(FRAMES[g]).format(rng.choice(GROUPS[g])).split())

vocab = sorted({w for s in sentences for w in s})
index = {w: i for i, w in enumerate(vocab)}

window = 3
C = np.zeros((len(vocab), len(vocab)))
for s in sentences:
    ids = [index[w] for w in s]
    for i, a in enumerate(ids):
        for b in ids[max(0, i - window): i]:
            C[a, b] += 1; C[b, a] += 1                     # count neighbours inside the window

# PPMI: how much more often do two words co-occur than chance predicts?
total, row = C.sum(), C.sum(axis=1, keepdims=True)
with np.errstate(divide="ignore", invalid="ignore"):
    pmi = np.log(C * total / (row @ row.T))
ppmi = np.where(np.isfinite(pmi) & (pmi > 0), pmi, 0.0)

U, S, _ = np.linalg.svd(ppmi)                              # compress the sparse counts into dense vectors
E = U[:, :8] * np.sqrt(S[:8])
E /= np.linalg.norm(E, axis=1, keepdims=True)

def neighbours(word, k=3):
    sims = E @ E[index[word]]
    return [f"{vocab[i]} ({sims[i]:.2f})" for i in np.argsort(-sims)[1:k + 1]]

print(f"vocabulary={len(vocab)} words, embedding size={E.shape[1]}")
for w in ["cat", "truck", "soup"]:
    print(f"  {w:<6} -> {', '.join(neighbours(w))}")
sim = lambda a, b: float(E[index[a]] @ E[index[b]])
print(f"\ncosine(cat, dog)={sim('cat', 'dog'):.2f}   cosine(cat, car)={sim('cat', 'car'):.2f}   cosine(car, bus)={sim('car', 'bus'):.2f}")
print("note: 'cat' and 'dog' NEVER appear in the same sentence in this corpus:", not any('cat' in s and 'dog' in s for s in sentences))
ConsoleOutput — captured from a real run
vocabulary=55 words, embedding size=8
  cat    -> dog (1.00), rabbit (1.00), horse (1.00)
  truck  -> car (1.00), van (1.00), bus (1.00)
  soup   -> cheese (1.00), rice (1.00), bread (1.00)

cosine(cat, dog)=1.00   cosine(cat, car)=0.00   cosine(car, bus)=1.00
note: 'cat' and 'dog' NEVER appear in the same sentence in this corpus: True

السطر الأخير هو لب الموضوع: cat و dog عمرهم ما ظهروا في نفس الجملة، ومع ذلك التشابه بينهم 1.00. هم متشابهين لأنهم بيظهروا في نفس السياقات ("the ___ sleeps on the grass")، مش لأنهم بيظهروا مع بعض. ده اللي بيخلي الـ embedding search يلاقي «سيارة» لما تدوّر على «عربية».

PPMI بيحوّل العدّ الخام لـ «قد إيه الاقتران ده أكتر من الصدفة»، فكلمات زي the اللي بتيجي مع كل حاجة ما تسيطرش. الـ SVD بيضغط المصفوفة لأبعاد قليلة بتحتفظ بالبنية الأساسية — وده اللي بيخلي كلمتين ليهم جيران متشابهين (مش متطابقين) يبقوا قريبين.

الأرقام مثالية (1.00 و0.00) لأن الـ corpus لعبة: 3 مجموعات معزولة تمامًا. في لغة حقيقية المعاني متداخلة والتشابهات بتبقى درجات. وحدود الـ static embeddings: كل كلمة ليها vector واحد، فكلمة بمعنيين ليها تمثيل واحد مخلوط. الـ transformers حلّت ده بـ contextual embeddings: الـ vector بيتحسب من الجملة كلها (شوف الـ attention في المجال 11).

موديل تصنيف تذاكر دعم وصل 98% في التقييم و70% في الإنتاج. البيانات كان فيها حقل «القسم اللي اتحوّلت له التذكرة» جوه النص. التفسير؟

نصوص عربية بلهجات مختلفة وأخطاء إملائية كتير. أنهي تمثيل كلاسيكي غالبًا هيبقى أثبت؟

07

مهام NLP العملية

Classification, NER and extraction

Text Classification

تعيين فئة للنص مثل spam أو sentiment أو intent. قِس precision/recall لكل فئة، خصوصًا مع عدم توازن البيانات.

Named Entity Recognition

تحديد spans مثل أسماء الأشخاص والمؤسسات والتواريخ. التقييم عادة span-level precision/recall/F1، وليس accuracy على كل token فقط.

Information Extraction

تحويل النص إلى schema مثل invoice fields. تحقق من الحقول والأنواع والمصدر، ولا تثق في output النموذج دون validation.

Semantic Similarity

قياس قرب المعنى أو ترتيب المرشحين. استخدم labeled pairs أو relevance judgments لتقييم الجودة.

08

Transformers في NLP

Contextual sequence modeling

Transformer يعالج tokens عبر attention و feed-forward blocks. Encoder models مثل BERT مناسبة غالبًا للفهم والتمثيل، بينما decoder-only models مناسبة لتوليد النص، وهناك encoder-decoder لمهام التحويل مثل الترجمة والتلخيص. هذه أنماط عامة وليست قاعدة مطلقة لكل نموذج حديث.

التطبيق العملي غالبًا يبدأ بنموذج pretrained ثم inference أو fine-tuning محدود. راقب truncation وطول sequence واللغة والتوزيع domain shift. تقسيم الوثائق إلى chunks قد يغير سياق NER أو extraction؛ لا تقطع span مهمًا عند الحدود.

09

التقييم وتحليل الأخطاء

Evaluate the task, not the demo

حدد وحدة التقييم: document، sentence، token، span، أو query-result pair. استخدم macro-F1 عندما تريد وزن الفئات بالتساوي، و micro-F1 عندما تهمك المحصلة عبر الأمثلة. في extraction افحص exact match و field-level accuracy، وفي retrieval افحص Recall@k و MRR أو nDCG حسب الاستخدام.

أنشئ slices حسب اللغة واللهجة وطول النص ومصدره والفئة. راجع false positives و false negatives يدويًا، وابحث عن تسرب IDs أو duplicate documents بين train و test. لا تختَر النموذج بناءً على مثالين ناجحين.

10

النشر والأمان

Production concerns

خدمة NLP تحتاج حدودًا لحجم النص وعدد tokens، timeouts، rate limits، logging يحترم الخصوصية، وإصدارات واضحة للنموذج والـ tokenizer والـ preprocessing. لا تسجل PII أو نصوصًا حساسة افتراضيًا. في multi-tenant systems يجب فرض authorization قبل إرجاع أي مستند أو نتيجة.

إذا كان inference في Python، اجعل API contract versioned ومتحققًا منه، وأعد model_version و request_id. يمكن لـ ‎.NET امتلاك business rules والهوية والصلاحيات، بينما Python يقدم inference فقط.

11

تمارين ومشروع مصغر

Practice and mastery
Practical
  1. ابنِ spam classifier باستخدام TF-IDF و Logistic Regression وقارن unigram مع bigram.
  2. أعد التجربة باستخدام pretrained transformer، مع تثبيت dataset split.
  3. حلل الأخطاء حسب طول الرسالة واللهجة والفئة.
  4. أنشئ FastAPI endpoint يعيد label و confidence و model version مع validation و tests.
لماذا نضع TfidfVectorizer داخل Pipeline؟
حتى يتم تعلم vocabulary و IDF داخل training fold فقط، ما يمنع تسرب معلومات validation/test أثناء cross-validation.
هل static word embedding يفهم اختلاف معنى الكلمة حسب السياق؟
ليس بصورة سياقية كاملة؛ contextual embeddings تنتج تمثيلًا يعتمد على الجملة.
12

مشروع NLP كامل: تصنيف تذاكر دعم من TF-IDF لتحليل الأخطاء

A text classifier: baseline, word vs character features, robustness to typos, error analysis — executed
Practical

قبل ما تجري على transformer، الـ baseline الكلاسيكي (TF-IDF + linear model) لازم يتجرّب: بيتدرّب في ثواني، بيتفسّر، وفي مهام تصنيف كتير بيوصل لنتيجة قريبة جدًا. المشروع ده بيصنّف تذاكر دعم لـ 4 أنواع، وبيختبر حاجة بتحصل في كل نظام حقيقي: نص الإنتاج فيه أخطاء إملائية ونص التدريب نضيف.

عن البيانات

الـ corpus هنا synthetic بيتولد جوه الكود (مفيش dataset نصي متاح أوفلاين في بيئة تجهيز الموسوعة). هو مصمم بحيث يكون فيه كلمات مشتركة بين الفئات، كلمات «دخيلة» من فئة تانية، وأخطاء إملائية — فالميكانيزم والمقارنة حقيقيين، لكن الأرقام المطلقة أسهل من أي بيانات حقيقية. طبّق نفس الكود على تذاكرك الفعلية قبل ما تاخد أي قرار.

Pythonticket_classifier.py — word vs character TF-IDF, clean vs noisy test sets, top features, errorsExecuted ✓
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, f1_score
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

# ---- a synthetic support-ticket corpus: 4 intents, shared filler words, overlapping vocabulary, typos ----
rng = np.random.default_rng(7)
TOPIC = {
    "billing":  "invoice charge charged refund payment card receipt subscription price billed twice amount".split(),
    "bug":      "crash crashes error freeze broken bug loading screen button upload fails exception slow".split(),
    "account":  "password login email username reset locked verify profile signin access account security".split(),
    "shipping": "delivery package courier tracking shipped late address parcel arrived damaged order warehouse".split(),
}
SHARED = "my the app please help i cannot since yesterday still after update order account again urgent need when".split()
LABELS = list(TOPIC)

def typo(word):
    if len(word) > 4 and rng.random() < 0.30:               # 30% of longer words get a character dropped
        i = rng.integers(1, len(word) - 1)
        return word[:i] + word[i + 1:]
    return word

def ticket(label, noisy):
    n_topic = rng.integers(1, 4)                            # only 1-3 topical words per ticket
    words = list(rng.choice(TOPIC[label], n_topic)) + list(rng.choice(SHARED, rng.integers(4, 9)))
    if rng.random() < 0.15:                                 # 15% mention a word from another intent
        words.append(rng.choice(TOPIC[rng.choice(LABELS)]))
    rng.shuffle(words)
    return " ".join(typo(w) if noisy else w for w in words)

def make(n, noisy):
    y = rng.integers(0, 4, n)
    return [ticket(LABELS[i], noisy) for i in y], y

X_train, y_train = make(1500, noisy=False)                  # clean training text
X_clean, y_clean = make(600, noisy=False)
X_noisy, y_noisy = make(600, noisy=True)                    # production text has typos
print("examples:", X_noisy[:2])

candidates = {
    "majority class":           DummyClassifier(strategy="most_frequent"),
    "word TF-IDF + NaiveBayes": make_pipeline(TfidfVectorizer(), MultinomialNB()),
    "word TF-IDF + LogReg":     make_pipeline(TfidfVectorizer(sublinear_tf=True), LogisticRegression(max_iter=2000, C=10)),
    "char 2-4grams + LogReg":   make_pipeline(TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4), sublinear_tf=True), LogisticRegression(max_iter=2000, C=10)),
}
fitted = {}
print(f"\n{'model':<26}{'F1 clean':>10}{'F1 typos':>10}{'features':>10}")
for name, model in candidates.items():
    fitted[name] = model.fit(X_train, y_train)
    f_clean = f1_score(y_clean, model.predict(X_clean), average="macro")
    f_noisy = f1_score(y_noisy, model.predict(X_noisy), average="macro")
    n_feat = len(model[0].vocabulary_) if name != "majority class" else 0
    print(f"{name:<26}{f_clean:10.3f}{f_noisy:10.3f}{n_feat:>10}")

best = fitted["word TF-IDF + LogReg"]
pred = best.predict(X_noisy)
print("\nword model on the typo set:\n" + classification_report(y_noisy, pred, target_names=LABELS, digits=3))
vocab = np.array(best[0].get_feature_names_out())
print("most indicative words per class:")
for i, c in enumerate(LABELS):
    print(f"  {c:<9} {', '.join(vocab[np.argsort(best[1].coef_[i])[-6:][::-1]])}")
print("most 'neutral' words (coefficients near zero for every class):", ", ".join(vocab[np.argsort(np.abs(best[1].coef_).max(axis=0))[:6]]))
wrong = [(X_noisy[i], LABELS[y_noisy[i]], LABELS[pred[i]]) for i in range(len(pred)) if pred[i] != y_noisy[i]][:3]
print("\nsample errors (text | true | predicted):")
for t, a, b in wrong:
    print(f"  {t} | {a} | {b}")
ConsoleOutput — captured from a real run
examples: ['when oder email i canot', 'help tracking sice please when when when address dlivery']

model                       F1 clean  F1 typos  features
majority class                 0.099     0.097         0
word TF-IDF + NaiveBayes       0.978     0.866        64
word TF-IDF + LogReg           0.982     0.870        64
char 2-4grams + LogReg         0.983     0.970       795

word model on the typo set:
              precision    recall  f1-score   support

     billing      0.935     0.866     0.899       149
         bug      0.895     0.901     0.898       161
     account      0.784     0.876     0.827       145
    shipping      0.877     0.834     0.855       145

    accuracy                          0.870       600
   macro avg      0.873     0.869     0.870       600
weighted avg      0.874     0.870     0.871       600

most indicative words per class:
  billing   receipt, payment, invoice, charge, price, card
  bug       freeze, slow, crashes, error, bug, broken
  account   username, locked, password, signin, security, profile
  shipping  parcel, damaged, delivery, courier, late, arrived
most 'neutral' words (coefficients near zero for every class): help, urgent, need, again, my, after

sample errors (text | true | predicted):
  when crases update cnnot since help yesterday | bug | account
  yesterdy after i account account logn passwrd subscription the need | account | billing
  oder update help urgent crahes i app order | bug | shipping

TF-IDF في جملة: وزن الكلمة في المستند = تكرارها فيه (TF) × ندرتها في المجموعة كلها (IDF). كلمة موجودة في كل التذاكر وزنها يقرب من الصفر، وكلمة نادرة ومميِّزة وزنها عالي. sublinear_tf بيستخدم 1+log(tf) عشان التكرار العاشر ما يبقاش بعشر أضعاف الأول.

العمود الأهم هو F1 typos: على النص النضيف التلات موديلات متساويين تقريبًا. على نص فيه أخطاء، الـ word model وقع حوالي 11 نقطة والـ character n-grams شبه ما اتأثرش. السبب: crahes بالنسبة للـ word model كلمة مجهولة تمامًا (مش في الـ vocabulary)، لكنها بتشارك أغلب الـ n-grams بتاعتها مع crashes. لو كنت قيّمت على بيانات نضيفة بس، كنت هتختار غلط.

الكلمات المميِّزة والمحايدة: القمة منطقية لكل فئة، والكلمات العامة (help, urgent) أوزانها قرب الصفر — الموديل اتعلم يتجاهلها من غير stop-word list. ده sanity check: لو لقيت في القمة اسم موظف أو توقيع، يبقى الموديل بيتعلم مين اللي كتب مش الموضوع.

اقرأ الأخطاء: التلاتة فيهم كلمة الموضوع مكتوبة غلط (crases, logn, crahes) فالموديل اتبقى معاه الكلمات المشتركة أو الدخيلة بس (order, subscription). تحليل 20 خطأ بالشكل ده بيقولك تعمل إيه بعدين أكتر من أي رقم إجمالي.

الطريقةبتلقط إيهاستخدمها لما
TF-IDF + linearوجود كلمات/عباراتتصنيف موضوعي، بيانات مُعلَّمة متوسطة، محتاج سرعة وتفسير — الـ baseline دايمًا
Character n-gramsأجزاء الكلمات، الأخطاء الإملائية، اللغات الغنية صرفيًا (زي العربي)نص مليان أخطاء أو لهجات أو أكواد منتجات
Embeddings ثابتة + classifierتشابه المعنى بين كلمات مختلفةبيانات مُعلَّمة قليلة، مرادفات كتير
Fine-tuned transformerالسياق وترتيب الكلمات والنفيالمعنى بيعتمد على التركيب (sentiment، NLI)، وعندك GPU وبيانات
LLM zero/few-shotتعليمات بلغة طبيعيةمفيش بيانات مُعلَّمة أصلًا، أو الفئات بتتغير — بتكلفة و latency أعلى لكل طلب
13

Named Entity Recognition: BIO Tagging وتقييم على مستوى الكيان

A token classifier with context features, tested on unseen names, scored per entity — executed
Practical

الـ NER بيحوّل «Mona Adel joined Nile Systems in Alexandria» لكيانات: شخص، شركة، مكان. تقنيًا هو تصنيف لكل token، بصيغة BIO: B- بداية كيان، I- جواه، O برا أي كيان. فيه فخّين: الموديل اللي «يحفظ» الأسماء بدل ما يتعلم السياق، والتقييم بدقة الـ tokens اللي بتخدع (أغلب الـ tokens O).

عن البيانات

الجمل synthetic من قوالب، والأسماء في الـ test مختلفة تمامًا عن التدريب — عشان نقيس التعميم مش الحفظ. الأرقام أسهل من نص حقيقي.

Pythonner.py — features per token, BIO labels, unseen-entity test set, token accuracy vs entity-level F1Executed ✓
import numpy as np
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(12)
TRAIN = {"PER": ["Mona Adel", "Omar Hassan", "Sara Nabil", "Karim Fathy", "Laila Mansour", "Youssef Zaki"],
         "ORG": ["Nile Systems", "Delta Bank", "Cairo Labs", "Pharos Tech", "Sphinx Media"],
         "LOC": ["Alexandria", "Giza", "Aswan", "Port Said", "Luxor"]}
TEST =  {"PER": ["Hana Refaat", "Tarek Samy", "Nour Elsayed"],                 # never seen in training
         "ORG": ["Horus Logistics", "Red Sea Foods", "Memphis AI"],
         "LOC": ["Tanta", "Marsa Alam", "Fayoum"]}
TEMPLATES = ["{PER} joined {ORG} in {LOC} last year", "the manager at {ORG} is {PER}", "{PER} moved from {LOC} to {LOC}",
             "{ORG} opened an office in {LOC}", "we met {PER} near {LOC} on Monday", "{ORG} hired {PER} as an engineer",
             "shipments to {LOC} are handled by {ORG}", "Dr. {PER} works for {ORG}", "the office is closed on Friday",
             "Please send the report before Monday"]

def make(n, names):
    data = []
    for _ in range(n):
        tokens, tags = [], []
        for part in rng.choice(TEMPLATES).split():
            if part.startswith("{"):
                kind = part.strip("{}")
                words = rng.choice(names[kind]).split()
                tokens += words; tags += [f"B-{kind}"] + [f"I-{kind}"] * (len(words) - 1)
            else:
                tokens.append(part); tags.append("O")
        data.append((tokens, tags))
    return data

def features(tokens, i, use_identity):
    w = tokens[i]
    f = {"is_title": w.istitle(), "is_first": i == 0, "suffix2": w[-2:].lower(),
         "prev": tokens[i - 1].lower() if i else "<s>", "next": tokens[i + 1].lower() if i + 1 < len(tokens) else "</s>",
         "prev_is_title": i > 0 and tokens[i - 1].istitle()}
    if use_identity:
        f["word"] = w.lower()                                    # lets the model memorise names
    return f

def spans(tags):
    """BIO tags -> set of (start, end, type). An entity counts only if its boundaries AND type are right."""
    out, start, kind = set(), None, None
    for i, t in enumerate(list(tags) + ["O"]):
        if start is not None and not (t.startswith("I-") and t[2:] == kind):
            out.add((start, i, kind)); start = None
        if t.startswith("B-"):
            start, kind = i, t[2:]
    return out

train, test = make(600, TRAIN), make(300, TEST)

def run(use_identity):
    Xtr = [features(t, i, use_identity) for t, _ in train for i in range(len(t))]
    ytr = [tag for _, tags in train for tag in tags]
    model = make_pipeline(DictVectorizer(), LogisticRegression(max_iter=2000, C=5)).fit(Xtr, ytr)
    tp = fp = fn = correct = total = 0
    examples = []
    for tokens, gold in test:
        pred = list(model.predict([features(tokens, i, use_identity) for i in range(len(tokens))]))
        correct += sum(p == g for p, g in zip(pred, gold)); total += len(gold)
        g, p = spans(gold), spans(pred)
        tp += len(g & p); fp += len(p - g); fn += len(g - p)
        if g != p and len(examples) < 2:
            examples.append((" ".join(tokens), sorted(g), sorted(p)))
    prec, rec = tp / max(tp + fp, 1), tp / max(tp + fn, 1)
    return correct / total, prec, rec, 2 * prec * rec / max(prec + rec, 1e-9), examples

o_share = np.mean([t == "O" for _, tags in test for t in tags])
print(f"share of 'O' tokens in the test set: {o_share:.2f}  (a model that tags everything O gets this token accuracy and entity F1 = 0)")
print(f"\n{'features':<34}{'token acc':>10}{'entity P':>10}{'entity R':>10}{'entity F1':>11}")
for label, flag in (("context + shape + word identity", True), ("context + shape only", False)):
    acc, p, r, f1, examples = run(flag)
    print(f"{label:<34}{acc:>10.3f}{p:>10.3f}{r:>10.3f}{f1:>11.3f}")
    for text, g, pr in examples[:1]:
        print(f"      error: {text}\n         gold={g}\n         pred={pr}")
ConsoleOutput — captured from a real run
share of 'O' tokens in the test set: 0.56  (a model that tags everything O gets this token accuracy and entity F1 = 0)

features                           token acc  entity P  entity R  entity F1
context + shape + word identity        0.857     0.711     0.546      0.617
      error: the manager at Red Sea Foods is Nour Elsayed
         gold=[(3, 6, 'ORG'), (7, 9, 'PER')]
         pred=[(7, 8, 'PER')]
context + shape only                   0.861     0.667     0.566      0.612
      error: the manager at Red Sea Foods is Nour Elsayed
         gold=[(3, 6, 'ORG'), (7, 9, 'PER')]
         pred=[(7, 8, 'PER')]

دقة الـ tokens بتخدع: 56% من الـ tokens O، فموديل ما بيطلّعش ولا كيان بياخد 0.56 token accuracy وهو عديم الفايدة. وهنا الـ token accuracy 0.86 والـ entity F1 حوالي 0.61 — فرق 25 نقطة بين «شكله كويس» والحقيقة. المقياس الصح entity-level: الكيان بيتحسب صح بس لو بدايته ونهايته ونوعه كلهم صح.

هوية الكلمة ما فرقتش (0.617 مقابل 0.612): الأسماء في الـ test جديدة، فحفظ الأسماء مالوش قيمة. اللي بيشتغل هو السياق (الكلمة اللي قبلها in أو joined أو Dr.) والشكل (حرف كبير). لو كنت قيّمت على أسماء من التدريب كانت الأرقام هتطلع قريبة من الكمال وكنت هتتخدع.

اقرأ مثال الخطأ: "Red Sea Foods" (3 كلمات) ما اتلقطش خالص، و"Nour Elsayed" اتلقط نصه. كل أسماء الشركات في التدريب كانت كلمتين — فالموديل ما اتعلمش إن الكيان ممكن يطول. ده distribution shift صغير، وبيتكشف بس لما تبص على الأخطاء نفسها. والـ recall أقل من الـ precision: الموديل بيفوّت كيانات أكتر ما بيخترع.

الخطوة اللي بعد كده في الواقع: الـ logistic regression بيصنّف كل token لوحده، فممكن يطلّع I-ORG بعد O (تسلسل مستحيل). الـ CRF بيضيف قيود على التسلسل. والموديلات الحديثة بتستخدم transformer بـ token classification head — نفس صيغة الـ BIO ونفس التقييم، مع مشكلة إضافية: محاذاة الـ subword tokens مع الكلمات. وللاستخراج من غير بيانات تدريب، LLM بـ structured output اختيار عملي — بتكلفة أعلى و latency أعلى لكل مستند.

موديل NER عندك: token accuracy 97%، entity F1 = 0.61. أنهي رقم تبلّغه وليه؟

14

خريطة تغطية الدرس

Learning objective coverage

تم ربط الأهداف بالمفاهيم والتمارين داخل هذا الدرس. اعتبر التغطية بداية تعلم وليست إثبات إتقان؛ أكمل التمارين واختبر الحل على بيانات ممثلة قبل استخدامه في الإنتاج.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

مصادر تعليمية ومتقدمة — Third-party & advanced reading

خريطة التغطية: 10 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionText normalization and tokenization§14
New sectionStemming and lemmatization§14
New sectionBag of Words and TF-IDF§14
New sectionWord2Vec and contextual embeddings§14
New sectionText classification§14
New sectionNamed Entity Recognition§14
New sectionSemantic similarity§14
New sectionInformation extraction§14
New sectionTransformer-based NLP§14
New sectionEvaluation and error analysis§14

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس