Software Engineer Encyclopedia
0%
Domain 10 · Python, Machine Learning & Data Engineering · Topic 10.3 · Part 2/2

أساسيات Machine Learning — الجزء الثاني

Machine Learning Fundamentals — Part 2

Ensembles, clustering, serialization, serving, experiment tracking, drift and .NET inference choices.

  • Intermediate
  • ~21 min read
  • 24 sections
  • 15 code examples
  • 1 diagrams
  • 11 questions
  • Priority L2 · Important
  • Python · scikit-learn · MLflow · ONNX · .NET

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

  • تبني مشروع تصنيف كامل: split → baseline → Pipeline → CV → test مرة واحدة.
  • تكتشف وتمنع أنواع الـ data leakage الخمسة.
  • تختار الـ threshold من تكلفة الأخطاء وتقيس الـ calibration.

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

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

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

PRACTICALتفهم إزاي الموديل يتعلم من البيانات. ده التفصيل العملي بعد ما تخلص الـ Math اللي قبله، وبعده تدخل الـ Deep Learning.

01

Ensembles و Boosting و Unsupervised Learning

Beyond the first baseline
Practical

Bagging يدرب نماذج بالتوازي على عينات مختلفة ثم يجمعها؛ Random Forest مثال. Boosting يبني سلسلة من learners يركز كل منها على الأخطاء المتبقية؛ Gradient Boosting قد يقدم أداء قويًا على tabular datasets. لا تختَر XGBoost أو LightGBM قبل baseline، ولا تخلط القوة مع سهولة التشغيل أو التفسير.

k-means يجمع النقاط حول centroids ويتأثر بال scale و k و outliers. PCA يقلل الأبعاد مع الحفاظ على أكبر variance، وليس بالضرورة أهم المعلومات التنبؤية. Anomaly detection و recommendation systems و time series مجالات لها assumptions خاصة؛ ابدأ بفهم المشكلة ثم baseline مناسب.

PythonBeyond the first baseline
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

clusterer = make_pipeline(StandardScaler(),
                          KMeans(n_clusters=4, n_init="auto", random_state=42))
labels = clusterer.fit_predict(X_numeric)
print(labels[:10])
02

Bias-variance في رسمة

Underfitting vs overfitting
Basics
sweet spottrain errorvalidation errorunderfit (high bias)overfit (high variance)
Training error keeps falling with complexity; validation error has a sweet spot
03

Model Serialization و Serving

Move a trained artifact into a service
Practical

النموذج في notebook ليس منتجًا. احفظ artifact مع preprocessing، schema، feature order، model version، training data reference، library versions، و evaluation metrics. joblib مناسب في بعض سيناريوهات Python لكنه pickle-based؛ لا تحمل artifacts غير موثوقة لأن deserialization قد تنفذ code. ONNX يتيح تبادل inference لبعض النماذج، و ML.NET خيار عندما تريد inference داخل ‎.NET، و Python API خيار عندما تحتاج ecosystem أو runtime خاصًا.

Serving contract يجب أن يحدد input schema، output schema، latency target، timeout، model version، behavior عند missing/unknown features، و backward compatibility. ضع warm-up و readiness checks، وحدد CPU/GPU resources.

PythonMove a trained artifact into a service
import joblib
from pathlib import Path

artifact = {
    "pipeline": search.best_estimator_,
    "model_version": "churn-2026-01",
    "feature_schema": feature_schema,
    "metrics": validation_metrics,
}
Path("artifacts").mkdir(exist_ok=True)
joblib.dump(artifact, "artifacts/churn-model.joblib")
# Load only artifacts produced by your trusted build pipeline.
04

Experiment Tracking و Reproducibility

Make experiments explainable
Practical

كل تجربة يجب أن تسجل dataset version، code commit، parameters، metrics، artifacts، environment، وسبب التجربة. MLflow Tracking يساعد على مقارنة runs، و Model Registry يضيف lifecycle stages/aliases/approvals حسب الإعداد. ثبّت random seeds حيثما أمكن، لكن لا تفترض reproducibility مطلقة مع GPU أو distributed training.

Model versioning لا يساوي file naming فقط؛ اربط artifact ببيانات التدريب و feature definitions والـ evaluation. لا تروج model لمجرد أنه أعلى accuracy؛ راجع latency، fairness، calibration، failure slices، وتكلفة التشغيل.

PythonMake experiments explainable
import mlflow
from sklearn.metrics import f1_score

with mlflow.start_run():
    mlflow.log_param("model", "random_forest")
    mlflow.log_param("seed", 42)
    mlflow.log_metric("validation_f1", validation_f1)
    mlflow.log_artifact("artifacts/churn-model.joblib")
    mlflow.set_tag("git_commit", git_commit)
05

Monitoring و Drift و Fairness

A model can decay after deployment
Deep dive

راقب data drift: تغير توزيع input features. Concept drift: تغير العلاقة بين features وال target. Performance drift: تراجع metric عند توفر labels. Drift alert لا يعني تلقائيًا أن model سيئ، وعدم وجود drift لا يثبت جودة القرار. اربط مراقبة features بنتائج حقيقية وتأخر وصول labels.

قسّم النتائج حسب cohorts مهمة، وراقب false positives/negatives والتغطية والـ abstention. افحص fairness والتمثيل والخصوصية، ولا تجمع بيانات حساسة لمجرد أنها متاحة. ضع rollback أو champion/challenger policy، واحتفظ بإمكانية إعادة إنتاج prediction بالـ model version وال features المسموح بتخزينها.

TextA model can decay after deployment
# Pseudocode for production monitoring
metrics = {
    "prediction_rate": predictions_per_minute,
    "input_missing_rate": missing_feature_ratio,
    "feature_drift": drift_score,
    "p95_inference_ms": inference_latency_p95,
    "model_version": deployed_model_version,
}
# Alert on sustained thresholds; investigate slices before retraining.
هل feature drift وحده دليل كافٍ لإعادة التدريب؟
لا. هو signal للتحقيق. اربطه بتغير الأداء، label delay، business outcomes، وجودة البيانات قبل قرار retraining.
06

اختيار طريقة دمج ML مع ‎.NET

Python API vs ONNX vs ML.NET
Deep dive

اختر Python microservice عندما تعتمد على مكتبات Python أو model runtime لا يتوفر بسهولة في ‎.NET، وتقبل تكلفة network hop والتشغيل المنفصل. اختر ONNX عندما النموذج مدعوم والتحويل صحيح وتحتاج inference داخل process أو خدمة ‎.NET. اختر ML.NET عندما workflow والنماذج المدعومة مناسبة وتريد ‎.NET-native training/inference. لا توجد إجابة واحدة لكل model.

قارن: conversion fidelity، latency، throughput، memory، CPU/GPU، deployment complexity، licensing، security patching، monitoring، و developer ownership. اختبر prediction parity على golden inputs قبل migration.

07

مشروع تطبيقي: Churn Prediction Service

From dataset to observable .NET feature
Practical

ابنِ pipeline لتوقع churn: اكتب problem statement و label window، افحص data leakage، split زمنيًا إن لزم، أنشئ baseline، preprocess داخل Pipeline، قارن Logistic Regression و Random Forest و Gradient Boosting، واختر metric متوافقة مع تكلفة التدخل. احفظ model card و artifact.

بعدها انشر Python FastAPI inference أو ONNX داخل خدمة ‎.NET. ASP.NET Core يملك auth و tenant boundaries و business workflow؛ inference component لا يقرر وحده تنفيذ خصم أو إلغاء. سجّل model version و latency و prediction confidence، واستخدم human review للقرارات المؤثرة.

Definition of Doneتقدر تعيد التجربة من commit و dataset version، تشرح metric والـ threshold، تختبر API، وتعمل rollback لإصدار model سابق.
08

Model Artifact Contract و Parity Tests

Train-serving consistency
Deep dive

أكبر خطر عند serving هو اختلاف preprocessing بين notebook والإنتاج. احفظ Pipeline كاملة، لا classifier وحده. احتفظ feature names/order، dtypes، missing-value policy، model version، training timestamp، dataset hash، dependency versions، و evaluation report. عند تحميل artifact تحقق من schema والـ signature قبل استقبال traffic.

Parity test يشغل نفس golden inputs في training pipeline و production serving ويقارن outputs ضمن tolerance. عند تحويل إلى ONNX أو ML.NET، قارن outputs والـ class probabilities على آلاف الحالات، بما فيها boundaries و missing values. اختلاف بسيط قد يغيّر قرار threshold.

PythonTrain-serving consistency
# Golden parity test (illustrative)
python_scores = python_pipeline.predict_proba(golden_X)[:, 1]
onnx_scores = onnx_session.run(None, {"input": golden_array})[0][:, 1]
assert np.max(np.abs(python_scores - onnx_scores)) < 1e-4
هل نحفظ model weights فقط؟
لا. يجب حفظ preprocessing و schema و version و lineage ومقاييس التقييم وإصدارات dependencies.
09

Model Card و Release Checklist

Explain what the model can and cannot do
Practical

Model Card وثيقة تشغيلية: intended use، prohibited use، training data provenance، population coverage، metrics overall and by slices، known limitations، threshold، calibration، latency/resource profile، privacy risks، owner، و rollback. اكتبها بلغة يستطيع product/security/operations فهمها.

قبل release: schema validation، reproducibility، leakage review، baseline comparison، fairness/slice review، security scan، latency load test، artifact signature، staged rollout، monitoring، rollback. لا تنشر model فقط لأن metric واحدة تحسنت.

PythonExplain what the model can and cannot do
release = {
  "artifact": "churn-model-2026-01",
  "data_version": "dataset-v17",
  "git_commit": "abc123",
  "primary_metric": "recall_at_precision_0_80",
  "known_limitations": ["new customers have sparse history"],
  "rollback_target": "churn-model-2025-12"
}
10

Recommendation و Time Series: حدود الأساسيات

Specialized problem families
Basics

Recommendation systems قد تكون popularity baseline، content-based، collaborative filtering، أو hybrid. انتبه إلى cold start و feedback loops و position bias؛ offline ranking metrics لا تساوي business uplift. Time series تتطلب temporal splits، seasonality، trend، leakage عبر future windows، و baseline مثل naive/seasonal naive قبل النماذج المعقدة.

Anomaly detection يعتمد على تعريف anomaly وسياقها؛ rare does not always mean bad. Clustering لا ينتج ground-truth classes. PCA يحافظ على variance لا على task relevance بالضرورة. اعرض النتائج كاستكشاف أو decision support حتى يتم تقييمها على outcome حقيقي.

11

Serving Contract و Operational Failure Modes

Schema, concurrency and model warmup
Deep dive

Inference endpoint يجب أن يحدد max batch size، request size، timeout، concurrency، model warm-up، readiness، output schema، version، و overload behavior. إذا model artifact لم يُحمّل، readiness false. إذا queue ممتلئة، أرجع 429/503 أو enqueue job بدل memory exhaustion.

راقب cold start، p95/p99 latency، memory، CPU/GPU، model exceptions، input schema failures، prediction distribution، و delayed labels. ضع fallback إلى baseline أو manual review عندما يتعذر inference، ولا تُرجع قيمة افتراضية توحي بأنها prediction حقيقية.

12

مشروع كامل: من بيانات خام لموديل تقدر تدافع عنه

An end-to-end scikit-learn classification project, executed
Practical

الفرق بين «شغّلت موديل» و«بنيت موديل» هو الانضباط: تقسيم البيانات قبل أي حاجة، baseline تقارن بيه، preprocessing جوه Pipeline، مقياس مناسب للمشكلة، و test set بيتلمس مرة واحدة في الآخر. المشروع ده بيمشي على الخطوات دي كلها على بيانات synthetic بتحاكي churn (العملاء اللي هيسيبوا الخدمة).

Pythonchurn_project.py — split → baseline → pipeline → cross-validation → held-out testExecuted ✓
import numpy as np, pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, classification_report, roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

