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

رياضيات ML بالحدس والتطبيق

Math for Machine Learning

Linear algebra, probability, statistics, gradients, tensors and embedding similarity.

  • Intermediate
  • ~17 min read
  • 21 sections
  • 15 code examples
  • 1 diagrams
  • 10 questions
  • Priority L3 · Optional
  • NumPy · Matplotlib

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

  • تكتب gradient descent وتفسّر علاقة الـ learning rate بانحناء الـ loss.
  • تطبّق Bayes على حدث نادر وتفسّر ليه أغلب الإنذارات كاذبة.
  • تحسب entropy وcross-entropy وKL وتربطهم بالـ loss والـ drift.
  • تبني PCA من الـ covariance matrix والـ eigenvectors.

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

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

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

BASICS (CONCEPTS)الرياضيات اللي هتفهمك الموديل بيتعلم إزاي. ابدأ بالحدس البصري، وبعدين بالكود في NumPy، ومش لازم إثباتات رياضية كاملة.

01

الرياضيات المطلوبة فعلًا لمهندس AI

Intuition before proofs
Basics

الهدف ليس تحويلك إلى باحث رياضي. المطلوب أن تفهم ما الذي تمثله الأرقام داخل النموذج: vector للخصائص، matrix لمجموعة عينات أو weights، probability لعدم اليقين، و gradient لاتجاه تقليل الخطأ. ابدأ بالرسم والأمثلة الصغيرة ثم نفّذها بـ NumPy.

قاعدة مهمة: shape جزء من معنى البيانات. مصفوفة (100, 5) قد تعني 100 صف و5 features. كثير من أخطاء ML ليست أخطاء رياضية عميقة بل خلط محاور أو تسريب بيانات أو مقارنة مقاييس غير متوافقة.

02

Gradient descent في رسمة

Gradient descent on a loss surface
Basics
minimumlr too large → overshoot / divergelr too small → painfully slowlossweight
Each step moves against the gradient; the learning rate sets the step size
03

Vectors و Matrices و Dot Product

Linear algebra for features and embeddings
Practical

الـ vector قائمة مرتبة من القيم، والـ matrix مجموعة vectors. Dot product بين متجهين يساوي مجموع حاصل ضرب العناصر المتناظرة، ويقيس alignment ويتحول إلى similarity بعد normalization. Matrix multiplication يربط تمثيلًا بآخر؛ الأبعاد الداخلية لازم تتطابق: (m,n) @ (n,p) → (m,p).

Transpose يبدّل المحاور. Identity matrix لا تغيّر vector عند الضرب. Inverse موجود فقط للمصفوفات المربعة غير singular، وغالبًا لا تحسب inverse صراحةً لحل نظام خطي؛ استخدم solve لأسباب عددية.

PythonLinear algebra for features and embeddings
import numpy as np
x = np.array([1.0, 2.0, 3.0])
y = np.array([2.0, 0.0, 1.0])
print(x @ y)                 # 5.0
A = np.array([[1., 2.], [3., 4.]])
print(A.T)
print(np.linalg.solve(A, np.array([5., 11.])))
04

Norms و Distances و Cosine Similarity

Geometry behind nearest neighbors
Practical

L1 norm مجموع القيم المطلقة، و L2 norm الجذر التربيعي لمجموع المربعات. Euclidean distance تقيس المسافة المباشرة، و cosine similarity تقيس زاوية الاتجاه لا الحجم. لهذا قد تكون cosine مفيدة مع embeddings، لكنها ليست دائمًا أفضل مقياس؛ اختَر metric المتوافق مع embedding model وطريقة فهرسته.

Normalize vectors إذا كان المقياس يتطلب ذلك، وتعامل مع zero vectors لأن cosine غير معرّفة لها. لا تقارن embeddings من نماذج أو إصدارات مختلفة دون إعادة الفهرسة والتحقق.

PythonGeometry behind nearest neighbors
import numpy as np
from numpy.linalg import norm

a = np.array([1., 2., 0.])
b = np.array([2., 1., 0.])
cosine = (a @ b) / (norm(a) * norm(b))
print("L2 distance:", norm(a - b))
print("Cosine:", round(float(cosine), 4))
05

Probability و Statistics و Sampling

Reasoning about uncertain data
Basics

Mean حساس للقيم الشاذة، median أكثر مقاومة لها، variance تقيس التشتت بوحدات مربعة و standard deviation بنفس وحدة القياس. Percentiles تصف التوزيع؛ p95 latency أهم غالبًا من المتوسط. Correlation تقيس association ولا تثبت causation.

افهم conditional probability: احتمال A مع العلم أن B حدث. Bayes تربط الاحتمال السابق بالدليل. Sampling bias يجعل العينة لا تمثل المجتمع، و data leakage يجعل معلومات من المستقبل أو target تتسرب إلى التدريب. Confidence interval يصف عدم اليقين في تقدير، وليس احتمالًا مباشرًا أن قيمة ثابتة تقع داخل فترة بعينها.

تعرف على Normal و Bernoulli و Binomial و Poisson و Uniform، وعلى Law of Large Numbers و Central Limit Theorem كحدس، لا تحفظ صيغًا بلا فهم.

PythonReasoning about uncertain data
import numpy as np
x = np.array([10, 11, 12, 13, 100])
print(np.mean(x), np.median(x))
print(np.percentile(x, [50, 95]))
print(np.std(x, ddof=1))
06

