ml-practicals-kit 1.0.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.
Files changed (30) hide show
  1. ml_practicals_kit-1.0.0/PKG-INFO +85 -0
  2. ml_practicals_kit-1.0.0/README.md +71 -0
  3. ml_practicals_kit-1.0.0/pyproject.toml +28 -0
  4. ml_practicals_kit-1.0.0/setup.cfg +4 -0
  5. ml_practicals_kit-1.0.0/src/ml_practical/__init__.py +3 -0
  6. ml_practicals_kit-1.0.0/src/ml_practical/__main__.py +8 -0
  7. ml_practicals_kit-1.0.0/src/ml_practical/cli.py +113 -0
  8. ml_practicals_kit-1.0.0/src/ml_practical/desktop.py +52 -0
  9. ml_practicals_kit-1.0.0/src/ml_practical/notebook_builder.py +107 -0
  10. ml_practicals_kit-1.0.0/src/ml_practical/practicals/__init__.py +32 -0
  11. ml_practicals_kit-1.0.0/src/ml_practical/practicals/base.py +180 -0
  12. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p01_naive_bayes.py +70 -0
  13. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p02_simple_linear_regression.py +82 -0
  14. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p03_multiple_linear_regression.py +71 -0
  15. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p04_polynomial_regression.py +72 -0
  16. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p05_lasso_ridge_regression.py +98 -0
  17. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p06_logistic_regression.py +69 -0
  18. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p07_artificial_neural_network.py +86 -0
  19. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p08_knn_classifier.py +91 -0
  20. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p09_decision_tree_classifier.py +84 -0
  21. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p10_svm_classifier.py +80 -0
  22. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p11_kmeans_clustering.py +106 -0
  23. ml_practicals_kit-1.0.0/src/ml_practical/practicals/p12_hierarchical_clustering.py +85 -0
  24. ml_practicals_kit-1.0.0/src/ml_practicals_kit.egg-info/PKG-INFO +85 -0
  25. ml_practicals_kit-1.0.0/src/ml_practicals_kit.egg-info/SOURCES.txt +28 -0
  26. ml_practicals_kit-1.0.0/src/ml_practicals_kit.egg-info/dependency_links.txt +1 -0
  27. ml_practicals_kit-1.0.0/src/ml_practicals_kit.egg-info/entry_points.txt +3 -0
  28. ml_practicals_kit-1.0.0/src/ml_practicals_kit.egg-info/requires.txt +7 -0
  29. ml_practicals_kit-1.0.0/src/ml_practicals_kit.egg-info/top_level.txt +1 -0
  30. ml_practicals_kit-1.0.0/tests/test_generator.py +70 -0
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: ml_practicals_kit
3
+ Version: 1.0.0
4
+ Summary: Generate university ML practical Jupyter notebooks (.ipynb) into a Desktop folder named after your university roll number.
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ Provides-Extra: notebook-runtime
9
+ Requires-Dist: numpy; extra == "notebook-runtime"
10
+ Requires-Dist: pandas; extra == "notebook-runtime"
11
+ Requires-Dist: matplotlib; extra == "notebook-runtime"
12
+ Requires-Dist: scikit-learn; extra == "notebook-runtime"
13
+ Requires-Dist: jupyter; extra == "notebook-runtime"
14
+
15
+ # ml_practicals_kit
16
+
17
+ A lightweight, cross-platform Python CLI package that generates all 12 Machine Learning Practicals as separate **`.py` Python scripts** (or `.ipynb` Jupyter Notebooks with `--format ipynb`) into a folder on your **Desktop** named after your **University Roll Number**.
18
+
19
+ ## Practicals Included
20
+
21
+ 1. **Naïve Bayes Classifier** (`01_Naive_Bayes_Classifier.py`)
22
+ 2. **Simple Linear Regression** (`02_Simple_Linear_Regression.py`)
23
+ 3. **Multiple Linear Regression** (`03_Multiple_Linear_Regression.py`)
24
+ 4. **Polynomial Regression** (`04_Polynomial_Regression.py`)
25
+ 5. **Lasso and Ridge Regression** (`05_Lasso_and_Ridge_Regression.py`)
26
+ 6. **Logistic Regression** (`06_Logistic_Regression.py`)
27
+ 7. **Artificial Neural Network** (`07_Artificial_Neural_Network.py`)
28
+ 8. **K-NN Classifier** (`08_KNN_Classifier.py`)
29
+ 9. **Decision Tree Classification** (`09_Decision_Tree_Classification.py`)
30
+ 10. **SVM Classification** (`10_SVM_Classification.py`)
31
+ 11. **K-Means Clustering** (`11_KMeans_Clustering.py`)
32
+ 12. **Hierarchical Clustering** (`12_Hierarchical_Clustering.py`)
33
+
34
+ ## Evaluation & Metrics Covered
35
+
36
+ - **Train-Test Split** & **k-Fold Cross-Validation** (`k=5`)
37
+ - **Regression**: MSE and $R^2$ score, Actual vs Predicted & Residual plots
38
+ - **Classification**: Accuracy, TP, TN, FP, FN, Error Rate, Recall, Specificity, F1-score, AUC, Confusion Matrix & ROC Curve plots
39
+ - **Clustering**: Silhouette Score, Davies-Bouldin Index, Elbow / Dendrogram plots & 2D PCA cluster visualizations
40
+
41
+ ## Installation
42
+
43
+ Once published to PyPI:
44
+
45
+ ```bash
46
+ pip install ml_practicals_kit
47
+ ```
48
+
49
+ Or install locally from this folder:
50
+
51
+ ```bash
52
+ pip install .
53
+ ```
54
+
55
+ To also install the libraries needed to execute the generated notebooks:
56
+
57
+ ```bash
58
+ pip install ".[notebook-runtime]"
59
+ ```
60
+
61
+ ## Usage
62
+
63
+ Run the command anywhere in your terminal:
64
+
65
+ ```bash
66
+ ml-practical
67
+ ```
68
+
69
+ It will prompt you for your university roll number, or you can pass it directly:
70
+
71
+ ```bash
72
+ ml-practical 2201234567
73
+ ```
74
+
75
+ Or run via module:
76
+
77
+ ```bash
78
+ python -m ml_practical 2201234567
79
+ ```
80
+
81
+ To generate `.ipynb` Jupyter notebooks instead of `.py` files:
82
+
83
+ ```bash
84
+ ml-practical 2201234567 --format ipynb
85
+ ```
@@ -0,0 +1,71 @@
1
+ # ml_practicals_kit
2
+
3
+ A lightweight, cross-platform Python CLI package that generates all 12 Machine Learning Practicals as separate **`.py` Python scripts** (or `.ipynb` Jupyter Notebooks with `--format ipynb`) into a folder on your **Desktop** named after your **University Roll Number**.
4
+
5
+ ## Practicals Included
6
+
7
+ 1. **Naïve Bayes Classifier** (`01_Naive_Bayes_Classifier.py`)
8
+ 2. **Simple Linear Regression** (`02_Simple_Linear_Regression.py`)
9
+ 3. **Multiple Linear Regression** (`03_Multiple_Linear_Regression.py`)
10
+ 4. **Polynomial Regression** (`04_Polynomial_Regression.py`)
11
+ 5. **Lasso and Ridge Regression** (`05_Lasso_and_Ridge_Regression.py`)
12
+ 6. **Logistic Regression** (`06_Logistic_Regression.py`)
13
+ 7. **Artificial Neural Network** (`07_Artificial_Neural_Network.py`)
14
+ 8. **K-NN Classifier** (`08_KNN_Classifier.py`)
15
+ 9. **Decision Tree Classification** (`09_Decision_Tree_Classification.py`)
16
+ 10. **SVM Classification** (`10_SVM_Classification.py`)
17
+ 11. **K-Means Clustering** (`11_KMeans_Clustering.py`)
18
+ 12. **Hierarchical Clustering** (`12_Hierarchical_Clustering.py`)
19
+
20
+ ## Evaluation & Metrics Covered
21
+
22
+ - **Train-Test Split** & **k-Fold Cross-Validation** (`k=5`)
23
+ - **Regression**: MSE and $R^2$ score, Actual vs Predicted & Residual plots
24
+ - **Classification**: Accuracy, TP, TN, FP, FN, Error Rate, Recall, Specificity, F1-score, AUC, Confusion Matrix & ROC Curve plots
25
+ - **Clustering**: Silhouette Score, Davies-Bouldin Index, Elbow / Dendrogram plots & 2D PCA cluster visualizations
26
+
27
+ ## Installation
28
+
29
+ Once published to PyPI:
30
+
31
+ ```bash
32
+ pip install ml_practicals_kit
33
+ ```
34
+
35
+ Or install locally from this folder:
36
+
37
+ ```bash
38
+ pip install .
39
+ ```
40
+
41
+ To also install the libraries needed to execute the generated notebooks:
42
+
43
+ ```bash
44
+ pip install ".[notebook-runtime]"
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ Run the command anywhere in your terminal:
50
+
51
+ ```bash
52
+ ml-practical
53
+ ```
54
+
55
+ It will prompt you for your university roll number, or you can pass it directly:
56
+
57
+ ```bash
58
+ ml-practical 2201234567
59
+ ```
60
+
61
+ Or run via module:
62
+
63
+ ```bash
64
+ python -m ml_practical 2201234567
65
+ ```
66
+
67
+ To generate `.ipynb` Jupyter notebooks instead of `.py` files:
68
+
69
+ ```bash
70
+ ml-practical 2201234567 --format ipynb
71
+ ```
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ml_practicals_kit"
7
+ version = "1.0.0"
8
+ description = "Generate university ML practical Jupyter notebooks (.ipynb) into a Desktop folder named after your university roll number."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+ dependencies = []
13
+
14
+ [project.optional-dependencies]
15
+ notebook-runtime = [
16
+ "numpy",
17
+ "pandas",
18
+ "matplotlib",
19
+ "scikit-learn",
20
+ "jupyter",
21
+ ]
22
+
23
+ [project.scripts]
24
+ ml_practicals_kit = "ml_practical.cli:main"
25
+ ml-practical = "ml_practical.cli:main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """ml_practical: Generate university ML practical Jupyter notebooks."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,8 @@
1
+ """Module entry point for `python -m ml_practical`."""
2
+
3
+ import sys
4
+
5
+ from ml_practical.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,113 @@
1
+ """Command-line interface for ml-practical."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import re
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from ml_practical import __version__
11
+ from ml_practical.desktop import get_desktop_path
12
+ from ml_practical.practicals import ALL_PRACTICALS
13
+
14
+ _INVALID_CHARS_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
15
+
16
+
17
+ def sanitize_roll_number(raw: str) -> str:
18
+ """Validate and sanitize a university roll number for use as a folder name."""
19
+ cleaned = raw.strip()
20
+ if not cleaned:
21
+ raise ValueError("University roll number cannot be empty.")
22
+ if cleaned in {".", ".."} or ".." in cleaned:
23
+ raise ValueError("Invalid university roll number.")
24
+ sanitized = _INVALID_CHARS_RE.sub("_", cleaned).strip(". ")
25
+ if not sanitized:
26
+ raise ValueError("University roll number contains only invalid characters.")
27
+ return sanitized
28
+
29
+
30
+ def generate_practicals(
31
+ roll_number: str,
32
+ base_dir: Path | None = None,
33
+ file_format: str = "py",
34
+ ) -> tuple[Path, list[Path]]:
35
+ """Generate all 12 practical files (.py or .ipynb) inside <base_dir>/<roll_number>."""
36
+ if file_format not in {"py", "ipynb"}:
37
+ raise ValueError(f"Unsupported format '{file_format}'. Choose 'py' or 'ipynb'.")
38
+
39
+ safe_roll = sanitize_roll_number(roll_number)
40
+ target_base = base_dir if base_dir is not None else get_desktop_path()
41
+ output_dir = target_base / safe_roll
42
+ output_dir.mkdir(parents=True, exist_ok=True)
43
+
44
+ created_files: list[Path] = []
45
+ for spec in ALL_PRACTICALS:
46
+ nb = spec.builder(safe_roll)
47
+ out_path = output_dir / spec.get_filename(file_format)
48
+ if file_format == "ipynb":
49
+ nb.write(out_path)
50
+ else:
51
+ nb.write_py(out_path)
52
+ created_files.append(out_path)
53
+
54
+ return output_dir, created_files
55
+
56
+
57
+ def build_parser() -> argparse.ArgumentParser:
58
+ parser = argparse.ArgumentParser(
59
+ prog="ml-practical",
60
+ description="Generate all 12 Machine Learning Practical Python scripts (.py) or notebooks (.ipynb) on your Desktop.",
61
+ )
62
+ parser.add_argument(
63
+ "roll_number",
64
+ nargs="?",
65
+ help="Your university roll number (used as the Desktop folder name).",
66
+ )
67
+ parser.add_argument(
68
+ "-o",
69
+ "--output-dir",
70
+ type=Path,
71
+ default=None,
72
+ help="Optional parent directory instead of the Desktop.",
73
+ )
74
+ parser.add_argument(
75
+ "-f",
76
+ "--format",
77
+ choices=["py", "ipynb"],
78
+ default="py",
79
+ help="Output file format (default: py).",
80
+ )
81
+ parser.add_argument(
82
+ "-v",
83
+ "--version",
84
+ action="version",
85
+ version=f"%(prog)s {__version__}",
86
+ )
87
+ return parser
88
+
89
+
90
+ def main(argv: list[str] | None = None) -> int:
91
+ parser = build_parser()
92
+ args = parser.parse_args(argv)
93
+
94
+ roll_number = args.roll_number
95
+ if not roll_number:
96
+ try:
97
+ roll_number = input("Enter your University Roll Number: ").strip()
98
+ except (EOFError, KeyboardInterrupt):
99
+ print("\nAborted.", file=sys.stderr)
100
+ return 1
101
+
102
+ try:
103
+ output_dir, files = generate_practicals(
104
+ roll_number, base_dir=args.output_dir, file_format=args.format
105
+ )
106
+ except ValueError as exc:
107
+ print(f"Error: {exc}", file=sys.stderr)
108
+ return 1
109
+
110
+ print(f"\nCreated {len(files)} practical .{args.format} files in: {output_dir}")
111
+ for file_path in files:
112
+ print(f" - {file_path.name}")
113
+ return 0
@@ -0,0 +1,52 @@
1
+ """Cross-platform Desktop directory resolution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import sys
8
+ from pathlib import Path
9
+
10
+
11
+ def get_desktop_path() -> Path:
12
+ """Return the current user's Desktop path on Windows, macOS, or Linux."""
13
+ home = Path.home()
14
+
15
+ if sys.platform == "win32":
16
+ try:
17
+ import winreg
18
+
19
+ with winreg.OpenKey(
20
+ winreg.HKEY_CURRENT_USER,
21
+ r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders",
22
+ ) as key:
23
+ raw_desktop, _ = winreg.QueryValueEx(key, "Desktop")
24
+ expanded = Path(os.path.expandvars(str(raw_desktop)))
25
+ if expanded.exists():
26
+ return expanded
27
+ except OSError:
28
+ pass
29
+
30
+ onedrive_desktop = home / "OneDrive" / "Desktop"
31
+ if onedrive_desktop.exists():
32
+ return onedrive_desktop
33
+ return home / "Desktop"
34
+
35
+ if sys.platform == "darwin":
36
+ return home / "Desktop"
37
+
38
+ # Linux / Unix: check XDG user-dirs.dirs
39
+ user_dirs_file = home / ".config" / "user-dirs.dirs"
40
+ if user_dirs_file.exists():
41
+ try:
42
+ content = user_dirs_file.read_text(encoding="utf-8", errors="ignore")
43
+ match = re.search(r'^XDG_DESKTOP_DIR="?([^"\n]+)"?', content, re.MULTILINE)
44
+ if match:
45
+ raw_path = match.group(1).replace("$HOME", str(home))
46
+ resolved = Path(os.path.expandvars(raw_path))
47
+ if resolved.exists():
48
+ return resolved
49
+ except OSError:
50
+ pass
51
+
52
+ return home / "Desktop"
@@ -0,0 +1,107 @@
1
+ """Lightweight nbformat 4.5 Jupyter Notebook (.ipynb) builder with zero external dependencies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import textwrap
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+
12
+ def _to_source_lines(text: str) -> list[str]:
13
+ """Normalize a multiline string into nbformat source lines."""
14
+ dedented = textwrap.dedent(text).strip("\n")
15
+ if not dedented:
16
+ return []
17
+ lines = dedented.splitlines(keepends=True)
18
+ return lines
19
+
20
+
21
+ @dataclass
22
+ class Cell:
23
+ """Represents a single Jupyter notebook cell."""
24
+
25
+ cell_type: Literal["markdown", "code"]
26
+ source: str
27
+ cell_id: str
28
+
29
+ def to_dict(self) -> dict:
30
+ base = {
31
+ "id": self.cell_id,
32
+ "cell_type": self.cell_type,
33
+ "metadata": {},
34
+ "source": _to_source_lines(self.source),
35
+ }
36
+ if self.cell_type == "code":
37
+ base["execution_count"] = None
38
+ base["outputs"] = []
39
+ return base
40
+
41
+
42
+ @dataclass
43
+ class NotebookBuilder:
44
+ """Builds a valid nbformat 4.5 .ipynb document."""
45
+
46
+ title: str
47
+ cells: list[Cell] = field(default_factory=list)
48
+
49
+ def add_markdown(self, source: str) -> NotebookBuilder:
50
+ idx = len(self.cells) + 1
51
+ self.cells.append(Cell(cell_type="markdown", source=source, cell_id=f"cell-{idx:03d}"))
52
+ return self
53
+
54
+ def add_code(self, source: str) -> NotebookBuilder:
55
+ idx = len(self.cells) + 1
56
+ self.cells.append(Cell(cell_type="code", source=source, cell_id=f"cell-{idx:03d}"))
57
+ return self
58
+
59
+ def to_dict(self) -> dict:
60
+ return {
61
+ "nbformat": 4,
62
+ "nbformat_minor": 5,
63
+ "metadata": {
64
+ "kernelspec": {
65
+ "display_name": "Python 3",
66
+ "language": "python",
67
+ "name": "python3",
68
+ },
69
+ "language_info": {
70
+ "codemirror_mode": {"name": "ipython", "version": 3},
71
+ "file_extension": ".py",
72
+ "mimetype": "text/x-python",
73
+ "name": "python",
74
+ "nbconvert_exporter": "python",
75
+ "pygments_lexer": "ipython3",
76
+ "version": "3.10.0",
77
+ },
78
+ },
79
+ "cells": [cell.to_dict() for cell in self.cells],
80
+ }
81
+
82
+ def write(self, path: Path) -> Path:
83
+ path.parent.mkdir(parents=True, exist_ok=True)
84
+ path.write_text(json.dumps(self.to_dict(), indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
85
+ return path
86
+
87
+ def to_python_script(self) -> str:
88
+ """Render the notebook cells as a clean, standalone Python (.py) script."""
89
+ chunks: list[str] = []
90
+ for idx, cell in enumerate(self.cells):
91
+ content = textwrap.dedent(cell.source).strip("\n")
92
+ if not content:
93
+ continue
94
+ if cell.cell_type == "markdown":
95
+ if idx == 0:
96
+ chunks.append(f'"""\n{content}\n"""')
97
+ else:
98
+ commented = "\n".join(f"# {line}" if line else "#" for line in content.splitlines())
99
+ chunks.append(commented)
100
+ else:
101
+ chunks.append(content)
102
+ return "\n\n".join(chunks) + "\n"
103
+
104
+ def write_py(self, path: Path) -> Path:
105
+ path.parent.mkdir(parents=True, exist_ok=True)
106
+ path.write_text(self.to_python_script(), encoding="utf-8")
107
+ return path
@@ -0,0 +1,32 @@
1
+ """Registry of all 12 ML practicals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ml_practical.practicals.base import PracticalSpec
6
+ from ml_practical.practicals.p01_naive_bayes import SPEC as P01
7
+ from ml_practical.practicals.p02_simple_linear_regression import SPEC as P02
8
+ from ml_practical.practicals.p03_multiple_linear_regression import SPEC as P03
9
+ from ml_practical.practicals.p04_polynomial_regression import SPEC as P04
10
+ from ml_practical.practicals.p05_lasso_ridge_regression import SPEC as P05
11
+ from ml_practical.practicals.p06_logistic_regression import SPEC as P06
12
+ from ml_practical.practicals.p07_artificial_neural_network import SPEC as P07
13
+ from ml_practical.practicals.p08_knn_classifier import SPEC as P08
14
+ from ml_practical.practicals.p09_decision_tree_classifier import SPEC as P09
15
+ from ml_practical.practicals.p10_svm_classifier import SPEC as P10
16
+ from ml_practical.practicals.p11_kmeans_clustering import SPEC as P11
17
+ from ml_practical.practicals.p12_hierarchical_clustering import SPEC as P12
18
+
19
+ ALL_PRACTICALS: list[PracticalSpec] = [
20
+ P01,
21
+ P02,
22
+ P03,
23
+ P04,
24
+ P05,
25
+ P06,
26
+ P07,
27
+ P08,
28
+ P09,
29
+ P10,
30
+ P11,
31
+ P12,
32
+ ]
@@ -0,0 +1,180 @@
1
+ """Shared notebook templates and code snippets for ML practicals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Callable
7
+
8
+ from ml_practical.notebook_builder import NotebookBuilder
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class PracticalSpec:
13
+ """Metadata and builder function for a single ML practical."""
14
+
15
+ number: int
16
+ slug: str
17
+ title: str
18
+ category: str
19
+ builder: Callable[[str], NotebookBuilder]
20
+
21
+ @property
22
+ def filename(self) -> str:
23
+ return f"{self.number:02d}_{self.slug}.py"
24
+
25
+ def get_filename(self, file_format: str = "py") -> str:
26
+ return f"{self.number:02d}_{self.slug}.{file_format}"
27
+
28
+
29
+ def add_header(
30
+ nb: NotebookBuilder,
31
+ *,
32
+ number: int,
33
+ title: str,
34
+ roll_number: str,
35
+ aim: str,
36
+ dataset_info: str,
37
+ metrics_info: str,
38
+ ) -> NotebookBuilder:
39
+ """Add a standardized header markdown cell to a practical notebook."""
40
+ nb.add_markdown(
41
+ f"""
42
+ # Practical {number}: {title}
43
+
44
+ - **University Roll Number:** `{roll_number}`
45
+ - **Aim:** {aim}
46
+ - **Dataset:** {dataset_info}
47
+ - **Evaluation Protocol:** Train-Test Split (80/20) and 5-Fold Cross-Validation
48
+ - **Reported Metrics:** {metrics_info}
49
+ """
50
+ )
51
+ return nb
52
+
53
+
54
+ CLASSIFICATION_EVAL_HELPER = '''
55
+ def evaluate_classification_model(model, X_train, X_test, y_train, y_test, X_all, y_all, model_name="Model", cv_folds=5):
56
+ """Fit model, evaluate on train-test split & k-fold CV, and plot Confusion Matrix & ROC Curve."""
57
+ model.fit(X_train, y_train)
58
+ y_pred = model.predict(X_test)
59
+
60
+ if hasattr(model, "predict_proba"):
61
+ y_prob = model.predict_proba(X_test)[:, 1]
62
+ elif hasattr(model, "decision_function"):
63
+ y_prob = model.decision_function(X_test)
64
+ else:
65
+ y_prob = y_pred
66
+
67
+ tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()
68
+ accuracy = accuracy_score(y_test, y_pred)
69
+ error_rate = 1.0 - accuracy
70
+ recall = recall_score(y_test, y_pred)
71
+ specificity = tn / (tn + fp) if (tn + fp) > 0 else 0.0
72
+ f1 = f1_score(y_test, y_pred)
73
+ auc_score = roc_auc_score(y_test, y_prob)
74
+
75
+ print(f"=== {model_name} (Train-Test Split) ===")
76
+ print(f"TP: {tp} | TN: {tn} | FP: {fp} | FN: {fn}")
77
+ print(f"Accuracy : {accuracy:.4f}")
78
+ print(f"Error Rate : {error_rate:.4f}")
79
+ print(f"Recall : {recall:.4f}")
80
+ print(f"Specificity : {specificity:.4f}")
81
+ print(f"F1-Score : {f1:.4f}")
82
+ print(f"ROC-AUC : {auc_score:.4f}")
83
+
84
+ # k-Fold Cross-Validation
85
+ skf = StratifiedKFold(n_splits=cv_folds, shuffle=True, random_state=42)
86
+ cv_results = cross_validate(
87
+ model, X_all, y_all, cv=skf,
88
+ scoring=["accuracy", "recall", "f1", "roc_auc"]
89
+ )
90
+ print(f"\\n=== {model_name} ({cv_folds}-Fold Cross-Validation) ===")
91
+ print(f"CV Accuracy : {cv_results['test_accuracy'].mean():.4f} +/- {cv_results['test_accuracy'].std():.4f}")
92
+ print(f"CV Recall : {cv_results['test_recall'].mean():.4f} +/- {cv_results['test_recall'].std():.4f}")
93
+ print(f"CV F1-Score : {cv_results['test_f1'].mean():.4f} +/- {cv_results['test_f1'].std():.4f}")
94
+ print(f"CV ROC-AUC : {cv_results['test_roc_auc'].mean():.4f} +/- {cv_results['test_roc_auc'].std():.4f}")
95
+
96
+ # Plots: Confusion Matrix & ROC Curve
97
+ fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
98
+ ConfusionMatrixDisplay.from_predictions(y_test, y_pred, ax=axes[0], cmap="Blues", colorbar=False)
99
+ axes[0].set_title(f"{model_name} - Confusion Matrix")
100
+
101
+ fpr, tpr, _ = roc_curve(y_test, y_prob)
102
+ axes[1].plot(fpr, tpr, label=f"AUC = {auc_score:.4f}", linewidth=2)
103
+ axes[1].plot([0, 1], [0, 1], "k--", alpha=0.6)
104
+ axes[1].set_xlabel("False Positive Rate (1 - Specificity)")
105
+ axes[1].set_ylabel("True Positive Rate (Recall)")
106
+ axes[1].set_title(f"{model_name} - ROC Curve")
107
+ axes[1].legend(loc="lower right")
108
+ axes[1].grid(alpha=0.3)
109
+ plt.tight_layout()
110
+ plt.show()
111
+ '''
112
+
113
+
114
+ REGRESSION_EVAL_HELPER = '''
115
+ def evaluate_regression_model(model, X_train, X_test, y_train, y_test, X_all, y_all, model_name="Model", cv_folds=5):
116
+ """Fit regression model, evaluate MSE & R2 on train-test split & k-fold CV, and plot diagnostics."""
117
+ model.fit(X_train, y_train)
118
+ y_pred = model.predict(X_test)
119
+
120
+ mse = mean_squared_error(y_test, y_pred)
121
+ r2 = r2_score(y_test, y_pred)
122
+
123
+ print(f"=== {model_name} (Train-Test Split) ===")
124
+ print(f"MSE : {mse:.4f}")
125
+ print(f"R2 Score : {r2:.4f}")
126
+
127
+ # k-Fold Cross-Validation
128
+ kf = KFold(n_splits=cv_folds, shuffle=True, random_state=42)
129
+ cv_mse = -cross_val_score(model, X_all, y_all, cv=kf, scoring="neg_mean_squared_error")
130
+ cv_r2 = cross_val_score(model, X_all, y_all, cv=kf, scoring="r2")
131
+
132
+ print(f"\\n=== {model_name} ({cv_folds}-Fold Cross-Validation) ===")
133
+ print(f"CV MSE : {cv_mse.mean():.4f} +/- {cv_mse.std():.4f}")
134
+ print(f"CV R2 Score : {cv_r2.mean():.4f} +/- {cv_r2.std():.4f}")
135
+
136
+ # Diagnostic Plots
137
+ fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
138
+ axes[0].scatter(y_test, y_pred, alpha=0.65, edgecolors="k", linewidths=0.4)
139
+ lims = [min(y_test.min(), y_pred.min()), max(y_test.max(), y_pred.max())]
140
+ axes[0].plot(lims, lims, "r--", linewidth=1.5)
141
+ axes[0].set_xlabel("Actual Values")
142
+ axes[0].set_ylabel("Predicted Values")
143
+ axes[0].set_title(f"{model_name}: Actual vs Predicted")
144
+ axes[0].grid(alpha=0.3)
145
+
146
+ residuals = y_test - y_pred
147
+ axes[1].scatter(y_pred, residuals, alpha=0.65, edgecolors="k", linewidths=0.4)
148
+ axes[1].axhline(0, color="r", linestyle="--", linewidth=1.5)
149
+ axes[1].set_xlabel("Predicted Values")
150
+ axes[1].set_ylabel("Residuals")
151
+ axes[1].set_title(f"{model_name}: Residual Plot")
152
+ axes[1].grid(alpha=0.3)
153
+ plt.tight_layout()
154
+ plt.show()
155
+ '''
156
+
157
+
158
+ def add_classification_split_and_helper(nb: NotebookBuilder) -> None:
159
+ """Add train-test split and classification evaluation helper cells."""
160
+ nb.add_code(
161
+ """
162
+ X_train, X_test, y_train, y_test = train_test_split(
163
+ X, y, test_size=0.2, random_state=42, stratify=y
164
+ )
165
+ """
166
+ )
167
+ nb.add_code(CLASSIFICATION_EVAL_HELPER)
168
+
169
+
170
+ def add_regression_split_and_helper(nb: NotebookBuilder) -> None:
171
+ """Add train-test split and regression evaluation helper cells."""
172
+ nb.add_code(
173
+ """
174
+ X_train, X_test, y_train, y_test = train_test_split(
175
+ X, y, test_size=0.2, random_state=42
176
+ )
177
+ """
178
+ )
179
+ nb.add_code(REGRESSION_EVAL_HELPER)
180
+