# ---- 1) data: synthetic, with missing values and an imbalanced target (~1 in 5 churn) ----
rng = np.random.default_rng(42)
n = 4000
df = pd.DataFrame({
    "tenure_months":   rng.integers(1, 72, n),
    "monthly_charge":  rng.normal(60, 20, n).round(2),
    "support_tickets": rng.poisson(1.5, n),
    "plan":            rng.choice(["basic", "plus", "pro"], n, p=[0.5, 0.3, 0.2]),
    "payment":         rng.choice(["card", "wallet", "cash"], n),
})
logit = (-2.6 - 0.035 * df.tenure_months + 0.018 * df.monthly_charge + 0.55 * df.support_tickets
         + np.where(df.plan == "basic", 0.6, 0.0) + rng.normal(0, 0.6, n))
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df.loc[rng.random(n) < 0.08, "monthly_charge"] = np.nan          # 8% missing
print(f"rows={len(df)}  churn rate={df.churned.mean():.3f}  missing monthly_charge={df.monthly_charge.isna().mean():.3f}")

# ---- 2) split FIRST. The test set is locked away until the very end. ----
X, y = df.drop(columns="churned"), df.churned
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)

# ---- 3) preprocessing lives INSIDE the pipeline, so it is re-fit on each CV training fold only ----
numeric, categorical = ["tenure_months", "monthly_charge", "support_tickets"], ["plan", "payment"]
prep = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
models = {
    "baseline (prior)":    DummyClassifier(strategy="prior"),
    "logistic regression": Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000, class_weight="balanced"))]),
    "gradient boosting":   Pipeline([("prep", prep), ("clf", HistGradientBoostingClassifier(max_depth=3, learning_rate=0.08, random_state=0))]),
}

# ---- 4) compare with cross-validation on the TRAINING data only ----
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
print("\n5-fold CV on train (PR-AUC = average precision; baseline equals the churn rate):")
for name, model in models.items():
    s = cross_val_score(model, X_train, y_train, cv=cv, scoring="average_precision")
    print(f"  {name:<20} {s.mean():.3f} ± {s.std():.3f}")

# ---- 5) pick ONE model, fit on all training data, touch the test set ONCE ----
final = models["logistic regression"].fit(X_train, y_train)
proba = final.predict_proba(X_test)[:, 1]
print(f"\nheld-out test:  PR-AUC={average_precision_score(y_test, proba):.3f}  ROC-AUC={roc_auc_score(y_test, proba):.3f}")
print(classification_report(y_test, (proba >= 0.5).astype(int), digits=3, target_names=["stay", "churn"]))

# ---- 6) what did the model learn? (standardised coefficients are comparable) ----
names = final.named_steps["prep"].get_feature_names_out()
coefs = pd.Series(final.named_steps["clf"].coef_[0], index=names).sort_values(key=abs, ascending=False)
print("largest coefficients:")
print(coefs.head(4).round(3).to_string())
ConsoleOutput — captured from a real run
rows=4000  churn rate=0.211  missing monthly_charge=0.082

5-fold CV on train (PR-AUC = average precision; baseline equals the churn rate):
  baseline (prior)     0.212 ± 0.001
  logistic regression  0.475 ± 0.046
  gradient boosting    0.449 ± 0.035

held-out test:  PR-AUC=0.469  ROC-AUC=0.765
              precision    recall  f1-score   support

        stay      0.896     0.683     0.775       631
       churn      0.373     0.704     0.488       169

    accuracy                          0.688       800
   macro avg      0.635     0.694     0.631       800
weighted avg      0.786     0.688     0.714       800

largest coefficients:
num__support_tickets    0.661
num__tenure_months     -0.623
cat__plan_basic         0.270
num__monthly_charge     0.266

ليه PR-AUC مش accuracy؟ حوالي خُمس العملاء بس بيسيبوا. موديل بيقول «محدش هيسيب» دايمًا هياخد accuracy حوالي 79% وهو عديم الفايدة تمامًا. الـ PR-AUC بتاع الـ baseline بيساوي نسبة الـ positive class — فأي رقم فوقه معناه إن الموديل اتعلم حاجة.

ليه الـ gradient boosting ما كسبش؟ البيانات اتولدت من علاقة خطية في الـ log-odds، فالـ logistic regression هو الموديل «الصح» ليها. الدرس: موديل أعقد مش دايمًا أحسن، والـ baseline البسيط لازم يتجرّب الأول. على بيانات حقيقية فيها تفاعلات غير خطية النتيجة غالبًا بتتعكس.

اقرأ الـ classification report: recall الـ churn عالي والـ precision واطي — نتيجة class_weight="balanced" مع threshold 0.5. هل ده كويس؟ يعتمد على التكلفة: القسم الجاي.

الـ coefficients: إشاراتها بتطابق الطريقة اللي ولّدنا بيها البيانات (tickets أكتر = churn أكتر، tenure أطول = أقل). ده sanity check مهم: لو موديلك اتعلم علاقة عكس المنطق، غالبًا فيه leakage أو bug.

13

Data Leakage: الغلطة اللي بتدّيك أرقام حلوة وموديل فاشل

Two leakage experiments with measured damage
Pitfalls

الـ leakage معناه إن معلومة مش هتبقى متاحة وقت التوقع الحقيقي اتسربت للتدريب. النتيجة: أرقام تقييم ممتازة، وأداء سيئ في الإنتاج. أخطر حاجة فيه إنه مش بيطلّع error.

Pythonleakage.py — (1) feature selection before the split, (2) a feature recorded after the outcomeExecuted ✓
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)

# ---- Experiment 1: pure noise. 100 rows, 5000 random features, random labels. True accuracy = 0.50 ----
X = rng.normal(size=(100, 5000))
y = rng.integers(0, 2, 100)

X_leaky = SelectKBest(f_classif, k=20).fit_transform(X, y)          # WRONG: selection saw ALL labels
wrong = cross_val_score(LogisticRegression(max_iter=1000), X_leaky, y, cv=5).mean()

honest = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
right = cross_val_score(honest, X, y, cv=5).mean()                   # selection re-done inside each fold

print("Experiment 1 — the data is pure noise, so the honest answer is ~0.50")
print(f"  select features on all data, then cross-validate : accuracy = {wrong:.2f}   <- leakage")
print(f"  selection inside the pipeline                    : accuracy = {right:.2f}")

# ---- Experiment 2: target leakage. 'refund_issued' is only known AFTER the customer has churned ----
n = 2000
tickets = rng.poisson(2, n)
churned = (rng.random(n) < 1 / (1 + np.exp(-(tickets - 3)))).astype(int)
refund_issued = churned * (rng.random(n) < 0.9)                       # consequence of the label, not a cause

with_leak    = cross_val_score(LogisticRegression(), np.c_[tickets, refund_issued], churned, cv=5).mean()
without_leak = cross_val_score(LogisticRegression(), tickets.reshape(-1, 1), churned, cv=5).mean()
print("\nExperiment 2 — a feature that is a consequence of the label")
print(f"  with refund_issued    : accuracy = {with_leak:.2f}   <- looks great, useless at prediction time")
print(f"  without refund_issued : accuracy = {without_leak:.2f}   <- the real, deployable number")
ConsoleOutput — captured from a real run
Experiment 1 — the data is pure noise, so the honest answer is ~0.50
  select features on all data, then cross-validate : accuracy = 0.85   <- leakage
  selection inside the pipeline                    : accuracy = 0.48

Experiment 2 — a feature that is a consequence of the label
  with refund_issued    : accuracy = 0.97   <- looks great, useless at prediction time
  without refund_issued : accuracy = 0.76   <- the real, deployable number

التجربة الأولى: البيانات ضوضاء بحتة، ومع ذلك الطريقة الغلط طلّعت دقة عالية. السبب: من 5000 feature عشوائية، لازم بالصدفة كام واحدة يبقوا مرتبطين بالـ labels في العيّنة دي. لما اختارناهم باستخدام كل البيانات، الـ validation folds ساهمت في الاختيار، فالتقييم بقى على بيانات «اتشافت».

التجربة التانية: refund_issued بيتسجل بعد ما العميل يسيب. وقت التوقع الحقيقي (قبل ما يسيب) قيمته دايمًا صفر. اسأل عن كل feature: «القيمة دي هتبقى موجودة عندي لحظة ما أحتاج التوقع؟».

نوع الـ leakageمثالالوقاية
Preprocessing قبل الـ splitscaler/imputer/feature selection اتعمله fit على كل البياناتكل حاجة جوه Pipeline
Target leakagefeature نتيجة للـ labelراجع توقيت كل feature مع صاحب الـ domain
Temporal leakagerandom split لبيانات زمنية: بتتدرّب على المستقبلTimeSeriesSplit أو split بالتاريخ
Group leakageنفس العميل في train و testGroupKFold على id العميل
Test-set tuningجرّبت 50 إعداد واخترت الأحسن على الـ testvalidation set منفصل؛ الـ test مرة واحدة
14

اختيار الـ Threshold بالتكلفة، والـ Calibration

Turn probabilities into decisions using business costs
Practical

الموديل بيطلّع احتمال. القرار (نتصل بالعميل ولا لأ) محتاج threshold. الـ 0.5 مش رقم مقدس — الصح بيتحدد بتكلفة كل نوع غلط.

Pythonthreshold.py — pick the threshold that minimises expected cost; check calibrationExecuted ✓
import numpy as np
from sklearn.calibration import calibration_curve
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, confusion_matrix
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(1)
n = 6000
X = rng.normal(size=(n, 3))
p_true = 1 / (1 + np.exp(-(-2.2 + 1.4 * X[:, 0] - 0.9 * X[:, 1])))
y = (rng.random(n) < p_true).astype(int)
X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.4, stratify=y, random_state=0)

COST_FN = 200     # a churner we did not contact: lost customer value
COST_FP = 15      # a retention call/discount spent on someone who would have stayed

def report(model, label):
    proba = model.fit(X_tr, y_tr).predict_proba(X_val)[:, 1]
    thresholds = np.linspace(0.02, 0.9, 89)
    costs = []
    for t in thresholds:
        tn, fp, fn, tp = confusion_matrix(y_val, proba >= t).ravel()
        costs.append(fn * COST_FN + fp * COST_FP)
    best = thresholds[int(np.argmin(costs))]
    tn, fp, fn, tp = confusion_matrix(y_val, proba >= 0.5).ravel()
    frac_pos, mean_pred = calibration_curve(y_val, proba, n_bins=5, strategy="quantile")
    print(f"{label}")
    print(f"  cost at threshold 0.50 : {fn * COST_FN + fp * COST_FP:>7,}   (missed churners={fn}, wasted calls={fp})")
    print(f"  best threshold {best:.2f}    : {min(costs):>7,}")
    print(f"  Brier score            : {brier_score_loss(y_val, proba):.4f}  (lower = better calibrated)")
    print("  predicted vs observed  : " + "  ".join(f"{m:.2f}->{f:.2f}" for m, f in zip(mean_pred, frac_pos)))

report(LogisticRegression(), "plain logistic regression")
report(LogisticRegression(class_weight="balanced"), "\nclass_weight='balanced'")
print(f"\ntheory: with these costs, act when p > FP/(FP+FN) = {COST_FP / (COST_FP + COST_FN):.3f}")
ConsoleOutput — captured from a real run
plain logistic regression
  cost at threshold 0.50 :  59,925   (missed churners=294, wasted calls=75)
  best threshold 0.05    :  20,590
  Brier score            : 0.1081  (lower = better calibrated)
  predicted vs observed  : 0.01->0.01  0.04->0.05  0.10->0.09  0.22->0.24  0.53->0.53

class_weight='balanced'
  cost at threshold 0.50 :  27,390   (missed churners=102, wasted calls=466)
  best threshold 0.30    :  20,255
  Brier score            : 0.1585  (lower = better calibrated)
  predicted vs observed  : 0.05->0.01  0.17->0.05  0.32->0.09  0.54->0.24  0.81->0.53

theory: with these costs, act when p > FP/(FP+FN) = 0.070

الـ threshold الأمثل بعيد عن 0.5 لأن تفويت عميل هيسيب أغلى بكتير من مكالمة ضايعة. نظريًا: اتصرف لما p > FP/(FP+FN) — بشرط إن الاحتمالات calibrated.

الـ calibration: سطر predicted vs observed بيقارن متوسط الاحتمال المتوقع بالنسبة الفعلية في كل شريحة. في الموديل العادي الرقمين قريبين: لما يقول 0.30، فعلًا حوالي 30% بيسيبوا. مع class_weight="balanced" الاحتمالات منفوخة (بيقول رقم أعلى من الواقع) والـ Brier score أسوأ — الترتيب لسه كويس، لكن الأرقام نفسها ما ينفعش تتفسر كاحتمالات ولا تتحط في معادلة التكلفة النظرية.