Derivatives و Gradient Descent

How models reduce a loss
Basics

المشتقة تقيس حساسية output لتغيير صغير في input. Gradient يجمع المشتقات الجزئية لكل parameter، واتجاهه يشير إلى أسرع زيادة محلية؛ لذلك نتحرك عكسه لتقليل loss. Learning rate يحدد حجم الخطوة: كبير جدًا قد يتذبذب أو يفشل، وصغير جدًا يجعل التدريب بطيئًا.

Chain rule تسمح بحساب مشتقة تركيب دوال؛ وهي أساس backpropagation. Cross-entropy تقيس mismatch بين توزيع متوقع و target distribution، و Softmax تحول logits إلى توزيع احتمالي لكن يجب استخدام implementation مستقرة عدديًا مثل log-sum-exp. Entropy/KL divergence مفاهيم لفهم uncertainty واختلاف التوزيعات.

PythonHow models reduce a loss
# Gradient descent for f(w) = (w - 3)^2
w, learning_rate = 0.0, 0.1
for step in range(20):
    gradient = 2 * (w - 3)
    w -= learning_rate * gradient
print(round(w, 3))  # approaches 3
07

Tensors و Broadcasting و PCA/SVD

Shapes, projections and dimensionality
Practical

Tensor تعميم للمصفوفات متعددة الأبعاد. Broadcasting يسمح بعمليات بين shapes متوافقة وفق قواعد المحاور؛ افحص shape صراحةً. Eigenvectors تشرح اتجاهات لا تتغير إلا في scale تحت تحويل matrix، و eigenvalues مقدار هذا التغير. PCA تبحث عن اتجاهات تفسر أكبر variance بعد centering/scaling مناسبين. SVD تفكك matrix إلى مكونات وتفيد في compression و low-rank approximation.

هذه مفاهيم تكفيك لقراءة نتائج النماذج وفهم embeddings والـ dimensionality reduction؛ لا تحتاج إثباتات كاملة في المسار الحالي.

PythonShapes, projections and dimensionality
X = np.array([[1., 2.], [3., 4.], [5., 6.]])
centered = X - X.mean(axis=0)
U, singular_values, Vt = np.linalg.svd(centered, full_matrices=False)
projected = centered @ Vt.T[:, :1]
print(projected.shape)  # (3, 1)
08

اختيار المقياس الرياضي الصحيح

Metric selection and numerical pitfalls
Pitfalls

لا تستخدم cosine لمجرد أن المنتج اسمه vector search. قارن metric مع training objective والـ embedding provider. لا تخلط correlation مع similarity، ولا accuracy مع probability calibration. راقب overflow/underflow، division by zero، NaN/Inf، واختلاف precision بين float32 و float64. اختبر edge cases مثل empty vectors و constant columns.

المستوى المطلوبافهم linear algebra و statistics و gradient descent حدسيًا وطبّقها بـ NumPy. التعمق في proofs و optimization theory مؤجل ما لم تتجه لأبحاث أو تدريب نماذج كبيرة.
PythonMetric selection and numerical pitfalls
def safe_cosine(a, b):
    a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
    denom = np.linalg.norm(a) * np.linalg.norm(b)
    if denom == 0:
        raise ValueError("Cosine similarity is undefined for zero vectors")
    return float(np.dot(a, b) / denom)

print(round(safe_cosine([1, 0], [0.8, 0.6]), 3))
09

معمل NumPy: Shapes و Broadcasting

Debug tensor shapes
Practical

ابدأ كل عملية tensor بسؤال: ما معنى كل axis؟ مثال (batch, features) يختلف عن (sequence, batch, embedding). axis=0 يجمع عبر الصفوف، و axis=1 عبر الأعمدة في matrix ثنائية الأبعاد. Broadcasting يعمل من آخر dimension إلى الأول؛ كل بُعدين متوافقان إذا تساويا أو كان أحدهما 1. اطبع shapes أثناء التطوير واكتب assertions.

أخطاء شائعة: استخدام * بدل @ للمصفوفات، جمع على axis خطأ، flatten وفقد structure، أو broadcasting ينتج مصفوفة أكبر مما تتوقع. لا تعالجها بتغيير shape عشوائي؛ ارسم الأبعاد واكتب expected shape قبل التنفيذ.

PythonDebug tensor shapes
X = np.arange(12).reshape(4, 3)       # 4 samples, 3 features
mean = X.mean(axis=0)                  # shape (3,)
centered = X - mean                    # broadcast across 4 rows
assert centered.shape == (4, 3)
print(centered.mean(axis=0))            # approximately [0, 0, 0]
في X shape=(100, 8)، ماذا يعني axis=0 عند mean؟
يعني حساب متوسط كل feature عبر 100 sample، فتكون النتيجة shape=(8,).
10

من Cosine Similarity إلى Embedding Retrieval

The math-to-RAG bridge
Practical

لو عندك query vector و document vectors، cosine similarity تقارن اتجاهاتهم. لكن retrieval quality تتأثر بالـ embedding model، chunking، domain language، query wording، و ACL filters. لا تستخدم cosine scores كاحتمالات. اعمل labeled query set فيه relevant chunks، ثم قِس Recall@k و MRR وقارن cosine مع dot product إذا كان model موصى به.

Normalization يجعل dot product مساويًا cosine similarity للمتجهات unit length. لكن بعض embedding models تدربت على dot product أو metric محدد؛ اتبع توصية النموذج ولا تغيّر normalization عشوائيًا. Embedding dimensions ليست قابلة للمقارنة بين providers.

PythonThe math-to-RAG bridge
def normalize_rows(matrix):
    matrix = np.asarray(matrix, dtype=np.float32)
    norms = np.linalg.norm(matrix, axis=1, keepdims=True)
    if np.any(norms == 0):
        raise ValueError("zero embedding encountered")
    return matrix / norms

vectors = normalize_rows(np.array([[1, 2], [2, 1]], dtype=np.float32))
query = normalize_rows(np.array([[1, 1]], dtype=np.float32))
scores = query @ vectors.T
print(scores.shape)  # (1, 2)
11

Loss Functions و Optimization عمليًا

What exactly is the model minimizing?
Basics

Loss function تحوّل جودة prediction إلى scalar يمكن تحسينه. MSE يعاقب الأخطاء الكبيرة تربيعيًا، MAE أكثر robust نسبيًا، و cross-entropy تقيس توافق التوزيع المتوقع مع target. اختيار loss يؤثر في gradient وسلوك النموذج؛ لا تقارن losses مختلفة دون فهم scale والمعنى.

Convex loss لها optimum عالمي ضمن افتراضات محددة، بينما deep networks non-convex. Local minima/saddle points جزء من optimization landscape. عمليًا راقب train/validation loss curves، learning rate، gradient explosion/vanishing، و numerical stability. إذا loss = NaN، افحص input NaNs، division by zero، overflow، learning rate، و log(0).

12

Bayes و Uncertainty في قرارات المنتج

Probabilities are conditional on assumptions
Basics

Bayes theorem: P(A|B)=P(B|A)P(A)/P(B). الفكرة العملية أن prior prevalence يؤثر على posterior. عند اكتشاف churn أو fraud نادر، حتى classifier جيد قد ينتج false positives كثيرة إذا لم نراعِ base rate. لذلك precision تتغير مع prevalence، والـ calibration مهمة.

Sampling bias يجعل training distribution مختلفًا عن production. Confidence interval يوضح uncertainty في estimate؛ p-value ليس احتمال أن فرضية العدم صحيحة. لا تجعل statistical significance بديلًا عن business significance أو حجم أثر مفيد.

13

Gradient Descent من أول سطر: المشتقة، الـ Learning Rate، والتباعد

Linear regression by gradient descent, checked against the closed-form solution
Deep dive

تدريب أي موديل — من linear regression لحد LLM — هو نفس الحلقة: احسب الـ loss، احسب اتجاه النزول (الـ gradient)، خُد خطوة صغيرة عكسه. الكود ده بيعملها على مسألة ليها حل تحليلي معروف، عشان تتأكد إن النزول وصل للإجابة الصح فعلًا.

L(w) = mean((Xw − y)²) → ∇L = (2/n)·Xᵀ(Xw − y) → w ← w − η·∇L
Pythongradient_descent.py — three learning rates, one of them divergesExecuted ✓
import numpy as np
rng = np.random.default_rng(0)

n = 200
X = np.c_[np.ones(n), rng.normal(size=(n, 2))]          # bias column + 2 features
true_w = np.array([4.0, 2.5, -1.5])
y = X @ true_w + rng.normal(0, 0.5, n)

closed_form = np.linalg.lstsq(X, y, rcond=None)[0]       # the exact minimiser, for comparison

def gradient_descent(lr, steps=200):
    w = np.zeros(3)
    for step in range(1, steps + 1):
        grad = 2 / n * X.T @ (X @ w - y)                 # direction of steepest INCREASE
        w -= lr * grad                                   # so we step the other way
        if not np.isfinite(w).all():
            return w, step, float("inf")
    return w, steps, float(np.mean((X @ w - y) ** 2))

print("closed form  w =", np.round(closed_form, 3))
for lr in (0.001, 0.1, 1.1):
    w, steps, loss = gradient_descent(lr)
    status = "DIVERGED" if not np.isfinite(loss) or loss > 1e6 else f"loss={loss:.4f}"
    print(f"lr={lr:<6} after {steps:>3} steps  w = {np.round(w, 3)}  {status}")

# the largest stable step is set by the curvature: lr < 2 / (largest eigenvalue of the Hessian)
hessian = 2 / n * X.T @ X
print(f"\nlargest Hessian eigenvalue = {np.linalg.eigvalsh(hessian).max():.3f}  =>  stable only if lr < {2 / np.linalg.eigvalsh(hessian).max():.3f}")
ConsoleOutput — captured from a real run
closed form  w = [ 3.999  2.475 -1.44 ]
lr=0.001  after 200 steps  w = [ 1.241  0.668 -0.419]  loss=10.7662
lr=0.1    after 200 steps  w = [ 3.999  2.475 -1.44 ]  loss=0.2458
lr=1.1    after 200 steps  w = [-4.78190633e+28  4.64353580e+28  1.59669335e+28]  DIVERGED

largest Hessian eigenvalue = 2.174  =>  stable only if lr < 0.920

lr صغير قوي: ماشي في الاتجاه الصح لكن بعد 200 خطوة لسه بعيد. lr مناسب: وصل لنفس أرقام الحل التحليلي. lr كبير: كل خطوة بتعدّي القاع وتطلع على الناحية التانية أعلى من ما كانت — الـ loss بتكبر لحد ما تنفجر.

