Cross-validation কেন দরকার
এই পাঠে যা শিখবেন
- একক validation-এর সমস্যা — কেন CV দরকার
- K-Fold cross-validation — algorithm ও কোড
- Stratified, group, time-series CV — variants
- Leave-One-Out CV — extreme case
- Bias-Variance-এর CV-এর নিজস্ব tradeoff
১ · একক validation কেন যথেষ্ট নয়
L03-এ আমরা ডেটা ৭০/১৫/১৫-এ ভাগ করলাম। কিন্তু — যদি আপনার "lucky" বা "unlucky" split হয়? Validation set-এর মাত্র ১৫% ডেটা, ছোট ডেটায় হয়তো ১০০ sample। এই ১০০-তে accuracy ৮৫%, ভিন্ন split-এ হয়তো ৭৮%।
সমস্যা: Validation accuracy-র variance বেশি। Hyperparameter tune করছেন এই unstable signal-এ — সঠিক সিদ্ধান্ত কঠিন।
একবার নয় — অনেকবার split করুন। ভিন্ন ভিন্ন validation set-এ accuracy মাপুন। গড় ও standard deviation reportable। এটাই cross-validationCross-Validationএকই ডেটা ভিন্ন ভিন্ন সমন্বয়ে train ও validation-এ ভাগ — ছোট ডেটায় robust performance estimate। K-fold সবচেয়ে জনপ্রিয়।।
২ · K-Fold Cross-Validation
সবচেয়ে জনপ্রিয় form — Stone (১৯৭৪):
- ডেটা $K$ সমান টুকরায় (folds) ভাগ।
- $K$ বার iterate:
- Iteration $i$: fold $i$ = validation, বাকি $K-1$ folds = training।
- মডেল train, validation accuracy record।
- $K$ accuracies-এর গড় ± standard deviation।
প্রতিটি sample exactly একবার validation-এ পড়ে, $K-1$ বার train-এ। উদাহরণ — K=৫, n=১০০০:
- Fold ১: train=৮০০, val=২০০
- Fold ২: train=৮০০ (ভিন্ন), val=২০০ (ভিন্ন)
- ... ৫ বার।
৩ · K কত হবে?
- K=৫: Standard, fast। সাধারণত যথেষ্ট।
- K=১০: বেশি robust estimate। যদি ডেটা ছোট।
- K=n (LOOCV): Leave-One-Out — প্রতিবার ১ sample test।
Tradeoff: বড় K → কম bias (training set প্রায়-পূর্ণ ডেটা), বেশি variance (folds correlated), বেশি compute।
৪ · scikit-learn-এ K-Fold
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
import numpy as np
X, y = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=200)
# 5-fold CV
scores = cross_val_score(model, X, y, cv=5, scoring='accuracy')
print(f"Scores: {scores}")
print(f"Mean: {scores.mean():.4f} ± {scores.std():.4f}")
print(f"95% CI: [{scores.mean() - 2*scores.std():.4f}, "
f"{scores.mean() + 2*scores.std():.4f}]")
৫ · Stratified K-Fold — imbalanced data-এ
Default cross_val_score classification-এ stratified K-Fold ব্যবহার করে। প্রতিটি fold-এ class proportion বজায়। Manual control দরকার হলে:
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = []
for train_idx, val_idx in skf.split(X, y):
X_tr, X_v = X[train_idx], X[val_idx]
y_tr, y_v = y[train_idx], y[val_idx]
model.fit(X_tr, y_tr)
scores.append(model.score(X_v, y_v))
print(f"Scores: {[f'{s:.3f}' for s in scores]}")
print(f"Mean: {np.mean(scores):.4f}")
৬ · Leave-One-Out (LOOCV)
$K = n$ — প্রতি iteration-এ ১ sample মাত্র validation। Pros:
- Training-এ প্রায়-সম্পূর্ণ ডেটা ($n-1$) — bias সর্বনিম্ন।
- Deterministic — কোনো random split নেই।
Cons:
- $n$ বার training — প্রচণ্ড expensive।
- Folds অত্যন্ত correlated — variance বেশি।
- সাধারণত ১০-fold ভাল estimate (Kohavi 1995)।
৭ · Time Series CV
Random K-fold — temporal data-এ time leakage। বিকল্প — TimeSeriesSplit:
- Iter ১: train [0:200], val [200:300]।
- Iter ২: train [0:300], val [300:400]।
- Iter ৩: train [0:400], val [400:500]।
- ... সবসময় past-এ train, future-এ val।
এটি production deployment-এর সঠিক simulation।
৮ · CV-এর পাঁচ ব্যবহার
- Performance estimation: এই মডেল production-এ কেমন হবে।
- Hyperparameter tuning: GridSearchCV — প্রতিটি hyperparameter combination CV-তে evaluate।
- Model selection: Logistic vs Tree vs SVM — কোনটা?
- Feature selection: কোন features keep করব।
- Confidence interval: mean ± 2·std — uncertainty quantification।
৯ · CV-এর সীমাবদ্ধতা
- Computationally expensive: K গুণ training। Deep learning-এ অসম্ভব হতে পারে।
- Small data noise: খুব ছোট ডেটায় (<১০০) CV-ও noisy।
- Nested CV needed: Hyperparameter tuning ও performance estimation একসাথে — outer + inner CV।
- Test set still needed: CV training data-এর ভেতরে। Final evaluation-এ untouched test set আলাদা।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ Hyperparameter tuning-এ "nested cross-validation" দরকার কেন? Single CV কেন overfitting করে?
Nested CV ML methodology-এর সবচেয়ে সূক্ষ্ম concept-এর একটি। অনেক experienced practitioner-ও সঠিকভাবে ব্যবহার করেন না।
সমস্যা — single CV-এর "selection bias":
- আপনি GridSearchCV চালালেন — ১০০ hyperparameter combination, প্রতিটি 5-fold CV।
- Best CV score ০.৯২ পেলেন (e.g., depth=৭)।
- Report করলেন — "মডেল accuracy ৯২%"।
- সমস্যা: ১০০টি random combinations-এর মধ্যে ০.৯২ — হয়তো একটি lucky combination!
- Production-এ — ০.৮৭ পাবেন।
গাণিতিক explanation:
- $\max$ of $n$ random variables-এর expectation > কোনো একটির expectation।
- "Best of 100 candidates" — biased upward।
- আপনার "best CV score" — performance-এর over-optimistic estimate।
Nested CV সমাধান:
- Outer loop (e.g., 5-fold): Performance estimation।
- Inner loop (e.g., 3-fold): Hyperparameter selection।
- প্রতিটি outer fold-এ — inner CV দিয়ে best HP choose, তারপর outer val set-এ evaluate।
- HP-selection inner-এ; performance outer-এ — সম্পূর্ণ আলাদা ডেটা।
Cost:
- Outer 5 × inner 3 × HP combinations 100 = ১৫০০ training।
- Heavy — কিন্তু trustworthy।
একটি subtlety:
- Nested CV — performance estimate দেয় না, একটি specific মডেল।
- Final deployable model — সব data-এ retrain (after best HP found)।
- Estimate বলে — "এই pipeline production-এ কেমন হবে।"
Practical compromise:
- Big data — nested CV অপ্রয়োজনীয়। Simple train/val/test।
- Medium data — single CV + separate test set।
- Small data — nested CV essential।
- Kaggle — nested CV সাধারণত skip, but performance overestimate।
Cawley & Talbot (2010): "On Over-fitting in Model Selection" — এই paper field-এ awareness এনেছিল। তবে এখনো বহু paper biased estimate publish।
মূল উপলব্ধি: "একই data দিয়ে hyperparameter select এবং performance estimate" — methodologically inconsistent। যথাযথ separation দরকার।
প্র ০২ "K=১০ default ব্যবহার করি" — কখন এটি ভুল? K=৫ বা K=৩-এর ভাল কারণ?
K-এর choice ML folklore-এর অংশ। "K=১০ best" — Kohavi (১৯৯৫)-এর famous paper থেকে। কিন্তু context-dependent।
K বড় হলে কী হয়:
- Bias কম: Each training set প্রায়-সম্পূর্ণ ডেটা।
- Variance বেশি: K folds অত্যন্ত correlated (overlapping training data)। Estimate-এর variance বাড়ে।
- Compute বেশি: $K$ গুণ time।
K ছোট হলে:
- Bias বেশি: Training set ছোট — pessimistic performance estimate।
- Variance কম: Folds কম correlated।
- Compute কম।
K=৫ বা K=১০ কখন ভাল:
- n < ১০০০ — K=১০ ভাল (more training data per fold)।
- n ১০০০-১০K — K=৫ যথেষ্ট।
- n > ১০০K — K=৩ পর্যাপ্ত (variance reduction is the goal, ছোট K-তেও যথেষ্ট data)।
K=৩ কেন কখনো:
- Deep learning — training expensive। K=৩ practical limit।
- Hyperparameter sweeps — quick screening।
- Big data — variance already low।
K=২ — কেন এড়াবেন:
- 50% data train-এ — high bias estimate।
- সমান যেন একটি single train/test split ২ বার flipped।
- আসলে কম useful।
K=n (LOOCV) — কেন এড়াবেন:
- Computationally insane (১০K training)।
- High variance — folds nearly identical।
- Linear regression-এ closed-form LOOCV — exception।
Repeated K-Fold:
- K=৫ × ১০ repeats — ৫০ training।
- Different random seeds।
- K=১০-এর চেয়ে ভাল estimate often।
- scikit-learn-এ
RepeatedKFold।
Specific edge cases:
- Imbalanced extreme: ১০০ positive / ১০০K negative — K=৫ stratified-এ each fold ২০ positive। K=১০-এ ১০। Possibility — K=৩, ৩৩-৩৪ positive।
- Time series: Standard K-fold incorrect — TimeSeriesSplit, K=৩ থেকে ৭।
- Group structure: Group K-fold। Groups-এর সংখ্যা K-এর upper bound।
আমার practical advice:
- Default — K=৫।
- Small data বা important publish — K=১০ + repeated।
- Production budget tight — K=৩।
- Always report mean ± std।
মূল উপলব্ধি: K choice — bias-variance-compute triangle। "Best K" দিয়ে depend করে context, default-এর ভাল কারণ একটিও perfect না।
প্র ০৩ আপনি একটি Kaggle competition-এ অংশ নিচ্ছেন। CV score ০.৯২, public leaderboard ০.৮৭। কী হতে পারে — এবং কীভাবে decide করবেন কোন submission final দেবেন?
Kaggle এই situation দিয়ে full — CV-LB gap চেনাই top players-এর প্রধান skill।
সম্ভাব্য কারণ — gap কেন:
(১) CV-LB different distribution:
- Training data থেকে test data ভিন্ন distribution।
- Time-based competition — recent data shift।
- Geographic — train US, test Europe।
(২) Public LB sample bias:
- Public LB মাত্র ৩০% of test।
- Variance বেশি — random fluctuation।
- Private LB-এ score ভিন্ন হবে।
(৩) Probing leakage:
- Some competitor public LB-এ overfit করতে পারে — multiple submissions দিয়ে।
- Private-এ collapse।
(৪) CV setup imperfect:
- Random K-fold — যখন time-series-এ TimeSeriesSplit লাগত।
- Group structure missing।
- Stratification missing imbalance-এ।
Final submission strategy:
(১) Diagnostic first:
- Adversarial validation — train ও test combine, classifier দিয়ে predict "from-train"। Accuracy ৫০% — same distribution। ৯০%+ — distribution shift।
- If shift detected — focus features distribution-invariant।
(২) Trust CV more than LB:
- CV proper সেট করলে — তাকে বিশ্বাস করুন।
- "Trust your CV" — top Kagglers-এর ক্লাসিক motto।
- Bowl-shape — best CV submission private-এ best হয়।
(৩) Allowed selections (usually 2):
- Submission ১: Best CV — even though LB lower।
- Submission ২: Best balance — high CV + high LB।
- "Best LB" select করবেন না (overfitting trap)।
(৪) Ensemble:
- Different models-এর average — variance কম।
- Diverse models — CV-LB gap reduce।
(৫) Stable cv-validation:
- Multiple seeds, repeated K-fold।
- Standard deviation across seeds — stability check।
Real story — "shake-up":
- Public LB top — private LB ১০০-এর নিচে — "shake-up"।
- Cause — public LB overfitting।
- Survivor strategy — CV-trust।
Production parallel:
- Real-world: training data-এর performance-কে production-এর exact predictor কখনো না।
- Robust evaluation — multiple validation sets, A/B test, monitoring।
মূল উপলব্ধি: "Best on validation" production-এ best হবে — এই assumption আংশিক সত্য। Robust process LB-chasing-এর চেয়ে important।
প্র ০৪ "Cross-validation expensive — Deep Learning-এ কেন possible না?" এই দাবিতে কী সত্য, কী ভুল? Modern alternatives কী?
Deep learning-এ CV myth এবং reality — দু'টোই আছে। Nuance বুঝা ML practitioner-এর gradient।
Myth: "DL-এ CV impossible"
- সত্য — bigger DL models, bigger datasets — full K-fold computationally prohibitive।
- BUT — small/medium DL models, moderate data — CV সম্পূর্ণ feasible।
Reality: কখন CV Deep Learning-এ practical:
- Tabular DL (TabNet, NODE) — ছোট model, CV easy।
- Small image dataset (medical, scientific) — K=৫ standard practice।
- NLP transfer learning — pre-trained model frozen, only top layers tuned।
Reality: কখন impractical:
- ImageNet scale — single training takes days। 5x = weeks।
- LLMs — millions of dollars per training run। CV impossible।
- Real-time training — production constraints।
DL-এর alternatives:
(১) Hold-out validation:
- Single train/val/test split।
- Large dataset → single split-এ enough statistics।
- Variance acceptable।
(২) Multiple seed runs:
- Same train/val split, কিন্তু ৩-৫টি random initialization।
- Variance estimate পাওয়া যায়।
- "5 random seeds" — DL paper-এর standard।
(৩) Bayesian optimization:
- HP search-এর জন্য — full grid search-এর চেয়ে কম training।
- Optuna, Hyperopt libraries।
(৪) Bootstrap evaluation:
- Test set-এ bootstrap sampling — confidence interval।
- No retraining needed।
- Cheap উপায় uncertainty quantification।
(৫) Theoretical bounds:
- PAC-Bayes, NTK theory — direct generalization bounds।
- Practical use limited।
(৬) Held-out validation curves:
- Training during epochs — validation loss track।
- Convergence pattern → generalization indication।
- Early stopping — implicit regularization।
(৭) Ensemble:
- Multiple models — uncertainty estimate।
- "Deep ensembles" (Lakshminarayanan et al., 2017)।
(৮) Test-time augmentation:
- Test sample-এ multiple augmentations, predictions average।
- Variance reduction inference time-এ।
Foundation models era:
- Pre-trained model + small fine-tuning — CV আবার practical।
- Few-shot learning evaluation — explicit CV-like multi-seed protocols।
আমার recommendation:
- Tabular ML — always CV।
- Small DL — K=3 minimum।
- Big DL — multiple seeds + held-out test।
- LLMs — careful eval suite, multiple benchmarks।
মূল উপলব্ধি: "CV expensive" — gradient, না binary। DL paper-এ "single seed, no CI" সাধারণ — কিন্তু bad practice।
অনুশীলন
-
হিসাব: ১০০০ sample, K=৫। প্রতি fold-এ training ও validation কতগুলো sample?
Validation: ২০০ (১/K)। Training: ৮০০ (K-১/K = ৪/৫)।
-
scikit-learn: উপরের code চালান। K=৩, ৫, ১০ — কোনটায় mean কী, std কত? কোনটা trust করবেন?
K বাড়ালে mean stable, std সাধারণত ছোট হয় (Iris-এ noise কম)। K=৫ সাধারণত যথেষ্ট। বড় std মানে বেশি uncertainty — small data signal।
-
চিন্তা: তিনটি scenario — কোন CV variant?
- (ক) ১০ বছরের stock price ডেটা
- (খ) ৫০০ patient × ১০ X-ray each
- (গ) ১M tweets সাথে sentiment label, ০.৫% positive
- (ক) TimeSeriesSplit — temporal leakage এড়ানো।
- (খ) GroupKFold — patient group।
- (গ) StratifiedKFold — class balance preserve।
আরও পড়ুন
- পাঠ ০৬ · মূল্যায়ন মেট্রিক পরবর্তী পাঠ CV-তে কী score করব — accuracy, F1, ROC ইত্যাদি।
- পাঠ ০৪ · Bias-Variance আগের পাঠ CV-এর underlying tradeoff।
- পাঠ ৪১ · Hyperparameter tuning পরবর্তী মডিউল CV ভিত্তিক GridSearchCV, BayesianSearchCV।
- সব AI Courses ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps।