ml-lab-prep 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ml_lab_prep-0.1.0/PKG-INFO +31 -0
- ml_lab_prep-0.1.0/README.md +15 -0
- ml_lab_prep-0.1.0/pyproject.toml +23 -0
- ml_lab_prep-0.1.0/setup.cfg +4 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/__init__.py +1 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/cli.py +39 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/EXAM_PLAYBOOK.md +83 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/HOW_TO_RUN.md +84 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/check_setup.py +35 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/data/breast_cancer.csv +570 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/data/diabetes_messy.csv +443 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/data/loan_data.csv +601 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/data/spambase.csv +4602 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/data/wine.csv +179 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/practice/01_Spambase_Classification.ipynb +544 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/practice/02_BreastCancer_Trees_Ensembles_PCA.ipynb +524 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/practice/03_LoanAmount_Regression.ipynb +528 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/practice/04_KMeans_Clustering_PCA.ipynb +220 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/practice/05_Drill_A_Wine_Classification.ipynb +208 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/practice/06_Drill_B_Diabetes_Regression.ipynb +183 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/solved/01_Spambase_Classification.ipynb +2453 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/solved/02_BreastCancer_Trees_Ensembles_PCA.ipynb +2208 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/solved/03_LoanAmount_Regression.ipynb +2611 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/solved/04_KMeans_Clustering_PCA.ipynb +759 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/solved/05_Drill_A_Wine_Classification.ipynb +772 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep/content/solved/06_Drill_B_Diabetes_Regression.ipynb +639 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep.egg-info/PKG-INFO +31 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep.egg-info/SOURCES.txt +30 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep.egg-info/dependency_links.txt +1 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep.egg-info/entry_points.txt +2 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep.egg-info/requires.txt +7 -0
- ml_lab_prep-0.1.0/src/ml_lab_prep.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ml-lab-prep
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Practice and solved Jupyter notebooks for an ML lab exam: EDA, tuning, CV, PCA, significance tests.
|
|
5
|
+
Classifier: Programming Language :: Python :: 3
|
|
6
|
+
Classifier: Intended Audience :: Education
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: numpy
|
|
10
|
+
Requires-Dist: pandas
|
|
11
|
+
Requires-Dist: scikit-learn>=1.2
|
|
12
|
+
Requires-Dist: scipy
|
|
13
|
+
Requires-Dist: matplotlib
|
|
14
|
+
Requires-Dist: seaborn
|
|
15
|
+
Requires-Dist: xgboost
|
|
16
|
+
|
|
17
|
+
# ml-lab-prep
|
|
18
|
+
|
|
19
|
+
Practice and solved notebooks for a machine learning lab exam (classification, regression, K-Means, PCA, grid vs random search, 5-fold CV, Friedman/ANOVA and post-hoc tests), plus the datasets they use.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install ml-lab-prep
|
|
23
|
+
ml-lab-prep check # verify scikit-learn / xgboost etc. work
|
|
24
|
+
ml-lab-prep init # copies notebooks + data into ./ML_Lab_Prep
|
|
25
|
+
cd ML_Lab_Prep && jupyter notebook
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Options: `ml-lab-prep init my_folder`, `ml-lab-prep init --practice-only`.
|
|
29
|
+
Start with `practice/01_Spambase_Classification.ipynb`; `solved/` has run outputs; read `EXAM_PLAYBOOK.md` last.
|
|
30
|
+
|
|
31
|
+
For study use. Follow your institution's rules on what material is allowed in an exam.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# ml-lab-prep
|
|
2
|
+
|
|
3
|
+
Practice and solved notebooks for a machine learning lab exam (classification, regression, K-Means, PCA, grid vs random search, 5-fold CV, Friedman/ANOVA and post-hoc tests), plus the datasets they use.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install ml-lab-prep
|
|
7
|
+
ml-lab-prep check # verify scikit-learn / xgboost etc. work
|
|
8
|
+
ml-lab-prep init # copies notebooks + data into ./ML_Lab_Prep
|
|
9
|
+
cd ML_Lab_Prep && jupyter notebook
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Options: `ml-lab-prep init my_folder`, `ml-lab-prep init --practice-only`.
|
|
13
|
+
Start with `practice/01_Spambase_Classification.ipynb`; `solved/` has run outputs; read `EXAM_PLAYBOOK.md` last.
|
|
14
|
+
|
|
15
|
+
For study use. Follow your institution's rules on what material is allowed in an exam.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ml-lab-prep"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Practice and solved Jupyter notebooks for an ML lab exam: EDA, tuning, CV, PCA, significance tests."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"numpy", "pandas", "scikit-learn>=1.2", "scipy", "matplotlib", "seaborn", "xgboost",
|
|
13
|
+
]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Intended Audience :: Education"]
|
|
15
|
+
|
|
16
|
+
[project.scripts]
|
|
17
|
+
ml-lab-prep = "ml_lab_prep.cli:main"
|
|
18
|
+
|
|
19
|
+
[tool.setuptools.packages.find]
|
|
20
|
+
where = ["src"]
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.package-data]
|
|
23
|
+
ml_lab_prep = ["content/**/*"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import argparse, runpy, shutil, sys
|
|
2
|
+
from importlib.resources import files
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _content() -> Path:
|
|
7
|
+
return Path(str(files("ml_lab_prep") / "content"))
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def init(dest: str, practice_only: bool) -> int:
|
|
11
|
+
out = Path(dest)
|
|
12
|
+
if out.exists() and any(out.iterdir()):
|
|
13
|
+
print(f"{out} already exists and is not empty. Pick another folder.")
|
|
14
|
+
return 1
|
|
15
|
+
ignore = shutil.ignore_patterns("solved", "__pycache__") if practice_only else shutil.ignore_patterns("__pycache__")
|
|
16
|
+
shutil.copytree(_content(), out, ignore=ignore, dirs_exist_ok=True)
|
|
17
|
+
print(f"Copied to {out.resolve()}\nNext: cd {out} && jupyter notebook (open practice/01_Spambase_Classification.ipynb)")
|
|
18
|
+
return 0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main(argv=None) -> int:
|
|
22
|
+
p = argparse.ArgumentParser(prog="ml-lab-prep")
|
|
23
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
24
|
+
i = sub.add_parser("init", help="copy notebooks and data into a folder")
|
|
25
|
+
i.add_argument("dest", nargs="?", default="ML_Lab_Prep")
|
|
26
|
+
i.add_argument("--practice-only", action="store_true", help="skip the solved notebooks")
|
|
27
|
+
sub.add_parser("check", help="check that required libraries work")
|
|
28
|
+
sub.add_parser("path", help="print where the bundled content lives")
|
|
29
|
+
a = p.parse_args(argv)
|
|
30
|
+
if a.cmd == "init":
|
|
31
|
+
return init(a.dest, a.practice_only)
|
|
32
|
+
if a.cmd == "path":
|
|
33
|
+
print(_content()); return 0
|
|
34
|
+
runpy.run_path(str(_content() / "check_setup.py"), run_name="__main__")
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
sys.exit(main())
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# ML lab exam playbook
|
|
2
|
+
|
|
3
|
+
Your sir's rule: understand the pipeline, adapt the cheat sheet. Marks come from **implementing a substantial part yourself (aim for 75%+)** and explaining it. Below 50% implementation scores 0, so never paste a block you cannot explain.
|
|
4
|
+
|
|
5
|
+
## 1 · The 10 steps (with cheat-sheet sections)
|
|
6
|
+
|
|
7
|
+
| Step | What to do | Cheat sheet |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| 1 | Read csv, drop duplicates, shape / dtypes / missing / target counts. **Balanced or imbalanced? Classification or regression?** | §1 Pandas / IO |
|
|
10
|
+
| 2 | EDA: target plot, describe, correlation heatmap, 1-2 boxplots/regplots, outlier check. Write the 3-4 line summary | §1, §5 Visualization |
|
|
11
|
+
| 3 | Fix data: impute NaN, encode categoricals, log1p if skewed | §1 Fill, Scaling & Encoding |
|
|
12
|
+
| 4 | `train_test_split` (`stratify=y` for classification only) | §1 Split |
|
|
13
|
+
| 5 | Pipeline: impute, scale, (PCA), model | §2 Pipeline |
|
|
14
|
+
| 6 | Baseline fit, predict, metrics | §2 General, §5 |
|
|
15
|
+
| 7 | Hyper-parameter search with `cv=5` (Grid, or Random if the grid is big) | §4, Parameter Grids |
|
|
16
|
+
| 8 | 5-fold CV: report **mean ± std**, not one split | §4 K-Fold & CV |
|
|
17
|
+
| 9 | PCA with vs without (if asked): same model, same CV, compare + number of components | §6 |
|
|
18
|
+
| 10 | Significance: Friedman/ANOVA, post-hoc, paired t / Wilcoxon, verdict at p < 0.05 | §7 |
|
|
19
|
+
|
|
20
|
+
## 2 · What to change per dataset
|
|
21
|
+
|
|
22
|
+
| Item | Classification | Regression |
|
|
23
|
+
|---|---|---|
|
|
24
|
+
| Split | `stratify=y` | no stratify |
|
|
25
|
+
| CV splitter | `StratifiedKFold` | `KFold` |
|
|
26
|
+
| Scoring string | `"accuracy"`, `"f1"`, `"f1_macro"` (3+ classes) | `"r2"`, `"neg_root_mean_squared_error"` |
|
|
27
|
+
| Metrics | accuracy, precision, recall, F1, confusion matrix, ROC-AUC | MAE, MSE, RMSE, R², adjusted R² |
|
|
28
|
+
| 3+ classes | `average="macro"`; `roc_auc_score(y, proba, multi_class="ovr")` | n/a |
|
|
29
|
+
| Text target | `LabelEncoder` (print `classes_`: alphabetical, so B=0, M=1) | n/a |
|
|
30
|
+
| Text features | `OneHotEncoder` (or `OrdinalEncoder` if ordered) via `ColumnTransformer` | same |
|
|
31
|
+
| Tree grid criterion | `gini` / `entropy` | `squared_error` / `friedman_mse` |
|
|
32
|
+
| Model class | `...Classifier` | `...Regressor` (SVR needs the **target** scaled too) |
|
|
33
|
+
|
|
34
|
+
## 3 · Pitfalls that cost marks
|
|
35
|
+
|
|
36
|
+
* **`model__` prefix.** Tuning a `Pipeline` needs `model__max_depth`; tuning a bare estimator needs `max_depth`.
|
|
37
|
+
* **Leakage.** Fit scaler/PCA on train only (inside the pipeline, or `fit_transform(train)` then `transform(test)`). Never `fit_transform` on all data before splitting.
|
|
38
|
+
* **Scaling by model.** Needed: KNN, SVM, Logistic, Linear with penalty, PCA, K-Means. Not needed: trees, forests, boosting, GaussianNB. MultinomialNB: non-negative only (`MinMaxScaler`).
|
|
39
|
+
* **SVM grid.** `gamma` only for rbf/poly/sigmoid, `degree` only for poly: use a *list of dicts*.
|
|
40
|
+
* **`solver="liblinear"` is binary-only in recent scikit-learn.** For 3+ classes use `lbfgs` (L2) or `saga` (L1/elasticnet) and a larger `max_iter`.
|
|
41
|
+
* **`predict_proba` for SVC** needs `probability=True`.
|
|
42
|
+
* **XGBoost grid** has 324 combinations: that is the reason to use `RandomizedSearchCV`.
|
|
43
|
+
* **Class labels.** In `precision_score` the "positive" class is label 1. Know which class that is.
|
|
44
|
+
* **Friedman needs at least 3 models.** For 2 models use paired t-test / Wilcoxon.
|
|
45
|
+
* **Wilcoxon on 5 folds can never give p < 0.05** (minimum 0.0625). Use repeated CV (5×3 = 15 paired scores) for tests and say why.
|
|
46
|
+
|
|
47
|
+
## 4 · How to say it (write these in the answer or viva)
|
|
48
|
+
|
|
49
|
+
**EDA, 3-4 lines.** "The dataset has N rows and M features, K numeric and J categorical, with/without missing values. The target is balanced / imbalanced (x% vs y%), so accuracy alone is / is not enough. Features are skewed / correlated / on different scales, so I scaled them / used PCA / regularised. The strongest predictors are A, B."
|
|
50
|
+
|
|
51
|
+
**What PCA does.** "PCA rotates the features onto orthogonal directions ordered by variance and keeps the first few (here N components keeping 95% of the variance). It reduces dimension, removes correlation and speeds training, but the components mix the original features, so supervised signal can be lost. With PCA accuracy went from X to Y while features dropped from M to N."
|
|
52
|
+
|
|
53
|
+
**Grid vs Random.** "Grid tries every combination (G fits), Random tries n_iter sampled ones (R fits). Both reached similar best CV score (a vs b); random was k times faster. Use random when the grid is large."
|
|
54
|
+
|
|
55
|
+
**Significance.** "A higher accuracy does not prove a better model. I compared models on the same 15 repeated-CV folds. Friedman gave p = … (< 0.05), so at least one model differs. Post-hoc paired tests with Bonferroni show that A is significantly better than B and C but not than D. The mean gap between A and D is only 0.4%, so in practice they are equivalent."
|
|
56
|
+
|
|
57
|
+
**5-fold CV.** "Data split into 5 folds; train on 4, validate on 1, repeat 5 times; report mean ± std: 0.93 ± 0.01."
|
|
58
|
+
|
|
59
|
+
**Input → intermediate → output.** Input: dataset and features. Intermediate: preprocessing, PCA (if any), model, tuning, CV. Output: predictions, metrics, best parameters, significance verdict.
|
|
60
|
+
|
|
61
|
+
## 5 · Imbalance checklist
|
|
62
|
+
1. Print `value_counts(normalize=True)` first.
|
|
63
|
+
2. If the minority class is below about 30%: stop quoting accuracy alone. Report precision, recall, F1, confusion matrix.
|
|
64
|
+
3. Fixes: `class_weight="balanced"`, oversample the minority / undersample the majority (`sklearn.utils.resample`), threshold tuning.
|
|
65
|
+
4. Say which error is worse (medical: missed disease = false negative, so favour recall).
|
|
66
|
+
|
|
67
|
+
## 6 · Which hyper-parameters matter (for "which values should be tested?")
|
|
68
|
+
|
|
69
|
+
| Model | Key hyper-parameters | Why |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| Decision Tree | `max_depth`, `min_samples_leaf/split`, `criterion` | control tree size = overfitting |
|
|
72
|
+
| KNN | `n_neighbors`, `weights`, `algorithm` | k is the bias/variance dial |
|
|
73
|
+
| SVM | `kernel`, `C`, `gamma`, `degree` | margin hardness, reach of a point |
|
|
74
|
+
| Logistic | `C`, `penalty` | regularisation strength / type |
|
|
75
|
+
| Ridge / Lasso | `alpha` (ElasticNet: `l1_ratio`) | shrinkage strength |
|
|
76
|
+
| Random Forest | `n_estimators`, `max_depth`, `max_features`, `min_samples_split` | tree count, tree size, decorrelation |
|
|
77
|
+
| AdaBoost | `n_estimators`, `learning_rate`, base `estimator` depth | weak-learner count and step |
|
|
78
|
+
| Gradient Boosting / XGBoost | `n_estimators`, `learning_rate`, `max_depth`, `subsample` | shallow trees + small steps generalise |
|
|
79
|
+
| K-Means | `n_clusters` (+ `n_init`) | choose by elbow + silhouette |
|
|
80
|
+
| PCA | `n_components` (0.95 or int) | variance kept |
|
|
81
|
+
|
|
82
|
+
## 7 · Cheat-sheet gaps to fill from these notebooks
|
|
83
|
+
`ColumnTransformer` (mixed column types), `Pipeline` step names, `RepeatedStratifiedKFold` for significance, `LabelEncoder` positive-class check, `TransformedTargetRegressor`, results-table building, Bonferroni correction.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# How to run these notebooks
|
|
2
|
+
|
|
3
|
+
## What is in this folder
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
ML_Lab_Prep/
|
|
7
|
+
data/ the 5 csv files (3 from your assignments + 2 for the drills)
|
|
8
|
+
solved/ fully run notebooks WITH outputs (read these, or re-run them)
|
|
9
|
+
practice/ same notebooks with every code cell emptied and a TODO hint (type these yourself)
|
|
10
|
+
EXAM_PLAYBOOK.md what to change per dataset, pitfalls, how to explain EDA / PCA / significance
|
|
11
|
+
check_setup.py run once on your exam laptop
|
|
12
|
+
requirements.txt
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
| # | Notebook | Dataset | Run time (2 CPU cores) |
|
|
16
|
+
|---|---|---|---|
|
|
17
|
+
| 01 | Spambase classification | spambase.csv | about 3 min |
|
|
18
|
+
| 02 | Breast cancer: trees, ensembles, PCA | breast_cancer.csv | about 5 to 8 min |
|
|
19
|
+
| 03 | Loan amount regression | loan_data.csv | about 5 to 8 min |
|
|
20
|
+
| 04 | K-Means + PCA | breast_cancer.csv | under 1 min |
|
|
21
|
+
| 05 | Drill A: Wine (3 classes) | wine.csv | about 1 min |
|
|
22
|
+
| 06 | Drill B: Diabetes, messy data | diabetes_messy.csv | about 1 min |
|
|
23
|
+
|
|
24
|
+
The notebooks read data from `../data/...`. **Keep the folder structure as is.** If you move a notebook, change the `DATA = ...` line in the config cell.
|
|
25
|
+
|
|
26
|
+
## Step 0 (do this tonight): check your laptop
|
|
27
|
+
|
|
28
|
+
Your own repo `.venv` already has numpy, pandas, scikit-learn 1.9, scipy and xgboost. It has `ipykernel` but **no Jupyter Notebook interface**, so install it once.
|
|
29
|
+
|
|
30
|
+
Mac Terminal:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
cd ~/Dev/college/SEM-5/ML/ML_Lab_Prep
|
|
34
|
+
source ../.venv/bin/activate
|
|
35
|
+
pip install notebook seaborn # only if missing
|
|
36
|
+
python check_setup.py # should end with: ALL GOOD
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
If you use Anaconda instead, open **Anaconda Prompt** (Windows) or Terminal and run `pip install xgboost seaborn`, then `python check_setup.py`.
|
|
40
|
+
|
|
41
|
+
## Option 1: Anaconda Navigator (what you said you would use in the lab)
|
|
42
|
+
|
|
43
|
+
1. Open **Anaconda Navigator**.
|
|
44
|
+
2. Click **Launch** under **Jupyter Notebook**. A browser tab opens.
|
|
45
|
+
3. In the file list go to `ML_Lab_Prep` then `practice` (or `solved`) and click a notebook.
|
|
46
|
+
4. Run one cell with **Shift+Enter**. Run everything with menu **Kernel, Restart & Run All**.
|
|
47
|
+
5. If you see `ModuleNotFoundError: xgboost`: Navigator, **Environments** tab, change the filter to *Not installed*, search `xgboost`, tick it, **Apply**. Or in Anaconda Prompt: `pip install xgboost`. Then restart the notebook kernel.
|
|
48
|
+
|
|
49
|
+
## Option 2: Jupyter from the terminal
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
cd ~/Dev/college/SEM-5/ML/ML_Lab_Prep
|
|
53
|
+
source ../.venv/bin/activate
|
|
54
|
+
jupyter notebook
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Option 3: VS Code
|
|
58
|
+
|
|
59
|
+
Open the `ML_Lab_Prep` folder, open a `.ipynb`, click **Select Kernel** (top right), pick the `.venv` Python, then **Run All** or run cell by cell.
|
|
60
|
+
|
|
61
|
+
## Option 4: Google Colab
|
|
62
|
+
|
|
63
|
+
Upload the notebook and the csv you need, then in the config cell change the path to the bare file name, for example `DATA = "spambase.csv"`. Colab already has everything except possibly `xgboost` (`!pip install xgboost` in a cell if needed).
|
|
64
|
+
|
|
65
|
+
## How to practice (suggested order for tonight)
|
|
66
|
+
|
|
67
|
+
1. Run `check_setup.py` (2 min).
|
|
68
|
+
2. Open **practice/01**. Keep the cheat sheet next to you. For every cell read the TODO hint, type the code, run it. Peek at **solved/01** only after you are stuck for 3 minutes.
|
|
69
|
+
3. Do the same for **02** (ensembles, PCA vs no PCA) and **03** (regression).
|
|
70
|
+
4. If time is left: **05** and **06**, the 45-minute timed drills. These are the closest thing to the exam.
|
|
71
|
+
5. Read `EXAM_PLAYBOOK.md` last, as a final revision sheet.
|
|
72
|
+
|
|
73
|
+
If you only have 2 hours: 01 (classification skeleton), 03 (regression skeleton), then the playbook. Once you can write the skeleton, other models are only a changed constructor and grid.
|
|
74
|
+
|
|
75
|
+
## Troubleshooting
|
|
76
|
+
|
|
77
|
+
| Symptom | Cause / fix |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `Invalid parameter 'max_depth' for estimator Pipeline` | Grid keys inside a pipeline need the step name: `model__max_depth`. For a bare estimator use `max_depth`. |
|
|
80
|
+
| `FileNotFoundError: ../data/...csv` | You moved the notebook. Edit the `DATA` line. |
|
|
81
|
+
| Run is very slow | Lower `n_jobs`/grid size, or use `RandomizedSearchCV` with a small `n_iter`. Your sir said random search exists for this reason. |
|
|
82
|
+
| `FutureWarning: 'penalty' was deprecated` | Harmless on sklearn 1.8+; the cheat sheet syntax still works. Warnings are hidden in the notebooks. |
|
|
83
|
+
| `ValueError: Input X contains NaN` | Add the `SimpleImputer` step (it is already inside `build`). |
|
|
84
|
+
| MultinomialNB error about negative values | Use `MinMaxScaler`, not `StandardScaler`, before MultinomialNB. |
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Run this on your lab laptop BEFORE the exam: python check_setup.py"""
|
|
2
|
+
import importlib, sys
|
|
3
|
+
|
|
4
|
+
print("Python", sys.version.split()[0])
|
|
5
|
+
need = ["numpy", "pandas", "sklearn", "scipy", "matplotlib", "seaborn", "xgboost"]
|
|
6
|
+
bad = []
|
|
7
|
+
for m in need:
|
|
8
|
+
try:
|
|
9
|
+
mod = importlib.import_module(m)
|
|
10
|
+
print(f" OK {m:12s}{getattr(mod, '__version__', '')}")
|
|
11
|
+
except Exception as e:
|
|
12
|
+
print(f" FAIL {m:12s}{e}")
|
|
13
|
+
bad.append(m)
|
|
14
|
+
|
|
15
|
+
if not bad:
|
|
16
|
+
# exercises every cheat-sheet call that has changed between versions
|
|
17
|
+
import warnings; warnings.filterwarnings("ignore")
|
|
18
|
+
import numpy as np
|
|
19
|
+
from sklearn.ensemble import AdaBoostClassifier, BaggingClassifier, StackingClassifier
|
|
20
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
21
|
+
from sklearn.linear_model import LogisticRegression
|
|
22
|
+
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
|
|
23
|
+
from xgboost import XGBClassifier
|
|
24
|
+
from sklearn.datasets import load_wine
|
|
25
|
+
X, y = load_wine(return_X_y=True); y = (y == 0).astype(int) # binary: liblinear is binary-only in new sklearn
|
|
26
|
+
for name, m in [("AdaBoost(estimator=)", AdaBoostClassifier(estimator=DecisionTreeClassifier(max_depth=1))),
|
|
27
|
+
("Bagging(estimator=)", BaggingClassifier(estimator=DecisionTreeClassifier())),
|
|
28
|
+
("XGBClassifier", XGBClassifier(eval_metric="logloss")),
|
|
29
|
+
("LogisticRegression(penalty=l1)", LogisticRegression(penalty="l1", solver="liblinear", max_iter=2000))]:
|
|
30
|
+
try:
|
|
31
|
+
cross_val_score(m, X, y, cv=3); print(f" OK {name}")
|
|
32
|
+
except Exception as e:
|
|
33
|
+
print(f" FAIL {name}: {str(e)[:80]}"); bad.append(name)
|
|
34
|
+
|
|
35
|
+
print("\nALL GOOD" if not bad else f"\nFIX THESE: {bad}\n pip install -r requirements.txt (or: pip install xgboost)")
|