السطر الأخير بيربط الجبر بالتدريب: أقصى learning rate مستقر بيتحدد بأكبر eigenvalue لمصفوفة الانحناء (Hessian). عشان كده features بمقاييس مختلفة جدًا (انحناء حاد في اتجاه ومسطح في التاني) بتخلي التدريب صعب، وعشان كده الـ normalization والـ optimizers التكيّفية (Adam) موجودين.

14

Bayes، Entropy، Cross-Entropy، KL: الاحتمالات اللي بتستخدمها كل يوم

Base-rate reasoning and the information-theory quantities behind every classification loss
Deep dive
Pythonprobability.py — Bayes with a rare class; entropy, cross-entropy and KL divergenceExecuted ✓
import numpy as np

# ---------- Bayes: a fraud detector that is "95% accurate" ----------
p_fraud = 0.002                     # base rate: 2 in 1000 transactions
sensitivity = 0.95                  # P(alert | fraud)
false_positive_rate = 0.05          # P(alert | legit)

p_alert = sensitivity * p_fraud + false_positive_rate * (1 - p_fraud)
p_fraud_given_alert = sensitivity * p_fraud / p_alert
print(f"P(fraud | alert) = {p_fraud_given_alert:.3f}   -> out of 1000 alerts, about {round(1000 * p_fraud_given_alert)} are real fraud")

# ---------- information theory ----------
def entropy(p):
    p = np.asarray(p, float); p = p[p > 0]
    return float(-(p * np.log2(p)).sum()) + 0.0        # + 0.0 turns -0.0 into 0.0

def cross_entropy(p, q):
    p, q = np.asarray(p, float), np.asarray(q, float)
    return float(-(p[p > 0] * np.log2(q[p > 0])).sum())

print("\nentropy (bits) = how uncertain a distribution is:")
for name, dist in [("fair coin", [0.5, 0.5]), ("biased coin", [0.9, 0.1]), ("certain", [1.0, 0.0]), ("uniform over 8", [1 / 8] * 8)]:
    print(f"  {name:<15} {entropy(dist):.3f}")

truth = [1, 0, 0]                   # the correct class is the first one (one-hot)
print("\ncross-entropy of a prediction against the true class (bits):")
for name, pred in [("confident and right", [0.90, 0.05, 0.05]), ("unsure", [0.34, 0.33, 0.33]), ("confident and WRONG", [0.01, 0.98, 0.01])]:
    print(f"  {name:<21} {cross_entropy(truth, pred):.3f}")

p, q = [0.7, 0.2, 0.1], [0.5, 0.3, 0.2]
kl_pq = cross_entropy(p, q) - entropy(p)
kl_qp = cross_entropy(q, p) - entropy(q)
print(f"\nKL(p||q) = {kl_pq:.4f}   KL(q||p) = {kl_qp:.4f}   (not symmetric)")
print(f"identity check: H(p) + KL(p||q) = {entropy(p) + kl_pq:.4f} = cross-entropy(p, q) = {cross_entropy(p, q):.4f}")
ConsoleOutput — captured from a real run
P(fraud | alert) = 0.037   -> out of 1000 alerts, about 37 are real fraud

entropy (bits) = how uncertain a distribution is:
  fair coin       1.000
  biased coin     0.469
  certain         0.000
  uniform over 8  3.000

cross-entropy of a prediction against the true class (bits):
  confident and right   0.152
  unsure                1.556
  confident and WRONG   6.644

KL(p||q) = 0.1228   KL(q||p) = 0.1328   (not symmetric)
identity check: H(p) + KL(p||q) = 1.2796 = cross-entropy(p, q) = 1.2796

Bayes: كاشف «دقته 95%» على حدث نادر، ومع ذلك أغلب الإنذارات كاذبة. السبب الـ base rate: المعاملات السليمة أكتر بـ 500 مرة، فـ 5% منها أكتر بكتير من 95% من الاحتيال الحقيقي. ده نفس سبب إن الـ accuracy مضللة مع الـ class imbalance، ونفس سبب أهمية الـ precision.

Cross-entropy هي الـ loss بتاعة التصنيف: مع one-hot truth بتتبسّط لـ −log(احتمال الـ class الصح). لاحظ إن «واثق وغلطان» بيتعاقب أضعاف «مش متأكد» — ده اللي بيدفع الموديل يبقى calibrated. ونفس الكمية دي هي الـ loss اللي الـ LLM بيتدرّب عليها (توقع الـ token الجاي)، والـ perplexity هي 2^cross-entropy.

KL divergence: المسافة «الزيادة» اللي بتدفعها لما تستخدم q بدل التوزيع الحقيقي p. مش متماثلة. بتستخدمها فعليًا في: قياس الـ drift، الـ knowledge distillation، والـ VAEs. والمعادلة الأخيرة بتقول إن تقليل الـ cross-entropy = تقليل الـ KL (لأن H(p) ثابتة) — يعني التدريب بيقرّب توزيع الموديل من توزيع البيانات.

15

Eigenvectors و PCA: الجبر الخطي وهو بيشتغل

PCA built from the covariance matrix and verified against scikit-learn
Deep dive
Pythonpca_from_scratch.py — covariance → eigen-decomposition → projectionExecuted ✓
import numpy as np
from sklearn.decomposition import PCA
rng = np.random.default_rng(1)

