ml-practicals-kit 1.0.0__py3-none-any.whl
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_practical/__init__.py +3 -0
- ml_practical/__main__.py +8 -0
- ml_practical/cli.py +113 -0
- ml_practical/desktop.py +52 -0
- ml_practical/notebook_builder.py +107 -0
- ml_practical/practicals/__init__.py +32 -0
- ml_practical/practicals/base.py +180 -0
- ml_practical/practicals/p01_naive_bayes.py +70 -0
- ml_practical/practicals/p02_simple_linear_regression.py +82 -0
- ml_practical/practicals/p03_multiple_linear_regression.py +71 -0
- ml_practical/practicals/p04_polynomial_regression.py +72 -0
- ml_practical/practicals/p05_lasso_ridge_regression.py +98 -0
- ml_practical/practicals/p06_logistic_regression.py +69 -0
- ml_practical/practicals/p07_artificial_neural_network.py +86 -0
- ml_practical/practicals/p08_knn_classifier.py +91 -0
- ml_practical/practicals/p09_decision_tree_classifier.py +84 -0
- ml_practical/practicals/p10_svm_classifier.py +80 -0
- ml_practical/practicals/p11_kmeans_clustering.py +106 -0
- ml_practical/practicals/p12_hierarchical_clustering.py +85 -0
- ml_practicals_kit-1.0.0.dist-info/METADATA +85 -0
- ml_practicals_kit-1.0.0.dist-info/RECORD +24 -0
- ml_practicals_kit-1.0.0.dist-info/WHEEL +5 -0
- ml_practicals_kit-1.0.0.dist-info/entry_points.txt +3 -0
- ml_practicals_kit-1.0.0.dist-info/top_level.txt +1 -0
ml_practical/__init__.py
ADDED
ml_practical/__main__.py
ADDED
ml_practical/cli.py
ADDED
|
@@ -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
|
ml_practical/desktop.py
ADDED
|
@@ -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
|
+
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Practical 1: Naive Bayes Classifier."""
|
|
2
|
+
|
|
3
|
+
from ml_practical.notebook_builder import NotebookBuilder
|
|
4
|
+
from ml_practical.practicals.base import (
|
|
5
|
+
PracticalSpec,
|
|
6
|
+
add_classification_split_and_helper,
|
|
7
|
+
add_header,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def build_notebook(roll_number: str) -> NotebookBuilder:
|
|
12
|
+
nb = NotebookBuilder(title="Practical 1: Naive Bayes Classifier")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=1,
|
|
16
|
+
title="Naïve Bayes Classifier",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Build and evaluate a Gaussian Naïve Bayes classifier on a public UCI dataset.",
|
|
19
|
+
dataset_info="Breast Cancer Wisconsin (Diagnostic) Dataset (UCI ML Repository / sklearn.datasets)",
|
|
20
|
+
metrics_info="Accuracy, TP, TN, FP, FN, Error Rate, Recall, Specificity, F1-score, AUC",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
nb.add_markdown("## 1. Import Libraries & Load Dataset")
|
|
24
|
+
nb.add_code(
|
|
25
|
+
"""
|
|
26
|
+
import numpy as np
|
|
27
|
+
import pandas as pd
|
|
28
|
+
import matplotlib.pyplot as plt
|
|
29
|
+
from sklearn.datasets import load_breast_cancer
|
|
30
|
+
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate
|
|
31
|
+
from sklearn.preprocessing import StandardScaler
|
|
32
|
+
from sklearn.pipeline import make_pipeline
|
|
33
|
+
from sklearn.naive_bayes import GaussianNB
|
|
34
|
+
from sklearn.metrics import (
|
|
35
|
+
accuracy_score, recall_score, f1_score, roc_auc_score,
|
|
36
|
+
confusion_matrix, ConfusionMatrixDisplay, roc_curve
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
data = load_breast_cancer(as_frame=True)
|
|
40
|
+
X = data.data
|
|
41
|
+
y = data.target
|
|
42
|
+
print("Dataset Shape:", X.shape)
|
|
43
|
+
print("Class Distribution:\\n", y.value_counts())
|
|
44
|
+
X.head()
|
|
45
|
+
"""
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
49
|
+
add_classification_split_and_helper(nb)
|
|
50
|
+
|
|
51
|
+
nb.add_markdown("## 3. Train & Evaluate Gaussian Naïve Bayes")
|
|
52
|
+
nb.add_code(
|
|
53
|
+
"""
|
|
54
|
+
nb_pipeline = make_pipeline(StandardScaler(), GaussianNB())
|
|
55
|
+
evaluate_classification_model(
|
|
56
|
+
nb_pipeline, X_train, X_test, y_train, y_test, X, y,
|
|
57
|
+
model_name="Gaussian Naive Bayes", cv_folds=5
|
|
58
|
+
)
|
|
59
|
+
"""
|
|
60
|
+
)
|
|
61
|
+
return nb
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
SPEC = PracticalSpec(
|
|
65
|
+
number=1,
|
|
66
|
+
slug="Naive_Bayes_Classifier",
|
|
67
|
+
title="Naïve Bayes Classifier",
|
|
68
|
+
category="Classification",
|
|
69
|
+
builder=build_notebook,
|
|
70
|
+
)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Practical 2: Simple Linear Regression."""
|
|
2
|
+
|
|
3
|
+
from ml_practical.notebook_builder import NotebookBuilder
|
|
4
|
+
from ml_practical.practicals.base import (
|
|
5
|
+
PracticalSpec,
|
|
6
|
+
add_header,
|
|
7
|
+
add_regression_split_and_helper,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def build_notebook(roll_number: str) -> NotebookBuilder:
|
|
12
|
+
nb = NotebookBuilder(title="Practical 2: Simple Linear Regression")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=2,
|
|
16
|
+
title="Simple Linear Regression",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Implement Simple Linear Regression using a single independent feature to predict a continuous target.",
|
|
19
|
+
dataset_info="Diabetes Dataset (UCI / sklearn.datasets) using BMI as the predictor",
|
|
20
|
+
metrics_info="MSE (Mean Squared Error) and R² Score",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
nb.add_markdown("## 1. Import Libraries & Load Dataset")
|
|
24
|
+
nb.add_code(
|
|
25
|
+
"""
|
|
26
|
+
import numpy as np
|
|
27
|
+
import pandas as pd
|
|
28
|
+
import matplotlib.pyplot as plt
|
|
29
|
+
from sklearn.datasets import load_diabetes
|
|
30
|
+
from sklearn.model_selection import train_test_split, KFold, cross_val_score
|
|
31
|
+
from sklearn.linear_model import LinearRegression
|
|
32
|
+
from sklearn.metrics import mean_squared_error, r2_score
|
|
33
|
+
|
|
34
|
+
data = load_diabetes(as_frame=True)
|
|
35
|
+
X = data.data[["bmi"]]
|
|
36
|
+
y = data.target
|
|
37
|
+
print("Feature Shape:", X.shape)
|
|
38
|
+
X.head()
|
|
39
|
+
"""
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
43
|
+
add_regression_split_and_helper(nb)
|
|
44
|
+
|
|
45
|
+
nb.add_markdown("## 3. Train & Evaluate Simple Linear Regression")
|
|
46
|
+
nb.add_code(
|
|
47
|
+
"""
|
|
48
|
+
model = LinearRegression()
|
|
49
|
+
evaluate_regression_model(
|
|
50
|
+
model, X_train, X_test, y_train, y_test, X, y,
|
|
51
|
+
model_name="Simple Linear Regression", cv_folds=5
|
|
52
|
+
)
|
|
53
|
+
print(f"Slope (Coefficient): {model.coef_[0]:.4f}")
|
|
54
|
+
print(f"Intercept : {model.intercept_:.4f}")
|
|
55
|
+
"""
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
nb.add_markdown("## 4. Regression Line Visualization")
|
|
59
|
+
nb.add_code(
|
|
60
|
+
"""
|
|
61
|
+
plt.figure(figsize=(7, 4.5))
|
|
62
|
+
plt.scatter(X_test, y_test, alpha=0.65, label="Test Data")
|
|
63
|
+
x_line = np.linspace(X_test.values.min(), X_test.values.max(), 100).reshape(-1, 1)
|
|
64
|
+
plt.plot(x_line, model.predict(pd.DataFrame(x_line, columns=["bmi"])), color="red", linewidth=2, label="Regression Line")
|
|
65
|
+
plt.xlabel("BMI (Normalized)")
|
|
66
|
+
plt.ylabel("Disease Progression")
|
|
67
|
+
plt.title("Simple Linear Regression Fit")
|
|
68
|
+
plt.legend()
|
|
69
|
+
plt.grid(alpha=0.3)
|
|
70
|
+
plt.show()
|
|
71
|
+
"""
|
|
72
|
+
)
|
|
73
|
+
return nb
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
SPEC = PracticalSpec(
|
|
77
|
+
number=2,
|
|
78
|
+
slug="Simple_Linear_Regression",
|
|
79
|
+
title="Simple Linear Regression",
|
|
80
|
+
category="Regression",
|
|
81
|
+
builder=build_notebook,
|
|
82
|
+
)
|