scikit-learn-এর সাথে পরিচয়
এই পাঠে যা শিখবেন
- scikit-learn কী — এর scope ও সীমা
- সর্বজনীন
fit / predict / scoreAPI - প্রথম classifier — Iris-এ KNN ও LogisticRegression
- Train/test split — কেন overfitting মাপা যায়
- Preprocessing transformer —
StandardScaler - Pipeline — leak-proof workflow
- Cross-validation দিয়ে নির্ভরযোগ্য estimate
১ · scikit-learn কী?
scikit-learnscikit-learn২০০৭-এ David Cournapeau-র Google Summer of Code প্রকল্প হিসেবে শুরু। আজকে INRIA-চালিত open-source — সবচেয়ে ব্যবহৃত classical ML library। Tabular data, prototyping, baseline-এর de facto tool। = NumPy, SciPy, matplotlib-এর উপর তৈরি Python ML library। ৬০+ algorithm — linear regression, logistic regression, decision tree, random forest, SVM, k-means, PCA, KNN — সব। Deep learning এতে নেই, কিন্তু tabular data-র ৮০-৯০% production কাজে এটাই যথেষ্ট। কাগলের অর্ধেক winning solution-এ scikit-learn থাকে।
১) Estimator API: সব মডেলের একই interface — fit(X, y), predict(X)।
২) Transformer API: data preprocessing — fit(X), transform(X)।
৩) Pipeline: transformer + estimator — composable, leak-proof।
২ · সর্বজনীন API — fit/predict/score
scikit-learn-এর সবচেয়ে সুন্দর design — সব মডেল একই API মেনে চলে। LogisticRegression-এ যা শিখবেন — RandomForest, SVM-এ একই syntax। তাই algorithm switch করতে এক লাইন বদলালেই হয়।
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
# (১) ডেটা লোড
iris = load_iris()
X, y = iris.data, iris.target
print("X shape:", X.shape, "| y unique:", set(y))
# (২) মডেল object — শুধু hyperparameter set
model = LogisticRegression(max_iter=1000)
# (৩) fit — ডেটা থেকে শেখা
model.fit(X, y)
# (৪) predict — নতুন sample
new_flower = [[5.1, 3.5, 1.4, 0.2]] # দু'টি ব্র্যাকেট, কারণ shape (1, 4)
print("Predict:", iris.target_names[model.predict(new_flower)[0]])
# (৫) score — accuracy
print(f"Train accuracy: {model.score(X, y):.3f}")
৩ · Train/test split — overfitting মাপা
Model train data মুখস্থ করে ফেলতে পারে — সেটাই overfittingOverfittingমডেল train data-র ছোট-ছোট pattern (এমনকি noise) মুখস্থ করে — কিন্তু নতুন data-তে সাধারণীকরণ পারে না। সবচেয়ে সাধারণ ML-এর সমস্যা। সমাধান — held-out test set, regularization, cross-validation।। তাই প্রকৃত performance মাপতে — data-কে আগে ভাগ। Train-এ fit, test-এ score।
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
# stratify=y → প্রতিটি class proportional
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
print("Train:", X_tr.shape, "| Test:", X_te.shape)
model = LogisticRegression(max_iter=1000)
model.fit(X_tr, y_tr)
print(f"Train acc: {model.score(X_tr, y_tr):.3f}")
print(f"Test acc: {model.score(X_te, y_te):.3f}") # এটাই honest number
random_state=42 — reproducibility। একই split বার বার পেতে। stratify=y — class imbalance থাকলে অপরিহার্য।
৪ · KNN — সবচেয়ে সরল classifier
K-Nearest NeighborsKNNএকটি নতুন বিন্দুর label — তার nearest k প্রতিবেশীর majority vote। কোনো "training" নেই — শুধু সব data-point store, predict-এ search। সরল ও ব্যাখ্যাযোগ্য, কিন্তু feature scale-এ sensitive ও বড় data-তে slow। — "আমার আশেপাশে কারা?" এক বাক্যে algorithm। নতুন বিন্দুর nearest k point-এর majority class = predicted class।
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2,
stratify=y, random_state=42)
# k=5 — পাঁচ nearest neighbor-এর vote
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_tr, y_tr)
print(f"Test accuracy: {knn.score(X_te, y_te):.3f}")
print("Predict probabilities (first 3):")
print(knn.predict_proba(X_te[:3]).round(2))
LogisticRegression থেকে KNeighborsClassifier। বাকি কোড একদম same। এটাই sklearn-এর শক্তি।
৫ · Preprocessing — StandardScaler
KNN, SVM, Logistic Regression — distance-based বা gradient-based — সবাই feature scale-এ sensitive। যদি একটি feature ০-১, আরেকটি ১,০০০-১০,০০০ range — বড়টা dominate। সমাধান: standardizationStandardization (z-score scaling)প্রতিটি feature থেকে mean বিয়োগ, std দিয়ে ভাগ — ফলে mean=0, std=1। distance-based ও gradient-based algorithm-এ অপরিহার্য। Tree-based (Random Forest, XGBoost) এর প্রয়োজন নেই। — প্রতিটি feature mean=0, std=1।
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2,
stratify=y, random_state=42)
# (১) Scaler train data-তে fit (mean, std শেখে)
scaler = StandardScaler().fit(X_tr)
# (২) train ও test দু'টোকেই transform
X_tr_s = scaler.transform(X_tr)
X_te_s = scaler.transform(X_te)
print("Train mean ~", X_tr_s.mean(axis=0).round(2))
print("Train std ~", X_tr_s.std(axis=0).round(2))
knn = KNeighborsClassifier(n_neighbors=5).fit(X_tr_s, y_tr)
print(f"\nScaled test acc: {knn.score(X_te_s, y_te):.3f}")
fit না — শুধু transform। Train data-র mean/std দিয়েই test scale হবে। নাহলে — data leakageData LeakageTest data-র information train phase-এ ঢুকে গেলে — model artificially inflated score পায়। Production-এ unseen data-তে ব্যর্থ। ML-এর সবচেয়ে কপট bug — debug করা কঠিন।। Pipeline-এ এই ভুল automatically এড়ানো যায়।
৬ · Pipeline — অপরিহার্য abstraction
Preprocessing + model একসাথে — একটি object। fit করলে — সব stage একসাথে fit। predict করলে — automatically transform → predict। CV-এ leak-proof।
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2,
stratify=y, random_state=42)
# Pipeline — দু'টি step
pipe = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
pipe.fit(X_tr, y_tr)
print(f"Test accuracy: {pipe.score(X_te, y_te):.3f}")
# 5-fold cross-validation — leak-proof
cv = cross_val_score(pipe, X, y, cv=5, scoring="accuracy")
print(f"5-fold CV: {cv.mean():.3f} ± {cv.std():.3f}")
cross_val_score ৫টি fold-এ Pipeline-কে fit/score — প্রতিবার scaler আলাদা ভাবে train fold-এ fit। Manual scaling-এ এটা ভুল হত। Pipeline সব ঠিক রাখে।
৭ · কখন sklearn, কখন না
- Tabular data (rows × columns): sklearn-ই default। RandomForest, XGBoost, LightGBM-এর জন্য sklearn-compatible।
- ছোট-মাঝারি data (১M row পর্যন্ত): sklearn যথেষ্ট। তার বেশি — Spark ML বা cuML।
- Image / text / audio: deep learning দরকার — PyTorch, TensorFlow, Hugging Face।
- Sequential / time-series: sklearn-এ basic আছে, কিন্তু statsmodels, sktime, prophet বেশি ভাল।
- Online / streaming: sklearn-এর partial_fit সীমিত — river library দেখুন।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ "Always use deep learning" — এই myth কেন ভুল? Tabular data-তে XGBoost/RandomForest কেন এখনো DL-কে হারায়? Real benchmark কী বলছে?
২০১২-র ImageNet thunderclap-এর পর "deep learning সব problem-এ best" — এই myth ছড়াল। কিন্তু gradient boosted trees (XGBoost ২০১৪, LightGBM ২০১৬, CatBoost ২০১৭) এখনো tabular data-তে রাজা। Why?
প্রমাণ — Kaggle ও academic benchmark:
- Kaggle-এর tabular competition-এ ৭০-৮০% winning solution — XGBoost বা LightGBM।
- Shwartz-Ziv & Armon (২০২২) — "Tabular Data: Deep Learning is Not All You Need" — ১১টি dataset-এ XGBoost average-এ DL হারায়।
- Grinsztajn et al. (২০২২, NeurIPS) — ৪৫টি tabular benchmark-এ tree ensemble dominate।
কেন tree-based wins (tabular-এ):
- Heterogeneous feature: tabular-এ একটি column int (age), একটি float (price), একটি categorical (city)। Trees এ স্বাভাবিকভাবে handle। NN-এ embedding লাগে।
- Missing values: XGBoost native handle। NN-এ impute ও mask লাগে।
- Feature interaction: trees split-এ pairwise interaction শেখে। NN deep হলে শেখে — কিন্তু overkill।
- Robust to scale: tree scale-invariant। NN-এ careful scaling, BatchNorm।
- Small data efficiency: trees ১০,০০০ row-এ ভাল কাজ করে। NN-এ overfit।
- Inductive bias align: tabular-এ feature axis-aligned split-এ যথেষ্ট structure ধরা পড়ে।
Deep learning কখন wins (tabular-এও):
- বিশাল ডেটা (১০M+ row): NN scaling ভাল, GBDT memory-bound।
- Mixed modality: tabular + image + text → NN-এ unified embedding।
- Sequential structure: click stream, time-series — RNN/Transformer।
- Transfer learning: pretrained tabular foundation model (TabPFN, ২০২২) বাড়ছে।
আধুনিক tabular DL (২০২২+):
- FT-Transformer, TabNet — promising কিন্তু GBDT-কে consistently হারাতে পারছে না।
- TabPFN — small data-তে impressive, prior-data fitted network।
Production reality:
- LightGBM/XGBoost — train fast (CPU), inference fast (no GPU), interpretable (SHAP), small artifact। Production-এ DL-এর চেয়ে অনেক সহজ।
- Banking, e-commerce, ad-tech — tabular dominant; DL marginal।
সিদ্ধান্ত নিয়ম:
- Tabular data + ১M row-এর কম → GBDT (XGBoost/LightGBM/CatBoost) প্রথম।
- Image/text/audio → DL।
- Mixed structure → DL দিয়ে fusion।
- "What's interpretable?" — tree + SHAP এখনো best।
মূল উপলব্ধি: "Best algorithm" data-র structure-এর উপর নির্ভর। Tabular-এ — শতাব্দীর পুরোনো principle (gradient boosting Friedman ২০০১) আজও champion। Hype নয়, evidence-based বাছাই — সেটাই mature ML practice।
প্র ০২ scikit-learn-এর fit/predict/score API ২০০৭ থেকে কেন এত copy হচ্ছে? PyTorch Lightning, Keras, XGBoost — সবাই এই pattern follow। কী principle-এ এর সাফল্য?
২০১১-তে Pedregosa et al.-এর JMLR paper "Scikit-learn: Machine Learning in Python" — শুধু একটি library announcement না, একটি API design philosophy। ১৫ বছর পরেও এর ছাপ সর্বত্র।
API-এর ৬টি core principle:
- Consistency: সব estimator-এর একই interface। 60+ algorithm, একটাই pattern।
- Inspection: hyperparameter ও learned parameter — public attribute।
model.coef_,model.feature_importances_। - Non-proliferation: data structure NumPy ndarray + Pandas DataFrame — নতুন কাস্টম format নেই।
- Composition: Pipeline, FeatureUnion — block বানিয়ে compose।
- Sensible defaults:
LogisticRegression()— কোনো arg ছাড়া কাজ করে। - Documentation: প্রতিটি class-এ docstring, example, রেফারেন্স paper।
কেন এই pattern এত contagious:
- Cognitive load কম: এক library শিখলেই সব বোঝা। RandomForest থেকে SVM switch — শুধু class বদলান।
- Tooling-friendly: GridSearchCV, cross_val_score — fit/predict-এ defined। যে কোনো মডেলে কাজ করে।
- Educational value: teaching-এ অসাধারণ — ML concept (fit, predict, score) language-level।
- Production workflow: serialize, load, deploy — uniform।
যারা এই pattern adopt করেছে:
- XGBoost / LightGBM: sklearn-compatible wrapper — ML pipeline-এ drop-in।
- Keras (২০১৫):
model.fit(X, y),model.predict(X)— সরাসরি sklearn থেকে অনুপ্রাণিত। - PyTorch Lightning:
Trainer.fit(),Trainer.test()— boilerplate কমাতে scikit-style। - Hugging Face Transformers:
Trainer.train(),Trainer.evaluate()। - fastai:
learn.fit()— Jeremy Howard pedagogy। - Spark MLlib: Pipeline + Transformer + Estimator — সরাসরি sklearn থেকে।
- cuML (NVIDIA): sklearn-compatible GPU ML — drop-in replacement।
সফল API design-এর লক্ষণ:
- Code-এর "shape" pattern চিনে — মাত্র ৩-৪ method মনে রাখলেই কাজ চলে।
- "How do I X with library Y?" — google-যোগ্য।
- Substitution test pass — "X দিয়ে যা করি, Y দিয়ে একই syntax-এ।"
- Beginner-এর জন্য সরল, expert-এর জন্য configurable।
সমালোচনা:
- Stateful API —
fitobject mutate করে। Functional purity নেই। - NumPy-centric — modern stack-এ DataFrame/Tensor mix সমস্যা।
- Sparse matrix support uneven।
- Multi-output, multi-target — late-stage retrofit।
পাঠ — যেকোনো API design-এর জন্য:
- Few methods, applied broadly = power।
- Composability ছাড়া reusability নেই।
- Defaults matter বেশি, custom config matter কম।
- Documentation = library-র অর্ধেক।
মূল উপলব্ধি: sklearn-এর সাফল্য algorithm-এ না, API-এ। ১৫ বছর পরেও — fit/predict/score literally ML-এর "verb"। API design-এ এটা case study।
প্র ০৩ Data leakage — ML-এর সবচেয়ে কপট bug। train_test_split-এর আগে scaling, target encoding-এ leak, time-series-এ "future" feature — তিন subtle scenario। কেন Pipeline এই risk কমায়?
Andrew Ng বহুবার বলেছেন — "Data leakage is the #1 reason ML projects fail in production." ৯০% accuracy notebook-এ → ৬০% live-এ — কারণ leak। Subtle, common, expensive।
কী data leakage:
Test data বা future data-র information train phase-এ ঢুকে যাওয়া। Model artificially boost — কিন্তু production-এ এই information নেই → পতন।
(১) Preprocessing leak — সবচেয়ে common:
- ❌
scaler.fit(X)→train_test_split(X)— test-এর mean/std train phase-এ leak। - ❌
SimpleImputer().fit(X)পুরো dataset-এ — test-এর missing pattern train-কে inform করে। - ❌ Feature selection (e.g., SelectKBest) পুরো data-তে — target correlation দেখে select।
- ✅ Pipeline-এ scaler & imputer — শুধু train fold-এ fit, test-এ transform।
(২) Target encoding leak:
- ❌ Categorical column-কে target mean দিয়ে encode (e.g., "city → avg_purchase_per_city") — full data দিয়ে compute। Test row-এর target নিজেই avg-এ included।
- ✅ Out-of-fold target encoding বা
category_encoders.TargetEncoder-এর smoothing। - ✅ Pipeline-এ encoder → fold-aware।
(৩) Time-series leak — "future" feature:
- ❌ Random k-fold CV time-series-এ — March data দিয়ে train, January predict — impossible production-এ।
- ❌ "Mean of last 7 days" feature compute-এ আজকের data যোগ — leak।
- ✅
TimeSeriesSplit— temporal order maintain। - ✅ Lag features — strict cutoff (t-1, t-7) এর আগের।
- ✅ Walk-forward validation।
আরও subtle leak scenario:
-
ID-based leak: patient_id train+test দু'জায়গায় — same patient-এর different visit। Group-aware split (
GroupKFold)। - Duplicate row: exact বা near-duplicate train ও test-এ — model "মুখস্থ" করে। Dedup আগে।
- Future encoded in past: "user churned" target। Feature "subscription_canceled_date" — same কথা ভিন্নভাবে।
- Selection bias: sample selection process target-correlated। Sampling logic carefully।
- Image dataset leak: train ও test-এ same patient-এর different image — model patient চিনে।
Pipeline কীভাবে রক্ষা করে:
- প্রতিটি CV fold-এ — entire pipeline fresh fit। Scaler, imputer, encoder — শুধু train fold দেখে।
- Test fold-এ পুরো pipeline transform → predict। Leak structurally impossible।
- Hyperparameter search-এ
GridSearchCV(pipeline, param_grid)— সব stage-এর hyperparameter একসাথে tune, leak-free। - Production deploy — same pipeline object। Train-test mismatch ০।
Leak detect করার উপায়:
- "Too good to be true" accuracy — sanity alarm।
- Permutation importance — যদি একটি feature suspiciously high → suspect।
- Holdout set যা never touched — final check।
- Production-এ A/B test → notebook number-এর চেয়ে কম হলে leak সম্ভাবনা।
মূল উপলব্ধি: Leak = ML-এর spaghetti code। Production-এ ধরা পড়ে — ব্যয়বহুল। Pipeline + temporal split + group-aware CV = structural defense। Discipline ও tooling দু'টো লাগে। কাগ্জে ৯৯% — production-এ ৬০%। সেই ৪০% gap-ই leak। সম্ভবত কোম্পানি বদলায় career-এ — কিন্তু leak-এর pattern একই থাকে।
প্র ০৪ scikit-learn-এর Pipeline + GridSearchCV — production ML-এর backbone। Cross-validation ও hyperparameter tuning-এ এই combination কেন এত শক্তিশালী? Compute cost কীভাবে manage করেন?
ML model-এর performance ৫০% feature, ৩০% data, ১৫% algorithm, ৫% hyperparameter — এই rule of thumb। কিন্তু সেই ৫% হাজার-ডলার-business value-এর অর্ধেক হতে পারে। GridSearchCV সেই ৫% সিস্টেমেটিকভাবে।
Pipeline + GridSearchCV কেন এত শক্তিশালী:
- Unified API: preprocessing-এর hyperparameter (e.g.,
n_componentsof PCA) ও model-এর hyperparameter (e.g.,Cof LogReg) একসাথে tune। - Leak-free: প্রতি CV fold-এ entire pipeline fresh — preprocessing leak ০।
- Reproducibility: single object — train, save, load, deploy।
- Best estimator auto-extract:
grid.best_estimator_— ready to predict।
সরল উদাহরণ:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
pipe = Pipeline([
("scaler", StandardScaler()),
("pca", PCA()),
("clf", LogisticRegression(max_iter=1000)),
])
grid = {
"pca__n_components": [2, 3, 4],
"clf__C": [0.01, 0.1, 1, 10],
"clf__penalty": ["l1", "l2"],
"clf__solver": ["liblinear"],
}
search = GridSearchCV(pipe, grid, cv=5, scoring="accuracy",
n_jobs=-1, verbose=1)
search.fit(X, y)
print(search.best_params_, search.best_score_)
Compute cost calculation:
- উপরে: ৩ × ৪ × ২ = ২৪ combination × ৫ fold = ১২০টি fit।
- Realistic — ১০ hyperparameter, প্রতিটি ৫ value → ১০M combination — কয়েক দিন।
- Big data + complex model → impossible।
Cost কমানোর strategy:
(১) RandomizedSearchCV — exhaustive-এর বদলে sample:
- সমস্ত combination check না করে — random ১০০টি।
- Bergstra & Bengio (২০১২) — random ≥ grid most cases।
- Continuous parameter-এ আদর্শ।
(২) HalvingGridSearchCV (sklearn ০.২৪+):
- Successive halving — কম resource-এ অনেক candidate, পরে winner-দের বেশি resource।
- প্রায় ১০× faster, similar quality।
(৩) Bayesian optimization (Optuna, Hyperopt):
- Past trial থেকে শিখে — পরের trial smart।
- ৫-১০× কম trial-এ same quality।
optuna— sklearn-compatible, modern best choice।
(৪) Parallelism:
n_jobs=-1— সব CPU core।- Dask + dask-ml — multiple machine।
- Ray Tune — distributed hyperparameter search।
(৫) Smart search space:
- Log-scale (regularization C: 0.001 → 1000) — log-uniform।
- Domain knowledge — যৌক্তিক range।
- Iterative — coarse search → narrow → fine।
(৬) Cheaper proxy:
- Subsample data-তে quick exploration।
- Smaller model-এ trend check, full model-এ final।
- Fewer CV folds (3 instead of 10) early stage-এ।
(৭) Early stopping:
- GBDT-তে validation loss না কমলে stop।
- NN-এ patience-based early stopping।
- Optuna-র pruner — bad trial early kill।
Best practice workflow:
- Quick baseline — default hyperparameter, ১ minute fit।
- Coarse RandomizedSearchCV — ১০-৫০ trial।
- Optuna fine-tune — ১০০-৫০০ trial top region-এ।
- Final model — best params, full data refit।
- Holdout test set — single number reporting।
Production caveat:
- Hyperparameter tune একবার না — periodically retrain।
- Monitor production performance; drift হলে retune।
- Tune cost vs business value — Pareto-rationale।
মূল উপলব্ধি: Hyperparameter search compute-এর সাথে quality-র tradeoff। GridSearchCV — pedagogically সহজ; production-এ Optuna/Bayesian + smart search space। Cost কমাতে — proxy, early stopping, parallel। সেরা ML practitioner-রা compute-এ ১০০× কম খরচ করে similar quality পান — discipline + tooling।
অনুশীলন
-
প্রথম classifier:
load_wine()dataset লোড করুন। Train/test split (test_size=0.25)।RandomForestClassifierদিয়ে fit, test accuracy print।from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier X, y = load_wine(return_X_y=True) X_tr, X_te, y_tr, y_te = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42) rf = RandomForestClassifier(n_estimators=100, random_state=42) rf.fit(X_tr, y_tr) print(f"Test accuracy: {rf.score(X_te, y_te):.3f}") print("\nFeature importances (top 5):") import numpy as np idx = np.argsort(rf.feature_importances_)[-5:][::-1] for i in idx: print(f" {load_wine().feature_names[i]}: {rf.feature_importances_[i]:.3f}") -
Pipeline দিয়ে CV: Iris-এ
StandardScaler + KNeighborsClassifierPipeline বানান। 5-fold CV-এর mean ও std print করুন।from sklearn.datasets import load_iris from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_val_score X, y = load_iris(return_X_y=True) pipe = Pipeline([ ("scaler", StandardScaler()), ("knn", KNeighborsClassifier(n_neighbors=5)), ]) scores = cross_val_score(pipe, X, y, cv=5, scoring="accuracy") print(f"5-fold accuracy: {scores.mean():.3f} ± {scores.std():.3f}") print(f"Per fold: {scores.round(3)}") -
Hyperparameter search: উপরের pipeline-এ
n_neighbors১ থেকে ১৫ পর্যন্ত try করুনGridSearchCVদিয়ে। Best k ও best score print।from sklearn.datasets import load_iris from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import GridSearchCV X, y = load_iris(return_X_y=True) pipe = Pipeline([ ("scaler", StandardScaler()), ("knn", KNeighborsClassifier()), ]) grid = {"knn__n_neighbors": list(range(1, 16))} search = GridSearchCV(pipe, grid, cv=5, scoring="accuracy", n_jobs=-1) search.fit(X, y) print(f"Best k: {search.best_params_}") print(f"Best CV score: {search.best_score_:.3f}")
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ২১ · EDA — Iris ডেটাসেটে পরবর্তী পাঠ Iris-এ পূর্ণ EDA workflow — preprocessing, plot, baseline।
- পাঠ ১৯ · Jupyter Notebook ও Colab আগের পাঠ sklearn কাজের পরিবেশ — notebook।
- Machine Learning track এই পাঠের সাথে সম্পর্কিত প্রতিটি sklearn algorithm-এর গাণিতিক ভিত্তি।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।