# correlated 2-D data: most of the variation lies along one diagonal direction
z = rng.normal(size=(500, 2)) * [3.0, 0.5]
angle = np.deg2rad(30)
R = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
X = z @ R.T + [10, 5]

Xc = X - X.mean(axis=0)                         # 1) centre
C = Xc.T @ Xc / (len(X) - 1)                    # 2) covariance matrix
values, vectors = np.linalg.eigh(C)             # 3) eigen-decomposition (symmetric matrix)
order = np.argsort(values)[::-1]
values, vectors = values[order], vectors[:, order]

print("covariance matrix:\n", np.round(C, 3))
print("eigenvalues (variance along each principal axis):", np.round(values, 3))
print("explained variance ratio:", np.round(values / values.sum(), 3))
print("first principal direction:", np.round(vectors[:, 0], 3), f"(angle = {np.degrees(np.arctan2(vectors[1, 0], vectors[0, 0])) % 180:.1f} degrees; data was rotated by 30)")

v = vectors[:, 0]
print("check C·v = λ·v :", np.allclose(C @ v, values[0] * v))

projected = Xc @ vectors[:, :1]                 # 4) project onto the top component: 2-D -> 1-D
reconstructed = projected @ vectors[:, :1].T + X.mean(axis=0)
print(f"mean reconstruction error after dropping 1 of 2 dimensions: {np.mean(np.linalg.norm(X - reconstructed, axis=1)):.3f}")

sk = PCA(n_components=2).fit(X)
print("matches scikit-learn:", np.allclose(sk.explained_variance_, values), np.allclose(np.abs(sk.components_[0]), np.abs(v)))
ConsoleOutput — captured from a real run
covariance matrix:
 [[6.468 3.512]
 [3.512 2.235]]
eigenvalues (variance along each principal axis): [8.452 0.251]
explained variance ratio: [0.971 0.029]
first principal direction: [-0.871 -0.492] (angle = 29.5 degrees; data was rotated by 30)
check C·v = λ·v : True
mean reconstruction error after dropping 1 of 2 dimensions: 0.402
matches scikit-learn: True True

الـ eigenvector هو اتجاه المصفوفة مش بتلفّه، بتمطّه بس بمقدار الـ eigenvalue (C·v = λ·v — واتأكدنا منها عدديًا). لمصفوفة الـ covariance: الـ eigenvectors هي اتجاهات أقصى تباين، والـ eigenvalues هي مقدار التباين في كل اتجاه.

الزاوية طلعت 30° — نفس الدوران اللي ولّدنا بيه البيانات. PCA «اكتشف» المحور الحقيقي من غير ما نقوله.

فين بتقابل ده في الـ AI؟ تقليل أبعاد الـ embeddings للعرض أو التخزين، الـ whitening، تحليل الانحناء في الـ optimization (القسم الأول)، والـ low-rank approximation اللي عليها LoRA: تحديث مصفوفة كبيرة بحاصل ضرب مصفوفتين صغيرتين.

اختبار طبي حساسيته 99% ونسبة الإيجابي الكاذب 1%، والمرض بيصيب 1 من كل 10,000. شخص طلع إيجابي. احتمال إنه مريض فعلًا تقريبًا؟

الـ loss بتتذبذب بعنف وبتكبر مع كل step. أول حاجة تجربها؟

16

Hypothesis Testing و A/B Tests: إمتى تصدّق الرقم

Sample size, power, peeking, the winner's curse and multiple comparisons — simulated over thousands of experiments
Practical

نموذج جديد رفع الـ conversion من 10% لـ 10.8% على ألفين مستخدم. ده تحسّن ولا حظ؟ الـ hypothesis test بيجاوب على سؤال محدد: لو مفيش فرق حقيقي، احتمال أشوف فرق بالحجم ده أو أكبر قد إيه؟ ده الـ p-value. مش احتمال إن النموذج الجديد أحسن، ومش حجم التحسّن.

  • alpha (0.05): نسبة الـ false positives اللي قابلها لما مفيش فرق.
  • Power (0.80): احتمال إنك تكتشف الفرق لما يكون موجود فعلًا. بتتحدد بحجم العينة.
  • حجم العينة بيتحسب قبل التجربة من أصغر فرق يهمّك، مش بعدها.

الـ lab بيحاكي آلاف التجارب عشان تشوف القواعد دي بتتكسر إزاي لما تتجاهلها.

Pythonab_test.py — sample size, power, peeking, winner's curse and multiple metricsExecuted ✓
import numpy as np
from scipy import stats

rng = np.random.default_rng(42)

def z_test(conv_a, n_a, conv_b, n_b):
    """Two-proportion z-test, two-sided."""
    p = (conv_a + conv_b) / (n_a + n_b)
    se = np.sqrt(p * (1 - p) * (1 / n_a + 1 / n_b))
    z = (conv_b / n_b - conv_a / n_a) / se
    return 2 * stats.norm.sf(abs(z))

def sample_size(p, lift, alpha=0.05, power=0.80):
    """Users per arm needed to detect an absolute lift."""
    za, zb = stats.norm.ppf(1 - alpha / 2), stats.norm.ppf(power)
    p2 = p + lift
    return int(np.ceil((za + zb) ** 2 * (p * (1 - p) + p2 * (1 - p2)) / lift ** 2))

BASE = 0.10
print("1) users per arm to detect a lift on a 10% baseline (alpha 0.05, power 0.80)")
for lift in (0.05, 0.02, 0.01, 0.005):
    print(f"   +{lift*100:>4.1f} points -> {sample_size(BASE, lift):>7,} per arm")

def simulate(n, lift, runs=4000):
    a = rng.binomial(n, BASE, runs)
    b = rng.binomial(n, BASE + lift, runs)
    return np.array([z_test(x, n, y, n) for x, y in zip(a, b)])

print("\n2) what the p-value does over 4,000 simulated experiments")
p_null = simulate(2000, 0.0)
print(f"   no real difference, n=2,000:  'significant' in {np.mean(p_null < 0.05):.1%} of runs (false positives)")
for n in (500, 2000, 15000):
    p = simulate(n, 0.01)
    print(f"   real +1 point lift, n={n:>6,}: detected in {np.mean(p < 0.05):.1%} of runs (power)")

print("\n3) peeking: check every 500 users and stop at the first p < 0.05 (no real difference)")
runs, step, looks = 4000, 500, 20
a = rng.binomial(step, BASE, (runs, looks)).cumsum(axis=1)
b = rng.binomial(step, BASE, (runs, looks)).cumsum(axis=1)
n = step * np.arange(1, looks + 1)
pvals = np.array([[z_test(a[r, j], n[j], b[r, j], n[j]) for j in range(looks)] for r in range(runs)])
print(f"   one look at the end:      {np.mean(pvals[:, -1] < 0.05):.1%} false positives")
for k in (5, 10, 20):
    idx = np.linspace(looks / k - 1, looks - 1, k).astype(int)
    print(f"   stop at any of {k:>2} looks:  {np.mean((pvals[:, idx] < 0.05).any(axis=1)):.1%} false positives")
bonf = 0.05 / looks
print(f"   20 looks, Bonferroni alpha {bonf:.4f}: {np.mean((pvals < bonf).any(axis=1)):.1%} false positives")

print("\n4) winner's curse: the lift reported by underpowered tests that came out significant")
n, lift = 2000, 0.01
a = rng.binomial(n, BASE, 20000); b = rng.binomial(n, BASE + lift, 20000)
obs = (b - a) / n
sig = np.array([z_test(x, n, y, n) for x, y in zip(a, b)]) < 0.05
print(f"   true lift {lift:.3f}; mean observed over all runs {obs.mean():.4f}; "
      f"over 'significant' wins only {obs[sig & (obs > 0)].mean():.4f} "
      f"({obs[sig & (obs > 0)].mean() / lift:.1f}x the truth)")

print("\n5) twenty metrics, no real effect on any of them")
def null_metric():
    x, y = rng.binomial(2000, BASE, 2)
    return z_test(x, 2000, y, 2000)

m = np.array([[null_metric() for _ in range(20)] for _ in range(2000)])
print(f"   at least one 'significant' metric: {np.mean((m < 0.05).any(axis=1)):.1%} of experiments")
print(f"   with Bonferroni (0.05/20):        {np.mean((m < 0.05 / 20).any(axis=1)):.1%}")
ConsoleOutput — captured from a real run
1) users per arm to detect a lift on a 10% baseline (alpha 0.05, power 0.80)
   + 5.0 points ->     683 per arm
   + 2.0 points ->   3,839 per arm
   + 1.0 points ->  14,749 per arm
   + 0.5 points ->  57,760 per arm

2) what the p-value does over 4,000 simulated experiments
   no real difference, n=2,000:  'significant' in 5.3% of runs (false positives)
   real +1 point lift, n=   500: detected in 7.2% of runs (power)
   real +1 point lift, n= 2,000: detected in 17.4% of runs (power)
   real +1 point lift, n=15,000: detected in 79.7% of runs (power)

3) peeking: check every 500 users and stop at the first p < 0.05 (no real difference)
   one look at the end:      5.0% false positives
   stop at any of  5 looks:  14.2% false positives
   stop at any of 10 looks:  18.9% false positives
   stop at any of 20 looks:  24.6% false positives
   20 looks, Bonferroni alpha 0.0025: 1.8% false positives

4) winner's curse: the lift reported by underpowered tests that came out significant
   true lift 0.010; mean observed over all runs 0.0099; over 'significant' wins only 0.0243 (2.4x the truth)

5) twenty metrics, no real effect on any of them
   at least one 'significant' metric: 63.0% of experiments
   with Bonferroni (0.05/20):        4.5%

1) حجم العينة بيزيد بمربع الدقة: عشان تكتشف +5 نقط محتاج 683 مستخدم في كل مجموعة، ولـ +1 نقطة محتاج 14,749، ولنص نقطة 57,760. نص الفرق = أربع أضعاف العينة. لو الـ traffic بتاعك ما يكفيش، التجربة مش هتجاوب مهما استنيت أسبوع.

2) العينة الصغيرة ما بتشوفش: من غير فرق حقيقي، 5.3% من التجارب طلعت «significant»، وده الـ alpha بالظبط. ومع فرق حقيقي +1 نقطة، ألفين مستخدم بيكتشفوه في 17.4% بس من المرات. يعني «مفيش فرق significant» على عينة صغيرة معناها «ما عرفناش»، مش «مفيش فرق».

