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
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Practical 3: Multiple 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 3: Multiple Linear Regression")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=3,
|
|
16
|
+
title="Multiple Linear Regression",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Build a Multiple Linear Regression model using multiple features and evaluate its performance.",
|
|
19
|
+
dataset_info="Diabetes Dataset (UCI / sklearn.datasets, all 10 physiological features)",
|
|
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.preprocessing import StandardScaler
|
|
32
|
+
from sklearn.pipeline import make_pipeline
|
|
33
|
+
from sklearn.linear_model import LinearRegression
|
|
34
|
+
from sklearn.metrics import mean_squared_error, r2_score
|
|
35
|
+
|
|
36
|
+
data = load_diabetes(as_frame=True)
|
|
37
|
+
X = data.data
|
|
38
|
+
y = data.target
|
|
39
|
+
print("Dataset Shape:", X.shape)
|
|
40
|
+
X.head()
|
|
41
|
+
"""
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
45
|
+
add_regression_split_and_helper(nb)
|
|
46
|
+
|
|
47
|
+
nb.add_markdown("## 3. Train & Evaluate Multiple Linear Regression")
|
|
48
|
+
nb.add_code(
|
|
49
|
+
"""
|
|
50
|
+
mlr_pipeline = make_pipeline(StandardScaler(), LinearRegression())
|
|
51
|
+
evaluate_regression_model(
|
|
52
|
+
mlr_pipeline, X_train, X_test, y_train, y_test, X, y,
|
|
53
|
+
model_name="Multiple Linear Regression", cv_folds=5
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
lr = mlr_pipeline.named_steps["linearregression"]
|
|
57
|
+
coef_df = pd.DataFrame({"Feature": X.columns, "Coefficient": lr.coef_}).sort_values("Coefficient", key=abs, ascending=False)
|
|
58
|
+
print("\\nFeature Coefficients:")
|
|
59
|
+
print(coef_df.to_string(index=False))
|
|
60
|
+
"""
|
|
61
|
+
)
|
|
62
|
+
return nb
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
SPEC = PracticalSpec(
|
|
66
|
+
number=3,
|
|
67
|
+
slug="Multiple_Linear_Regression",
|
|
68
|
+
title="Multiple Linear Regression",
|
|
69
|
+
category="Regression",
|
|
70
|
+
builder=build_notebook,
|
|
71
|
+
)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Practical 4: Polynomial 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 4: Polynomial Regression")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=4,
|
|
16
|
+
title="Polynomial Regression",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Model non-linear relationships using Polynomial Regression and compare polynomial degrees.",
|
|
19
|
+
dataset_info="Diabetes Dataset (UCI / sklearn.datasets) with Polynomial Feature Expansion",
|
|
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.preprocessing import PolynomialFeatures, StandardScaler
|
|
32
|
+
from sklearn.pipeline import make_pipeline
|
|
33
|
+
from sklearn.linear_model import LinearRegression
|
|
34
|
+
from sklearn.metrics import mean_squared_error, r2_score
|
|
35
|
+
|
|
36
|
+
data = load_diabetes(as_frame=True)
|
|
37
|
+
X = data.data[["bmi", "bp", "s5"]]
|
|
38
|
+
y = data.target
|
|
39
|
+
print("Dataset Shape:", X.shape)
|
|
40
|
+
X.head()
|
|
41
|
+
"""
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
45
|
+
add_regression_split_and_helper(nb)
|
|
46
|
+
|
|
47
|
+
nb.add_markdown("## 3. Compare Polynomial Degrees & Evaluate Degree 2 Model")
|
|
48
|
+
nb.add_code(
|
|
49
|
+
"""
|
|
50
|
+
for deg in [1, 2, 3]:
|
|
51
|
+
pipe = make_pipeline(PolynomialFeatures(degree=deg, include_bias=False), StandardScaler(), LinearRegression())
|
|
52
|
+
pipe.fit(X_train, y_train)
|
|
53
|
+
preds = pipe.predict(X_test)
|
|
54
|
+
print(f"Degree {deg} -> Test MSE: {mean_squared_error(y_test, preds):.4f}, Test R2: {r2_score(y_test, preds):.4f}")
|
|
55
|
+
|
|
56
|
+
best_poly = make_pipeline(PolynomialFeatures(degree=2, include_bias=False), StandardScaler(), LinearRegression())
|
|
57
|
+
evaluate_regression_model(
|
|
58
|
+
best_poly, X_train, X_test, y_train, y_test, X, y,
|
|
59
|
+
model_name="Polynomial Regression (Degree=2)", cv_folds=5
|
|
60
|
+
)
|
|
61
|
+
"""
|
|
62
|
+
)
|
|
63
|
+
return nb
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
SPEC = PracticalSpec(
|
|
67
|
+
number=4,
|
|
68
|
+
slug="Polynomial_Regression",
|
|
69
|
+
title="Polynomial Regression",
|
|
70
|
+
category="Regression",
|
|
71
|
+
builder=build_notebook,
|
|
72
|
+
)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Practical 5: Lasso and Ridge 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 5: Lasso and Ridge Regression")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=5,
|
|
16
|
+
title="Lasso and Ridge Regression",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Apply L1 (Lasso) and L2 (Ridge) regularization to prevent overfitting and compare their performance.",
|
|
19
|
+
dataset_info="Diabetes Dataset (UCI / sklearn.datasets, 10 features)",
|
|
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.preprocessing import StandardScaler
|
|
32
|
+
from sklearn.pipeline import make_pipeline
|
|
33
|
+
from sklearn.linear_model import Lasso, Ridge
|
|
34
|
+
from sklearn.metrics import mean_squared_error, r2_score
|
|
35
|
+
|
|
36
|
+
data = load_diabetes(as_frame=True)
|
|
37
|
+
X = data.data
|
|
38
|
+
y = data.target
|
|
39
|
+
print("Dataset Shape:", X.shape)
|
|
40
|
+
X.head()
|
|
41
|
+
"""
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
45
|
+
add_regression_split_and_helper(nb)
|
|
46
|
+
|
|
47
|
+
nb.add_markdown("## 3. Train & Evaluate Ridge Regression (L2)")
|
|
48
|
+
nb.add_code(
|
|
49
|
+
"""
|
|
50
|
+
ridge_pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
|
|
51
|
+
evaluate_regression_model(
|
|
52
|
+
ridge_pipe, X_train, X_test, y_train, y_test, X, y,
|
|
53
|
+
model_name="Ridge Regression (alpha=1.0)", cv_folds=5
|
|
54
|
+
)
|
|
55
|
+
"""
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
nb.add_markdown("## 4. Train & Evaluate Lasso Regression (L1)")
|
|
59
|
+
nb.add_code(
|
|
60
|
+
"""
|
|
61
|
+
lasso_pipe = make_pipeline(StandardScaler(), Lasso(alpha=1.0, max_iter=5000))
|
|
62
|
+
evaluate_regression_model(
|
|
63
|
+
lasso_pipe, X_train, X_test, y_train, y_test, X, y,
|
|
64
|
+
model_name="Lasso Regression (alpha=1.0)", cv_folds=5
|
|
65
|
+
)
|
|
66
|
+
"""
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
nb.add_markdown("## 5. Coefficient Comparison (Ridge vs Lasso)")
|
|
70
|
+
nb.add_code(
|
|
71
|
+
"""
|
|
72
|
+
ridge_coef = ridge_pipe.named_steps["ridge"].coef_
|
|
73
|
+
lasso_coef = lasso_pipe.named_steps["lasso"].coef_
|
|
74
|
+
|
|
75
|
+
x_pos = np.arange(len(X.columns))
|
|
76
|
+
plt.figure(figsize=(9, 4.5))
|
|
77
|
+
plt.bar(x_pos - 0.18, ridge_coef, width=0.36, label="Ridge (L2)")
|
|
78
|
+
plt.bar(x_pos + 0.18, lasso_coef, width=0.36, label="Lasso (L1)")
|
|
79
|
+
plt.xticks(x_pos, X.columns, rotation=30)
|
|
80
|
+
plt.axhline(0, color="black", linewidth=0.8)
|
|
81
|
+
plt.ylabel("Coefficient Magnitude")
|
|
82
|
+
plt.title("Ridge vs Lasso Feature Coefficients")
|
|
83
|
+
plt.legend()
|
|
84
|
+
plt.grid(axis="y", alpha=0.3)
|
|
85
|
+
plt.tight_layout()
|
|
86
|
+
plt.show()
|
|
87
|
+
"""
|
|
88
|
+
)
|
|
89
|
+
return nb
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
SPEC = PracticalSpec(
|
|
93
|
+
number=5,
|
|
94
|
+
slug="Lasso_and_Ridge_Regression",
|
|
95
|
+
title="Lasso and Ridge Regression",
|
|
96
|
+
category="Regression",
|
|
97
|
+
builder=build_notebook,
|
|
98
|
+
)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Practical 6: Logistic Regression."""
|
|
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 6: Logistic Regression")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=6,
|
|
16
|
+
title="Logistic Regression",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Build and evaluate a Logistic Regression binary classification model.",
|
|
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.linear_model import LogisticRegression
|
|
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
|
+
X.head()
|
|
44
|
+
"""
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
48
|
+
add_classification_split_and_helper(nb)
|
|
49
|
+
|
|
50
|
+
nb.add_markdown("## 3. Train & Evaluate Logistic Regression")
|
|
51
|
+
nb.add_code(
|
|
52
|
+
"""
|
|
53
|
+
log_reg_pipeline = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000, random_state=42))
|
|
54
|
+
evaluate_classification_model(
|
|
55
|
+
log_reg_pipeline, X_train, X_test, y_train, y_test, X, y,
|
|
56
|
+
model_name="Logistic Regression", cv_folds=5
|
|
57
|
+
)
|
|
58
|
+
"""
|
|
59
|
+
)
|
|
60
|
+
return nb
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
SPEC = PracticalSpec(
|
|
64
|
+
number=6,
|
|
65
|
+
slug="Logistic_Regression",
|
|
66
|
+
title="Logistic Regression",
|
|
67
|
+
category="Classification",
|
|
68
|
+
builder=build_notebook,
|
|
69
|
+
)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Practical 7: Artificial Neural Network."""
|
|
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 7: Artificial Neural Network")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=7,
|
|
16
|
+
title="Artificial Neural Network",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Train and evaluate a Multi-Layer Perceptron (Artificial Neural Network) classifier.",
|
|
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.neural_network import MLPClassifier
|
|
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
|
+
X.head()
|
|
44
|
+
"""
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
48
|
+
add_classification_split_and_helper(nb)
|
|
49
|
+
|
|
50
|
+
nb.add_markdown("## 3. Train & Evaluate Artificial Neural Network (MLP)")
|
|
51
|
+
nb.add_code(
|
|
52
|
+
"""
|
|
53
|
+
ann_pipeline = make_pipeline(
|
|
54
|
+
StandardScaler(),
|
|
55
|
+
MLPClassifier(hidden_layer_sizes=(64, 32), activation="relu", max_iter=500, random_state=42)
|
|
56
|
+
)
|
|
57
|
+
evaluate_classification_model(
|
|
58
|
+
ann_pipeline, X_train, X_test, y_train, y_test, X, y,
|
|
59
|
+
model_name="Artificial Neural Network (MLP)", cv_folds=5
|
|
60
|
+
)
|
|
61
|
+
"""
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
nb.add_markdown("## 4. Training Loss Curve")
|
|
65
|
+
nb.add_code(
|
|
66
|
+
"""
|
|
67
|
+
mlp = ann_pipeline.named_steps["mlpclassifier"]
|
|
68
|
+
plt.figure(figsize=(7, 4))
|
|
69
|
+
plt.plot(mlp.loss_curve_, linewidth=2)
|
|
70
|
+
plt.xlabel("Iteration")
|
|
71
|
+
plt.ylabel("Loss")
|
|
72
|
+
plt.title("ANN Training Loss Curve")
|
|
73
|
+
plt.grid(alpha=0.3)
|
|
74
|
+
plt.show()
|
|
75
|
+
"""
|
|
76
|
+
)
|
|
77
|
+
return nb
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
SPEC = PracticalSpec(
|
|
81
|
+
number=7,
|
|
82
|
+
slug="Artificial_Neural_Network",
|
|
83
|
+
title="Artificial Neural Network",
|
|
84
|
+
category="Classification",
|
|
85
|
+
builder=build_notebook,
|
|
86
|
+
)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Practical 8: K-NN 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 8: K-NN Classifier")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=8,
|
|
16
|
+
title="K-NN Classifier",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Implement a K-Nearest Neighbors (K-NN) classifier and tune K using cross-validation.",
|
|
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, cross_val_score
|
|
31
|
+
from sklearn.preprocessing import StandardScaler
|
|
32
|
+
from sklearn.pipeline import make_pipeline
|
|
33
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
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
|
+
X.head()
|
|
44
|
+
"""
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
48
|
+
add_classification_split_and_helper(nb)
|
|
49
|
+
|
|
50
|
+
nb.add_markdown("## 3. Find Optimal K via 5-Fold Cross-Validation")
|
|
51
|
+
nb.add_code(
|
|
52
|
+
"""
|
|
53
|
+
k_values = range(1, 21)
|
|
54
|
+
cv_scores = [
|
|
55
|
+
cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k)), X_train, y_train, cv=5).mean()
|
|
56
|
+
for k in k_values
|
|
57
|
+
]
|
|
58
|
+
best_k = k_values[int(np.argmax(cv_scores))]
|
|
59
|
+
print(f"Optimal K: {best_k} (CV Accuracy: {max(cv_scores):.4f})")
|
|
60
|
+
|
|
61
|
+
plt.figure(figsize=(7, 4))
|
|
62
|
+
plt.plot(k_values, cv_scores, marker="o")
|
|
63
|
+
plt.xlabel("Number of Neighbors (K)")
|
|
64
|
+
plt.ylabel("5-Fold CV Accuracy")
|
|
65
|
+
plt.title("K-NN Hyperparameter Tuning")
|
|
66
|
+
plt.xticks(list(k_values))
|
|
67
|
+
plt.grid(alpha=0.3)
|
|
68
|
+
plt.show()
|
|
69
|
+
"""
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
nb.add_markdown("## 4. Train & Evaluate K-NN Classifier")
|
|
73
|
+
nb.add_code(
|
|
74
|
+
"""
|
|
75
|
+
knn_pipeline = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=best_k))
|
|
76
|
+
evaluate_classification_model(
|
|
77
|
+
knn_pipeline, X_train, X_test, y_train, y_test, X, y,
|
|
78
|
+
model_name=f"K-NN Classifier (K={best_k})", cv_folds=5
|
|
79
|
+
)
|
|
80
|
+
"""
|
|
81
|
+
)
|
|
82
|
+
return nb
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
SPEC = PracticalSpec(
|
|
86
|
+
number=8,
|
|
87
|
+
slug="KNN_Classifier",
|
|
88
|
+
title="K-NN Classifier",
|
|
89
|
+
category="Classification",
|
|
90
|
+
builder=build_notebook,
|
|
91
|
+
)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Practical 9: Decision Tree Classification."""
|
|
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 9: Decision Tree Classification")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=9,
|
|
16
|
+
title="Decision Tree Classification",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Build, visualize, and evaluate a Decision Tree Classifier.",
|
|
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.tree import DecisionTreeClassifier, plot_tree
|
|
32
|
+
from sklearn.metrics import (
|
|
33
|
+
accuracy_score, recall_score, f1_score, roc_auc_score,
|
|
34
|
+
confusion_matrix, ConfusionMatrixDisplay, roc_curve
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
data = load_breast_cancer(as_frame=True)
|
|
38
|
+
X = data.data
|
|
39
|
+
y = data.target
|
|
40
|
+
print("Dataset Shape:", X.shape)
|
|
41
|
+
X.head()
|
|
42
|
+
"""
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
46
|
+
add_classification_split_and_helper(nb)
|
|
47
|
+
|
|
48
|
+
nb.add_markdown("## 3. Train & Evaluate Decision Tree Classifier")
|
|
49
|
+
nb.add_code(
|
|
50
|
+
"""
|
|
51
|
+
dt_model = DecisionTreeClassifier(criterion="gini", max_depth=4, random_state=42)
|
|
52
|
+
evaluate_classification_model(
|
|
53
|
+
dt_model, X_train, X_test, y_train, y_test, X, y,
|
|
54
|
+
model_name="Decision Tree Classifier (max_depth=4)", cv_folds=5
|
|
55
|
+
)
|
|
56
|
+
"""
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
nb.add_markdown("## 4. Decision Tree Structure Visualization")
|
|
60
|
+
nb.add_code(
|
|
61
|
+
"""
|
|
62
|
+
plt.figure(figsize=(16, 8))
|
|
63
|
+
plot_tree(
|
|
64
|
+
dt_model,
|
|
65
|
+
feature_names=X.columns,
|
|
66
|
+
class_names=data.target_names,
|
|
67
|
+
filled=True,
|
|
68
|
+
rounded=True,
|
|
69
|
+
fontsize=8
|
|
70
|
+
)
|
|
71
|
+
plt.title("Decision Tree Visualization")
|
|
72
|
+
plt.show()
|
|
73
|
+
"""
|
|
74
|
+
)
|
|
75
|
+
return nb
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
SPEC = PracticalSpec(
|
|
79
|
+
number=9,
|
|
80
|
+
slug="Decision_Tree_Classification",
|
|
81
|
+
title="Decision Tree Classification",
|
|
82
|
+
category="Classification",
|
|
83
|
+
builder=build_notebook,
|
|
84
|
+
)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Practical 10: SVM Classification."""
|
|
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 10: SVM Classification")
|
|
13
|
+
add_header(
|
|
14
|
+
nb,
|
|
15
|
+
number=10,
|
|
16
|
+
title="SVM Classification",
|
|
17
|
+
roll_number=roll_number,
|
|
18
|
+
aim="Train and evaluate Support Vector Machine (SVM) classifiers with Linear and RBF kernels.",
|
|
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.svm import SVC
|
|
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
|
+
X.head()
|
|
44
|
+
"""
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
nb.add_markdown("## 2. Train-Test Split & Evaluation Helper")
|
|
48
|
+
add_classification_split_and_helper(nb)
|
|
49
|
+
|
|
50
|
+
nb.add_markdown("## 3. Train & Evaluate SVM (RBF Kernel)")
|
|
51
|
+
nb.add_code(
|
|
52
|
+
"""
|
|
53
|
+
svm_rbf = make_pipeline(StandardScaler(), SVC(kernel="rbf", C=1.0, probability=True, random_state=42))
|
|
54
|
+
evaluate_classification_model(
|
|
55
|
+
svm_rbf, X_train, X_test, y_train, y_test, X, y,
|
|
56
|
+
model_name="SVM (RBF Kernel)", cv_folds=5
|
|
57
|
+
)
|
|
58
|
+
"""
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
nb.add_markdown("## 4. Train & Evaluate SVM (Linear Kernel)")
|
|
62
|
+
nb.add_code(
|
|
63
|
+
"""
|
|
64
|
+
svm_linear = make_pipeline(StandardScaler(), SVC(kernel="linear", C=1.0, probability=True, random_state=42))
|
|
65
|
+
evaluate_classification_model(
|
|
66
|
+
svm_linear, X_train, X_test, y_train, y_test, X, y,
|
|
67
|
+
model_name="SVM (Linear Kernel)", cv_folds=5
|
|
68
|
+
)
|
|
69
|
+
"""
|
|
70
|
+
)
|
|
71
|
+
return nb
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
SPEC = PracticalSpec(
|
|
75
|
+
number=10,
|
|
76
|
+
slug="SVM_Classification",
|
|
77
|
+
title="SVM Classification",
|
|
78
|
+
category="Classification",
|
|
79
|
+
builder=build_notebook,
|
|
80
|
+
)
|