القاعدة: لو هتستخدم الاحتمال نفسه (تسعير، ترتيب أولويات بالقيمة المتوقعة)، قِس الـ calibration وصلّحها بـ CalibratedClassifierCV لو لازم. لو محتاج ترتيب بس، اختار الـ threshold من منحنى التكلفة على validation set.

15

تمارين وتقييم

Exercises and assessment
Practical
  • Beginner: في churn_project.py غيّر الـ scoring لـ accuracy. ليه الـ baseline بقى شكله كويس؟
  • Intermediate: ضيف RandomForestClassifier للمقارنة، واعمل GridSearchCV على C بتاع الـ logistic regression — جوه الـ training data بس.
  • Intermediate: في threshold.py خلّي COST_FP = 150. الـ threshold الأمثل اتحرك لفين؟ ليه؟
  • Advanced: ولّد بيانات فيها تفاعل غير خطي (مثلاً churn عالي بس لما tenure < 6 و tickets > 3 مع بعض) وشوف هل الـ gradient boosting بقى يكسب.
  • Engineering challenge: اكتب pytest بيفشل لو أي خطوة preprocessing اتعملها fit برا الـ pipeline (hint: قارن الـ CV score بـ noise labels — لازم يبقى قريب من الـ chance).

موديل كشف احتيال دقته 99.2% على بيانات فيها 0.8% احتيال. إيه أول استنتاج؟

تكلفة الـ false negative عندك 10 أضعاف الـ false positive. تحرّك الـ threshold إزاي بالنسبة لـ 0.5؟

16

Explainability: Permutation Importance و Shapley Values من الصفر

Global and per-prediction explanations, with exact Shapley values verified by their additivity property — executed
Deep dive

«الموديل رفض الطلب ده ليه؟» سؤال هتتسأله من عميل، من مدير، ومن جهة رقابية. فيه نوعين من الإجابة: global (الموديل بيعتمد على إيه عمومًا؟) وlocal (التوقع ده بالذات طلع كده ليه؟). SHAP — أشهر أداة — مبنية على Shapley values من نظرية الألعاب. هنا بنحسبها بالتعريف الأصلي (كل التباديل الممكنة) على موديل صغير، عشان تفهم الرقم اللي المكتبة بتطلّعه.

Pythonexplain.py — permutation importance (global) and exact Shapley values (local)Executed ✓
import itertools, math
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(0)
n = 4000
names = ["income", "debt_ratio", "late_payments", "account_age", "shoe_size"]
X = np.c_[rng.normal(50, 15, n), rng.uniform(0, 1, n), rng.poisson(1.0, n), rng.uniform(0, 20, n), rng.normal(42, 3, n)]
logit = -1.0 - 0.04 * (X[:, 0] - 50) + 3.0 * (X[:, 1] - 0.5) + 0.9 * X[:, 2] - 0.05 * X[:, 3]      # shoe_size has NO effect
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = GradientBoostingClassifier(random_state=0).fit(X_tr, y_tr)

# ---------- global: how much does the score drop when one feature is shuffled? ----------
pi = permutation_importance(model, X_te, y_te, scoring="roc_auc", n_repeats=20, random_state=0)
print("permutation importance on the TEST set (drop in ROC-AUC when the feature is shuffled):")
for i in np.argsort(-pi.importances_mean):
    print(f"   {names[i]:<14} {pi.importances_mean[i]:+.4f} ± {pi.importances_std[i]:.4f}")
print("impurity-based importance from the trees (computed on TRAINING data):")
print("   " + "  ".join(f"{names[i]}={model.feature_importances_[i]:.3f}" for i in np.argsort(-model.feature_importances_)))

# ---------- local: exact Shapley values for ONE prediction ----------
background = X_tr[rng.choice(len(X_tr), 200, replace=False)]

def value(x, subset):
    """Expected model output when only the features in `subset` are known to be x's values."""
    Z = background.copy()
    Z[:, list(subset)] = x[list(subset)]
    return model.predict_proba(Z)[:, 1].mean()

def shapley(x):
    m, phi = len(x), np.zeros(len(x))
    for i in range(m):
        others = [j for j in range(m) if j != i]
        for size in range(m):
            for S in itertools.combinations(others, size):
                weight = math.factorial(size) * math.factorial(m - size - 1) / math.factorial(m)
                phi[i] += weight * (value(x, S + (i,)) - value(x, S))     # marginal contribution of feature i
    return phi

x = X_te[np.argmax(model.predict_proba(X_te)[:, 1])]                    # the applicant the model is most worried about
phi, base, pred = shapley(x), value(x, ()), model.predict_proba(x.reshape(1, -1))[0, 1]
print(f"\none applicant: predicted default risk = {pred:.3f}; average prediction (baseline) = {base:.3f}")
for i in np.argsort(-np.abs(phi)):
    print(f"   {names[i]:<14} value={x[i]:7.2f}   contribution {phi[i]:+.3f}")
print(f"additivity check: baseline + sum(contributions) = {base + phi.sum():.3f}  (equals the prediction: {np.isclose(base + phi.sum(), pred)})")
ConsoleOutput — captured from a real run
permutation importance on the TEST set (drop in ROC-AUC when the feature is shuffled):
   debt_ratio     +0.1245 ± 0.0098
   late_payments  +0.1183 ± 0.0096
   income         +0.0391 ± 0.0095
   account_age    +0.0154 ± 0.0033
   shoe_size      +0.0060 ± 0.0021
impurity-based importance from the trees (computed on TRAINING data):
   debt_ratio=0.372  late_payments=0.274  income=0.207  account_age=0.096  shoe_size=0.051

one applicant: predicted default risk = 0.973; average prediction (baseline) = 0.383
   income         value=   2.04   contribution +0.280
   late_payments  value=   3.00   contribution +0.185
   debt_ratio     value=   0.94   contribution +0.125
   account_age    value=   6.04   contribution +0.001
   shoe_size      value=  42.40   contribution -0.001
additivity check: baseline + sum(contributions) = 0.973  (equals the prediction: True)

Permutation importance: بنلخبط عمود واحد في الـ test set ونشوف الأداء نزل قد إيه. shoe_size — اللي ملوش أي علاقة بالـ target — طلع الأصغر بفارق كبير (0.006 مقابل 0.12 لأهم feature). قارنه بالـ impurity-based importance اللي جاية من الأشجار: دي محسوبة على بيانات التدريب، وادّت الـ feature العشوائية 5% من الأهمية لأن الأشجار بتلاقي فيها splits بالصدفة. القاعدة: الأهمية بتتقاس على بيانات ما اتشافتش.

Shapley value لـ feature: متوسط «الفرق اللي بتعمله لما تتضاف» على كل الترتيبات الممكنة لإضافة الـ features. الخاصية اللي بتميّزها: الجمع — الـ baseline + مجموع المساهمات = التوقع بالظبط (والكود اتأكد منها). عشان كده تقدر تقول «الخطر طلع من 0.38 (المتوسط) لـ 0.97: +0.28 بسبب الدخل المنخفض جدًا، +0.19 بسبب 3 متأخرات، +0.13 بسبب نسبة الدين».

التكلفة: الحساب الدقيق بيمشي على 2M مجموعة — ممكن لـ 5 features ومستحيل لـ 50. مكتبة SHAP بتستخدم خوارزميات خاصة (TreeSHAP للأشجار) أو تقريب بالعيّنات. وLIME بيجاوب نفس السؤال بطريقة تانية: بيدرّب موديل خطي بسيط حوالين النقطة دي بس.

حدود لازم تتقال: الشرح بيوصف الموديل مش العالم — مساهمة عالية مش معناها سببية. ومع features مرتبطة ببعض، تثبيت واحدة وتغيير التانية بيخلق حالات مش واقعية والمساهمات بتتوزع بشكل مضلل. والـ baseline اللي بتختاره بيغيّر الأرقام.

17

Fairness: نفس الموديل، أرقام مختلفة لكل مجموعة

Group metrics on a model that never saw the protected attribute — executed
Pitfalls
Pythonfairness.py — selection rate, TPR and FPR per group; the proxy problemExecuted ✓
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(3)
n = 20_000
group = rng.integers(0, 2, n)                                   # protected attribute: NOT given to the model
skill = rng.normal(0, 1, n)                                     # what actually determines success, same in both groups
district = (rng.random(n) < np.where(group == 1, 0.8, 0.2)).astype(float)    # a proxy: strongly tied to the group
# historical labels are biased: group 1 was approved less often at the same skill
y = (skill + rng.normal(0, 0.5, n) - 0.8 * group > 0).astype(int)

X = np.c_[skill + rng.normal(0, 0.7, n), district]              # the model sees a noisy skill signal and the district
X_tr, X_te, y_tr, y_te, g_tr, g_te, s_tr, s_te = train_test_split(X, y, group, skill, random_state=0)
pred = LogisticRegression().fit(X_tr, y_tr).predict(X_te)
qualified = (s_te > 0).astype(int)                              # ground truth we only have because this is a simulation

print(f"{'group':<8}{'selection rate':>15}{'TPR (qualified approved)':>26}{'FPR (unqualified approved)':>28}")
for g in (0, 1):
    m = g_te == g
    sel = pred[m].mean()
    tpr = pred[m & (qualified == 1)].mean()
    fpr = pred[m & (qualified == 0)].mean()
    print(f"{g:<8}{sel:>15.3f}{tpr:>26.3f}{fpr:>28.3f}")
r0, r1 = pred[g_te == 0].mean(), pred[g_te == 1].mean()
print(f"\ndisparate impact ratio (selection rate of group 1 / group 0) = {r1 / r0:.2f}   (a common screening rule flags values below 0.80)")
print("the model never received `group` — it reconstructed it from `district`")
ConsoleOutput — captured from a real run
group    selection rate  TPR (qualified approved)  FPR (unqualified approved)
0                 0.385                     0.661                       0.104
1                 0.256                     0.478                       0.037

disparate impact ratio (selection rate of group 1 / group 0) = 0.67   (a common screening rule flags values below 0.80)
the model never received `group` — it reconstructed it from `district`

الموديل ما شافش الـ protected attribute، ومع ذلك مجموعة 1 بتتقبل بنسبة أقل بكتير، وحتى المؤهلين فيها (نفس الـ skill) بيتقبلوا أقل. السبب حاجتين: الـ labels التاريخية نفسها متحيزة، والـ district بيشتغل كـ proxy بيخلّي الموديل يعيد بناء المجموعة. «شيلنا عمود الجنس/الدين» مش حل.

مفيش تعريف واحد للعدالة: تساوي نسب القبول (demographic parity)، تساوي الـ TPR (equal opportunity)، وتساوي الـ TPR والـ FPR مع بعض (equalized odds) تعريفات مختلفة ومش بتتحقق كلها في نفس الوقت عمومًا. اختيار التعريف قرار policy وقانوني مش تقني — دورك إنك تقيس وتعرض الأرقام لكل مجموعة، مش إنك تقرر لوحدك.

عمليًا: احسب مقاييسك لكل شريحة حساسة كجزء ثابت من تقرير التقييم، وراجع مصدر الـ labels قبل الموديل. في المحاكاة عندنا «الحقيقة» (qualified)؛ في الواقع مش موجودة، وده اللي بيخلي المشكلة صعبة.

شيلتوا عمود «الجنسية» من الـ features عشان الموديل يبقى عادل. ليه ده مش كفاية؟

18

اختبر فهمك

Knowledge Check
Practical
لماذا نحفظ preprocessing مع model؟
لضمان تطابق transformations بين التدريب و inference ومنع train-serving skew.
هل data drift يعني ضرورة retraining فورًا؟
لا. هو signal للتحقيق؛ افحص source pipeline و labels و performance/business impact أولًا.

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

لماذا قد يكون Random Forest أكثر استقرارًا من شجرة واحدة؟
لأنه يجمع أشجارًا متعددة مدربة على bootstrap samples و feature subsets، ما يقلل variance والتأثر بشجرة منفردة.
لماذا لا يكفي Silhouette Score لإثبات فائدة clustering؟
هو metric داخلي هندسي ولا يثبت أن المجموعات مستقرة أو مفيدة تجاريًا أو مرتبطة بنتيجة حقيقية.
لماذا يجب حفظ preprocessing مع model artifact؟
لأن inference يجب أن يستخدم نفس feature transformations والترتيب والـ schema المستخدمة أثناء التدريب.
19

Tree Ensembles and Boosting Mechanics

Bagging, random forests and gradient boosting
Deep dive

Decision tree يقسم feature space عبر rules متتابعة لتقليل impurity مثل Gini أو entropy في classification أو variance في regression. الأشجار سهلة التفسير نسبيًا لكنها high variance لو عميقة. Bagging يدرب نماذج على bootstrap samples ويجمعها لتقليل variance؛ Random Forest يضيف random feature subsets لتقليل correlation بين الأشجار.

Gradient Boosting يبني learners بالتتابع لتقليل residuals أو negative gradients من loss. XGBoost/LightGBM/CatBoost تضيف regularization و sampling و efficient split finding بطرق مختلفة. راقب depth، learning_rate، number_of_estimators، min_child_samples، و early stopping. لا تختارها من وصفة عامة؛ استخدم CV مناسبًا ووقت inference.

PythonBagging, random forests and gradient boosting
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier

# Fit on a prepared numeric matrix; these are illustrative baselines.
rf = RandomForestClassifier(n_estimators=300, min_samples_leaf=3, random_state=42, n_jobs=-1)
gb = HistGradientBoostingClassifier(max_iter=200, learning_rate=0.08, max_leaf_nodes=15, random_state=42)
# rf.fit(X_train, y_train); gb.fit(X_train, y_train)
# Compare validation quality, calibration, latency and memory—not score alone.
20

Imbalanced Learning and Cost-Sensitive Decisions

Rare positives require more than accuracy
Deep dive

عندما positive class نادرة، accuracy قد تكون مضللة: نموذج يتنبأ دائمًا negative قد يحقق 99% accuracy مع prevalence=1% لكنه لا يكتشف أي positive. راقب precision/recall، PR-AUC، confusion matrix، و precision@k حسب workflow. ROC-AUC قد يبدو جيدًا مع class imbalance بينما precision التشغيلية ضعيفة.

Class weights تغير training objective، resampling يغير training distribution، و threshold tuning يغير قرار التصنيف. لا تعمل oversampling قبل split أو cross-validation لأن نسخًا متشابهة قد تتسرب إلى folds. Probability calibration بعد resampling قد تحتاج إعادة معايرة على population ممثل.

PythonRare positives require more than accuracy
from sklearn.metrics import classification_report, average_precision_score
import numpy as np

# y_true and probability scores come from a held-out validation set.
y_true = np.array([0,0,0,1,0,1,0,0,1,0])
score = np.array([.05,.10,.20,.70,.15,.60,.30,.08,.85,.25])
pred = (score >= .5).astype(int)
print(classification_report(y_true, pred, zero_division=0))
print('PR-AUC/AP:', round(average_precision_score(y_true, score), 3))
21

Unsupervised Learning: Clustering Without Ground Truth

Interpret structure, do not invent labels
Deep dive

K-Means يقلل within-cluster squared distance ويفترض clusters تقريبًا compact/spherical في scaled feature space. يتأثر بالـ initialization و k والـ outliers والـ scaling. DBSCAN يلتقط density-based clusters لكنه حساس لـ eps و min_samples ويتعامل مع varying densities بصعوبة. Hierarchical clustering يعرض بنية متعددة المستويات لكنه قد يكون مكلفًا.

Silhouette score مؤشر داخلي وليس دليلًا أن clusters ذات معنى تجاري. قيّم stability عبر seeds/subsamples، افحص cluster profiles، وقارنها بقرارات المستخدم أو outcomes لاحقة. PCA visualization إسقاط ثنائي الأبعاد وقد يخفي أو يخلق انطباعًا بصريًا؛ لا تعتبر الرسم proof.

PythonInterpret structure, do not invent labels
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
import numpy as np

X = np.array([[20, 2000], [22, 2200], [55, 9000], [58, 9500]], dtype=float)
X_scaled = StandardScaler().fit_transform(X)
labels = KMeans(n_clusters=2, n_init=20, random_state=42).fit_predict(X_scaled)
print(labels)  # cluster IDs are arbitrary; inspect original-space profiles
22

Model Artifact, Reproducible Inference and Rollback

Training output must be deployable safely
Deep dive

Model artifact يجب أن يضم model weights/serialized estimator، preprocessing، input schema، feature names/order، label mapping، dependency versions، training data reference، metrics، threshold، و code revision. pickle/joblib قد ينفذ code عند loading؛ لا تحمل artifact غير موثوق. استخدم signed/controlled registry و checksum.

Inference contract يحدد validation، missing fields، unknown categories، batch limits، timeout، output schema، model version، و fallback. اختبر artifact في clean environment منفصل عن notebook. Canary أو shadow deployment يكشف اختلاف runtime؛ rollback يحتاج artifact سابقًا و schema متوافقًا، لا مجرد إعادة نشر كود قديم.

PythonTraining output must be deployable safely
from dataclasses import dataclass

@dataclass(frozen=True)
class Prediction:
    label: str
    score: float
    model_version: str

def validate_score(score: float) -> None:
    if not 0.0 <= score <= 1.0:
        raise ValueError('score must be in [0, 1]')

# A production adapter should validate inputs, load a versioned artifact,
# attach provenance, enforce timeouts and emit structured telemetry.
23

Exporting to ONNX and Serving from ‎.NET

A portable inference artifact with an explicit feature contract
Practical

ONNX صيغة تمثيل portable للـ ML models والعمليات المرتبطة بها. الفكرة أن التدريب قد يتم في Python، ثم يُحمّل artifact في خدمة ‎.NET باستخدام Microsoft.ML.OnnxRuntime. هذا لا يجعل أي estimator قابلًا للتصدير تلقائيًا: تحقق من دعم العمليات والـ opset، واحتفظ بالـ preprocessing المتوافق، واختبر parity بين نتائج Python و ‎.NET.

مهم قبل الإنتاج

المثال التالي يوضح inference contract فقط. يجب أن يتطابق ترتيب features وأنواعها وعمليات scaling/encoding مع التدريب. لا تعتبر أسماء الأعمدة وحدها ضمانًا للتوافق.

C#Minimal ONNX Runtime inference shape
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;

