
ليه الـ 0.5 مش جزء من الموديل؟ إزاي تظبط الـ Decision Threshold
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
الفكرة الغلط الشائعة
predict بيستخدمه، فلو عايز قرارات مختلفة يبقى لازم تدرّب موديل مختلف. وده سهل تفهم جه منين:
الـ predictبيرجّع labels على طول. الـ cutoff مش باين في أي حتة في الـ call، فبيبان كإنه جوه الموديل.الـ tutorials بتصلّح القرارات المايلة بإنها تغيّر الـ training: class weights، أو resampling، أو داتا أكتر. الـ 0.5 شكلها منطقية: قول "أيوه" لما "أيوه" تبقى أرجح من "لأ".
اللي بيحصل فعلًا
الـ 0.5 rule بيتطبّق بعد الموديل
predict_proba أو score أكبر من 0 من decision_function، والـ rules دي أكيد مش مثالية لأغلب الاستخدامات. والـ training عمره ما بيبص عليها. الـ LogisticRegression بيظبط الـ weights بإنه يقلّل الـ log loss على الاحتمالات، ومفيش في أي حتة من العملية دي. الموديل بعد الـ fit هو دالة الاحتمالات، والـ threshold سياسة إنت اللي بتحطها فوقه.
الـ cutoff الصح بييجي من التكاليف
from sklearn.datasets import make_classificationfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import confusion_matrixfrom sklearn.model_selection import train_test_splitX, y = make_classification(n_samples=10_000, n_features=10, n_informative=4, weights=[0.8], class_sep=0.7, random_state=2)X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)model = LogisticRegression().fit(X_tr, y_tr)tn, fp, fn, tp = confusion_matrix(y_te, model.predict(X_te)).ravel()print(f"cutoff 0.5: {fp} declined good, {fn} missed defaults")print(f"cost {fp + 5 * fn}") # a missed default costs 5x a wrong decline# cutoff 0.5: 48 declined good, 417 missed defaults# cost 2133from sklearn.datasets import make_classificationfrom sklearn.frozen import FrozenEstimatorfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import confusion_matrix, make_scorerfrom sklearn.model_selection import FixedThresholdClassifier, train_test_splitfrom sklearn.model_selection import TunedThresholdClassifierCVdef cost(y_true, y_pred): # a missed default costs 5x a wrong decline tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() return fp + 5 * fnX, y = make_classification(n_samples=10_000, n_features=10, n_informative=4, weights=[0.8], class_sep=0.7, random_state=2)X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)model = LogisticRegression().fit(X_tr, y_tr)frozen = FrozenEstimator(model) # fit() won't retrain itby_costs = FixedThresholdClassifier(frozen, threshold=1 / 6).fit(X_tr, y_tr)print(f"cutoff 1/6: cost {cost(y_te, by_costs.predict(X_te))}")scorer = make_scorer(cost, greater_is_better=False)tuned = TunedThresholdClassifierCV(LogisticRegression(), scoring=scorer)tuned.fit(X_tr, y_tr) # picks the cutoff by 5-fold cross-validationtuned_cost = cost(y_te, tuned.predict(X_te))print(f"cutoff {tuned.best_threshold_:.3f}: cost {tuned_cost}")# cutoff 1/6: cost 1390# cutoff 0.187: cost 1390FrozenEstimator بيوضّح الفكرة: لما تنادي fit على الـ wrapper، الـ weights المتدرّبة مابتتلمسش.
TunedThresholdClassifierCV فبيوصل لنفس النتيجة من غير المعادلة. بيجرّب cutoffs على cross-validation داخلي بـ 5 folds، ويقيّم كل واحد بتكلفة الـ business، ويقف عند 0.187، بنفس تكلفة الـ test، 1390. والـ scorer الافتراضي بتاعه هو الـ balanced accuracy، فادّيله الـ scorer بتاعك: الـ cutoff مش هيبقى أحسن من الـ metric اللي بيحسّنها.
لما المعادلة والداتا مايتفقوش
موديل واحد، كذا cutoff
predict؛ والـ training عمره ما شافه | |
تطبقها إزاي في مشروعك
سعّر الغلطتين اتفق مع الـ business على تكلفة الـ false positive والـ false negative، ولو بالتقريب. ابدأ من المعادلة مع احتمالات calibrated، تكلفة الـ false positive مقسومة على مجموع التكلفتين أول cutoff سليم. ظبطه على داتا validation استخدم TunedThresholdClassifierCVبـ scorer مبني من تكاليفك، أو منحنى محسوب على validation split.اعمل deploy للـ cutoff مع الموديل لف الموديل المتدرّب في FixedThresholdClassifier(FrozenEstimator(model), threshold=...)، واعمل version للاتنين.راجعه لما التكاليف تتغيّر أسعار أو طاقة أو سياسة جديدة معناها cutoff جديد. احسبه تاني على داتا حديثة؛ والموديل يفضل زي ما هو.
الخلاصة
الـ classifier بيتعلّم احتمالات؛ والـ 0.5 مجرد rule بيتطبّق عليها بعدين. تحريك الـ cutoff مش محتاج training من جديد: تكلفة نفس الموديل نزلت من 2133 لـ 1390. الـ cutoff الصح بييجي من التكاليف: تكلفة الـ false positive على مجموع التكلفتين، لو الاحتمالات calibrated. ظبطه على داتا validation، عمرك ما تظبطه على داتا الـ training، واعمله version مع الموديل.
📚 المصادر
Tuning the decision threshold for class prediction — scikit-learn User Guide Post-tuning the decision threshold for cost-sensitive learning — scikit-learn examples Classification: Thresholds and the confusion matrix — Google Machine Learning Crash Course Elkan, The Foundations of Cost-Sensitive Learning (IJCAI 2001) Probability calibration — scikit-learn User Guide
التعليقات (0)