3) الـ peeking: لو بتبص على النتيجة كل 500 مستخدم وتقف أول ما p تنزل تحت 0.05، الـ false positives بتطلع من 5.0% لـ 24.6% مع 20 نظرة، ومفيش أي فرق حقيقي. الحل: حدد حجم العينة مقدمًا وبص مرة واحدة، أو استخدم تصحيح. Bonferroni هنا نزّلها لـ 1.8%، وهو متحفظ زيادة؛ الطرق الـ sequential المخصوصة بتدّي power أحسن.

4) Winner's curse: في التجارب الضعيفة اللي «كسبت»، الفرق المقاس كان 2.4 ضعف الفرق الحقيقي. اللي بيعدّي الفلتر هو اللي الحظ نفخه. عشان كده التحسّن اللي اتعلن بعد A/B test صغير غالبًا بيصغر في الـ production.

5) عشرين metric: من غير أي تأثير حقيقي، 63.0% من التجارب فيها metric واحد على الأقل «significant». حدد metric أساسي واحد قبل التجربة، والباقي للمراقبة.

في تقييم النماذج: نفس المنطق بالظبط لما تقارن نموذجين على test set. فرق 1% في الـ accuracy على 500 مثال جوه الضوضاء. احسب confidence interval (bootstrap على الـ test set) قبل ما تقول إن نموذج أحسن.

تجربة A/B اتخطط لها 15,000 مستخدم لكل مجموعة. بعد 3,000 الـ p-value بقت 0.03. تعمل إيه؟

الـ p-value = 0.04. أنهي جملة صح؟

17

اختبر فهمك

Knowledge Check
Practical
متى يتساوى dot product مع cosine similarity؟
عندما يكون المتجهان normalized إلى unit length؛ عندها dot product يساوي cosine.
هل correlation العالية تثبت أن feature تسبب target؟
لا. الارتباط لا يثبت السببية وقد ينتج عن confounders أو sampling bias.

اختبار الإتقان المهني

متى تستخدم finite-difference gradient checking؟
للتحقق من صحة مشتقات custom operations/loss أثناء التطوير، وليس كبديل عن backpropagation في التدريب الفعلي.
لماذا لا يثبت ROC-AUC أن الاحتمالات calibrated؟
ROC-AUC يقيس قدرة الترتيب بين positive و negative، بينما calibration تقيس مدى تطابق الاحتمال المتوقع مع التكرار الفعلي.
هل PCA يضمن الحفاظ على المعلومات المهمة لمهمة التصنيف؟
لا؛ PCA يحافظ على اتجاهات variance وليس بالضرورة الاتجاهات الأكثر ارتباطًا بالـ target.
18

Matrix Calculus: Shapes, Jacobians and Gradients

Derivatives for vectorized models
Deep dive

في ML نادرًا ما تكون parameter واحدة؛ غالبًا لدينا vector أو matrix من parameters. المشتقة العادية تصبح gradient عندما يكون الناتج scalar والمدخل vector، وتصبح Jacobian عندما يكون الناتج vector والمدخل vector. لو y = Wx + b، فإن شكل W هو (out_features, in_features)، و x شكله (in_features, batch) أو (batch, in_features) حسب convention. لا تحفظ الصيغة قبل أن تكتب shapes؛ معظم أخطاء backpropagation هي transpose أو broadcasting غير مقصود.

قاعدة عملية: اكتب dimensions بجانب كل expression، ثم استخدم finite differences للتحقق من gradient صغير. Gradient checking لا يستخدم في training production لأنه مكلف، لكنه ممتاز لاكتشاف خطأ في custom loss أو custom layer. استخدم tolerance نسبيًا ومطلقًا لأن floating point لا يعطي equality تامة.

PythonDerivatives for vectorized models
import numpy as np

W = np.array([[2.0, -1.0], [0.5, 3.0]])
x = np.array([4.0, 2.0])
b = np.array([1.0, -2.0])
y = W @ x + b
print(y)  # [7. 6.]

# Finite-difference check for f(w) = sum((w*x)^2)
w = np.array([0.3, -0.7])
def f(v): return np.sum((v * x[:2]) ** 2)
eps = 1e-6
g_num = np.array([(f(w + np.eye(2)[i]*eps)-f(w - np.eye(2)[i]*eps))/(2*eps) for i in range(2)])
g_exact = 2 * w * (x[:2] ** 2)
print(np.allclose(g_num, g_exact, rtol=1e-5, atol=1e-7))  # True
19

Optimization Beyond Basic Gradient Descent

Momentum, adaptive methods and schedules
Deep dive

Gradient Descent يستخدم gradient الحالي فقط. Momentum يحتفظ بمتوسط متحرك للاتجاهات السابقة فيقلل التذبذب على valleys طويلة. RMSProp يطبع gradient بمقياس متحرك لمربعاته، و Adam يجمع momentum مع adaptive scaling. هذه optimizers ليست سحرًا: ما زالت تحتاج learning-rate مناسبًا، وقد تتصرف بشكل مختلف مع weight decay و batch size و gradient clipping.

Learning-rate schedule قد يكون ثابتًا، step decay، cosine، أو warmup ثم decay. Warmup يقلل عدم الاستقرار في بداية بعض تدريبات Transformers، بينما cosine decay يقلل الخطوة تدريجيًا. سجّل optimizer state عند checkpoint؛ استئناف weights وحدها ليس استئنافًا مطابقًا للتدريب لأن moments وال scheduler state مهمان.