using var session = new InferenceSession("model.onnx");
var input = new DenseTensor<float>(new[] { 1, 3 });
input[0, 0] = 0.25f; // feature 1, transformed exactly as during training
input[0, 1] = 1.00f; // feature 2
input[0, 2] = 0.75f; // feature 3

var inputs = new[] { NamedOnnxValue.CreateFromTensor("features", input) };
using var outputs = session.Run(inputs);
var scores = outputs.First().AsEnumerable<float>().ToArray();
Console.WriteLine(string.Join(", ", scores));

اسم input (features) وشكل output ليسا ثابتين لكل model؛ افحص model metadata عند البناء، واكتب integration test يحمّل نفس artifact الذي سيُنشر. في ASP.NET Core لا تنشئ Session لكل request: session مكلف نسبيًا ويمكن إعادة استخدامه، مع التحقق من thread-safety وفق إصدار runtime والمزود المستخدم. حدد timeout وقيود حجم batch، وسجّل model version لا بيانات شخصية حساسة.

للتصدير من Python، استخدم المسار الرسمي المدعوم من المكتبة التي دربت النموذج (مثل skl2onnx لبعض scikit-learn estimators)، ثم اختبر المدخلات الحدّية و missing values ونتائج probabilities. قد تحتاج إلى تحويل preprocessing pipeline أو دعم عمليات إضافية.

References: ONNX Runtime documentation · ONNX Runtime C#‎ guide · ONNX specification.

24

Kaggle Mini-Projects: From Notebook to Reproducible Experiment

A disciplined project workflow, not leaderboard chasing
Practical

ابدأ بمشروع صغير له target واضح و dataset موثوق. قبل التدريب، اقرأ data card و license وشرح الأعمدة، وحدد وحدة الصف (customer, transaction, image) والهدف ووقت حدوثه. اعمل baseline بسيطًا، ثم قارن نموذجًا واحدًا أكثر تعقيدًا باستخدام نفس split ونفس metric.

  1. Problem framing: هل المطلوب classification أم regression؟ ما تكلفة false positive و false negative؟
  2. Leakage audit: احذف أي feature لا تكون متاحة وقت التنبؤ، وتجنب target-derived columns.
  3. Split: استخدم stratified split للتصنيف عند الحاجة، و time-based split للبيانات الزمنية؛ لا تلمس test set أثناء tuning.
  4. Baseline: DummyClassifier ثم LogisticRegression أو شجرة صغيرة.
  5. Pipeline: ضع imputation و scaling و encoding داخل scikit-learn Pipeline حتى تُfit على training folds فقط.
  6. Evaluation: اعرض confusion matrix و precision/recall و ROC-AUC أو PR-AUC حسب imbalance، مع threshold rationale.
  7. Reproducibility: ثبّت random_state والاعتماديات، واحفظ dataset version و features والـ metrics و commit hash.
PythonLeakage-safe baseline pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42
)

preprocess = ColumnTransformer([
    ("numeric", Pipeline([("impute", SimpleImputer(strategy="median")),
                          ("scale", StandardScaler())]), numeric_columns),
    ("categorical", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                              ("encode", OneHotEncoder(handle_unknown="ignore"))]), categorical_columns),
])
model = Pipeline([("preprocess", preprocess),
                  ("classifier", LogisticRegression(max_iter=1000))])
model.fit(X_train, y_train)
print("test score:", model.score(X_test, y_test))

اختَر مشروعًا مثل Telco Churn أو Bike Sharing أو House Prices، لكن لا تتعامل مع نتيجة notebook كمنتج. اكتب README يشرح السؤال والـ split والـ metric والقيود، وأضف inference script واختبارًا على سجل واحد. راجع شروط استخدام البيانات قبل نشرها أو إعادة توزيعها.

References: Kaggle Datasets documentation · scikit-learn common pitfalls · Pipelines and composite estimators.

↗

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

References & further reading

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

خريطة التغطية: 48 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapDataset, Features, Labels§07
RoadmapTraining, Validation, Testing§07
RoadmapSupervised vs. Unsupervised Learning§07
RoadmapRegression & Classification§07
RoadmapLinear Regression, Logistic Regression§07
RoadmapDecision Trees, Random Forest§07
RoadmapPython for Data Science§07
RoadmapNumPy§07
RoadmapPandas§07
RoadmapData Cleaning§07
RoadmapData Visualization§07
RoadmapEvaluation Metrics§07
RoadmapOverfitting and Underfitting§07
RoadmapFeature Engineering§07
Roadmapscikit-learn§07
RoadmapModel Serialization§03
RoadmapModel Serving§03
Roadmap.NET Integration§03
RoadmapModel Versioning Basics§03
RoadmapModel Monitoring Basics§05
SuggestedBaseline models first§07
SuggestedBias-variance trade-off§07
SuggestedOverfitting, underfitting, regularization (L1, L2)§07
SuggestedCross-validation§07
SuggestedHyperparameter tuning (grid, random search)§07
SuggestedMetrics: accuracy, precision, recall, F1, ROC-AUC, RMSE, MAE, R²§07
SuggestedConfusion matrix and choosing the right metric§07
SuggestedClass imbalance (class weights, resampling)§07
SuggestedData leakage (the classic silent bug)§07
SuggestedMissing values, scaling, encoding categorical data§07
Suggestedk-Nearest Neighbors, Naive Bayes, SVM (awareness)§01
SuggestedEnsembles: bagging vs boosting§01
SuggestedGradient boosting: XGBoost, LightGBM§01
SuggestedClustering: k-Means§01
SuggestedDimensionality reduction: PCA§01
SuggestedAnomaly detection (awareness)§01
SuggestedRecommendation systems basics (connects to Project 4)§01
SuggestedTime series (awareness)§01
SuggestedPandas and scikit-learn pipelines§07
SuggestedExperiment tracking (MLflow concept)§04
SuggestedDeploying a model: ONNX, ML.NET, or a Python API§03
SuggestedModel drift and monitoring§04
SuggestedFairness and bias in data§04
SuggestedGradient descent and loss intuition§22
SuggestedConfusion matrix, precision, recall, F1, ROC-AUC§22
SuggestedML.NET basics§22
SuggestedONNX export and ONNX Runtime in .NET§23
SuggestedKaggle mini-projects§24

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

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