PythonMomentum, adaptive methods and schedules
# Illustrative Adam-style update for one scalar parameter
w, m, v = 0.0, 0.0, 0.0
beta1, beta2, lr, eps = 0.9, 0.999, 0.05, 1e-8
for t in range(1, 101):
    g = 2 * (w - 3.0)  # gradient of (w-3)^2
    m = beta1*m + (1-beta1)*g
    v = beta2*v + (1-beta2)*(g*g)
    m_hat = m/(1-beta1**t)
    v_hat = v/(1-beta2**t)
    w -= lr*m_hat/(v_hat**0.5 + eps)
print(round(w, 3))  # approaches 3.0
20

Probability Calibration and Decision Thresholds

A score is not automatically a reliable probability
Deep dive

Classifier قد يخرج score أو probability estimate. Calibration تعني أن الحالات التي أعطاها النموذج 0.8 تكون positive تقريبًا في 80% من الحالات على population مماثل. Discrimination تقيس ترتيب الحالات (مثل ROC-AUC)، بينما calibration تقيس صدق الاحتمال. قد يكون النموذج جيدًا في ranking وسيئًا في calibration؛ لذلك لا تخلط AUC مع reliability.

Threshold ليس خاصية ثابتة للنموذج؛ هو قرار تشغيلي يعتمد على تكلفة false positive و false negative وسعة فريق المراجعة. لو تكلفة FN أعلى، قد تخفض threshold لكن ستزيد FP غالبًا. اختر threshold على validation data وفق cost matrix ثم ثبّته قبل test النهائي، وراقب تغيّر prevalence في production.

PythonA score is not automatically a reliable probability
import numpy as np

# Expected cost for candidate thresholds using already-computed probabilities
p = np.array([.05, .20, .35, .65, .80, .95])
y = np.array([0, 0, 1, 0, 1, 1])
for threshold in [.3, .5, .7]:
    pred = (p >= threshold).astype(int)
    fp = np.sum((pred == 1) & (y == 0))
    fn = np.sum((pred == 0) & (y == 1))
    cost = 2*fp + 8*fn  # business cost assumptions, not universal
    print(threshold, fp, fn, cost)
21

Linear Algebra for Embedding Geometry: Limits and Diagnostics

Why nearest-neighbor scores can mislead
Deep dive

Embedding space هندسة متعلمة وليست فضاءً دلاليًا مثاليًا. High-dimensional vectors قد تتجمع مسافاتها نسبيًا (distance concentration)، وقد تتكرر اتجاهات شائعة (anisotropy) تجعل cosine scores مرتفعة حتى بين نصوص غير متقاربة. لهذا لا يكفي النظر إلى top scores؛ افحص positive/negative pairs، score distributions، nearest-neighbor examples، و Recall@k على queries ممثلة.

Normalization يزيل أثر magnitude لكنه لا يصلح embedding model ضعيفًا. Whitening أو centering قد يغير ranking ولا ينبغي تطبيقه إلا بتجربة controlled. لا تخلط embedding spaces، ولا تستخدم PCA كتحسين تلقائي؛ PCA تحافظ على variance وليس بالضرورة semantic relevance.

PythonWhy nearest-neighbor scores can mislead
import numpy as np

E = np.array([[1., 0.], [.9, .1], [0., 1.], [-1., 0.]])
E = E / np.linalg.norm(E, axis=1, keepdims=True)
q = np.array([1., 0.]); q /= np.linalg.norm(q)
scores = E @ q
print(np.argsort(scores)[::-1])  # nearest candidates by cosine for unit vectors
print(np.round(scores, 3))
↗

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

References & further reading

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

التوثيق الرسمي — Official documentation

خريطة التغطية: 28 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapLinear Algebra: Vectors, Matrices§01
RoadmapStatistics & Probability§01
RoadmapMean, Median, Variance, Standard Deviation§01
RoadmapProbability Distributions§01
RoadmapDerivatives وGradient بشكل أساسي§01
Roadmapفكرة Gradient Descent§01
SuggestedDot product and matrix multiplication§03
SuggestedTranspose, inverse, identity matrix§03
SuggestedNorms and distance (L1, L2)§03
SuggestedCosine similarity (the math behind embeddings and vector search)§03
SuggestedTensors, shapes, and broadcasting§03
SuggestedEigenvalues and eigenvectors (concept)§07
SuggestedSVD and PCA (concept)§07
SuggestedConditional probability and Bayes' theorem§05
SuggestedIndependence and expected value§05
SuggestedNormal, Bernoulli, Binomial, Poisson, Uniform distributions§05
SuggestedLaw of large numbers and Central Limit Theorem§05
SuggestedCovariance and correlation (correlation is not causation)§05
SuggestedPercentiles and quantiles§05
SuggestedSampling and sampling bias§05
SuggestedHypothesis testing, p-value, confidence interval (awareness)§05
SuggestedMaximum likelihood (concept)§06
SuggestedEntropy and cross-entropy (why it is a loss function)§06
SuggestedKL divergence (awareness)§06
SuggestedPartial derivatives and the chain rule (the engine of backpropagation)§06
SuggestedLearning rate, local minima, convex vs non-convex loss§06
SuggestedSoftmax and numerical stability (log-sum-exp)§06
SuggestedPractice with NumPy and Matplotlib§06

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

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