du-ml-practicals 0.1.1__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 (24) hide show
  1. du_ml_practicals-0.1.1/PKG-INFO +34 -0
  2. du_ml_practicals-0.1.1/README.md +22 -0
  3. du_ml_practicals-0.1.1/pyproject.toml +23 -0
  4. du_ml_practicals-0.1.1/setup.cfg +4 -0
  5. du_ml_practicals-0.1.1/src/du_ml_practicals.egg-info/PKG-INFO +34 -0
  6. du_ml_practicals-0.1.1/src/du_ml_practicals.egg-info/SOURCES.txt +22 -0
  7. du_ml_practicals-0.1.1/src/du_ml_practicals.egg-info/dependency_links.txt +1 -0
  8. du_ml_practicals-0.1.1/src/du_ml_practicals.egg-info/entry_points.txt +2 -0
  9. du_ml_practicals-0.1.1/src/du_ml_practicals.egg-info/requires.txt +6 -0
  10. du_ml_practicals-0.1.1/src/du_ml_practicals.egg-info/top_level.txt +1 -0
  11. du_ml_practicals-0.1.1/src/ml_practicals/__init__.py +0 -0
  12. du_ml_practicals-0.1.1/src/ml_practicals/__main__.py +61 -0
  13. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_01.txt +31 -0
  14. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_02.txt +24 -0
  15. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_03.txt +24 -0
  16. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_04.txt +26 -0
  17. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_05.txt +31 -0
  18. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_06.txt +33 -0
  19. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_07.txt +35 -0
  20. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_08.txt +34 -0
  21. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_09.txt +31 -0
  22. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_10.txt +36 -0
  23. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_11.txt +17 -0
  24. du_ml_practicals-0.1.1/src/ml_practicals/solutions/practical_12.txt +17 -0
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: du-ml-practicals
3
+ Version: 0.1.1
4
+ Summary: Export twelve machine learning practicals as Python scripts
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Provides-Extra: run
8
+ Requires-Dist: numpy; extra == "run"
9
+ Requires-Dist: scipy; extra == "run"
10
+ Requires-Dist: scikit-learn; extra == "run"
11
+ Requires-Dist: matplotlib; extra == "run"
12
+
13
+ # ML Practicals
14
+
15
+ Export any of the 12 machine learning practicals as a standalone Python script.
16
+ Python 3.10 or newer is required for the menu.
17
+
18
+ From the project directory, install the menu with `py -m pip install .`.
19
+ Then open PowerShell in the folder where you want your answers and run
20
+ `ml-practicals` or `py -m ml_practicals`. Choose 1–12 to create the matching
21
+ file, such as `q1.py`. Move or rename an existing answer to export a fresh
22
+ copy. Enter 0 to exit.
23
+
24
+ To run the exported scripts, install their libraries once using
25
+ `py -m pip install numpy scipy scikit-learn matplotlib`. You can also install
26
+ the menu and these libraries together from the project directory with
27
+ `py -m pip install ".[run]"`.
28
+
29
+ Run an exported script with `py q1.py`. All 12 answers use the Iris dataset
30
+ bundled with scikit-learn. For Q8, enter `5` at the neighbors prompt to try
31
+ the example. Q11 and Q12 open a plot window.
32
+
33
+ The exported answers match the Word answer sheet in `course-materials/`.
34
+ The Word document is available in the project folder.
@@ -0,0 +1,22 @@
1
+ # ML Practicals
2
+
3
+ Export any of the 12 machine learning practicals as a standalone Python script.
4
+ Python 3.10 or newer is required for the menu.
5
+
6
+ From the project directory, install the menu with `py -m pip install .`.
7
+ Then open PowerShell in the folder where you want your answers and run
8
+ `ml-practicals` or `py -m ml_practicals`. Choose 1–12 to create the matching
9
+ file, such as `q1.py`. Move or rename an existing answer to export a fresh
10
+ copy. Enter 0 to exit.
11
+
12
+ To run the exported scripts, install their libraries once using
13
+ `py -m pip install numpy scipy scikit-learn matplotlib`. You can also install
14
+ the menu and these libraries together from the project directory with
15
+ `py -m pip install ".[run]"`.
16
+
17
+ Run an exported script with `py q1.py`. All 12 answers use the Iris dataset
18
+ bundled with scikit-learn. For Q8, enter `5` at the neighbors prompt to try
19
+ the example. Q11 and Q12 open a plot window.
20
+
21
+ The exported answers match the Word answer sheet in `course-materials/`.
22
+ The Word document is available in the project folder.
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "du-ml-practicals"
7
+ version = "0.1.1"
8
+ description = "Export twelve machine learning practicals as Python scripts"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+
12
+ [project.optional-dependencies]
13
+ run = ["numpy", "scipy", "scikit-learn", "matplotlib"]
14
+
15
+ [project.scripts]
16
+ ml-practicals = "ml_practicals.__main__:main"
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["src"]
20
+ namespaces = false
21
+
22
+ [tool.setuptools.package-data]
23
+ ml_practicals = ["solutions/*.txt"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: du-ml-practicals
3
+ Version: 0.1.1
4
+ Summary: Export twelve machine learning practicals as Python scripts
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Provides-Extra: run
8
+ Requires-Dist: numpy; extra == "run"
9
+ Requires-Dist: scipy; extra == "run"
10
+ Requires-Dist: scikit-learn; extra == "run"
11
+ Requires-Dist: matplotlib; extra == "run"
12
+
13
+ # ML Practicals
14
+
15
+ Export any of the 12 machine learning practicals as a standalone Python script.
16
+ Python 3.10 or newer is required for the menu.
17
+
18
+ From the project directory, install the menu with `py -m pip install .`.
19
+ Then open PowerShell in the folder where you want your answers and run
20
+ `ml-practicals` or `py -m ml_practicals`. Choose 1–12 to create the matching
21
+ file, such as `q1.py`. Move or rename an existing answer to export a fresh
22
+ copy. Enter 0 to exit.
23
+
24
+ To run the exported scripts, install their libraries once using
25
+ `py -m pip install numpy scipy scikit-learn matplotlib`. You can also install
26
+ the menu and these libraries together from the project directory with
27
+ `py -m pip install ".[run]"`.
28
+
29
+ Run an exported script with `py q1.py`. All 12 answers use the Iris dataset
30
+ bundled with scikit-learn. For Q8, enter `5` at the neighbors prompt to try
31
+ the example. Q11 and Q12 open a plot window.
32
+
33
+ The exported answers match the Word answer sheet in `course-materials/`.
34
+ The Word document is available in the project folder.
@@ -0,0 +1,22 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/du_ml_practicals.egg-info/PKG-INFO
4
+ src/du_ml_practicals.egg-info/SOURCES.txt
5
+ src/du_ml_practicals.egg-info/dependency_links.txt
6
+ src/du_ml_practicals.egg-info/entry_points.txt
7
+ src/du_ml_practicals.egg-info/requires.txt
8
+ src/du_ml_practicals.egg-info/top_level.txt
9
+ src/ml_practicals/__init__.py
10
+ src/ml_practicals/__main__.py
11
+ src/ml_practicals/solutions/practical_01.txt
12
+ src/ml_practicals/solutions/practical_02.txt
13
+ src/ml_practicals/solutions/practical_03.txt
14
+ src/ml_practicals/solutions/practical_04.txt
15
+ src/ml_practicals/solutions/practical_05.txt
16
+ src/ml_practicals/solutions/practical_06.txt
17
+ src/ml_practicals/solutions/practical_07.txt
18
+ src/ml_practicals/solutions/practical_08.txt
19
+ src/ml_practicals/solutions/practical_09.txt
20
+ src/ml_practicals/solutions/practical_10.txt
21
+ src/ml_practicals/solutions/practical_11.txt
22
+ src/ml_practicals/solutions/practical_12.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ml-practicals = ml_practicals.__main__:main
@@ -0,0 +1,6 @@
1
+
2
+ [run]
3
+ numpy
4
+ scipy
5
+ scikit-learn
6
+ matplotlib
File without changes
@@ -0,0 +1,61 @@
1
+ from importlib.resources import files
2
+ from pathlib import Path
3
+ import sys
4
+
5
+
6
+ PRACTICALS = (
7
+ "Naive Bayes Classifier",
8
+ "Simple Linear Regression",
9
+ "Multiple Linear Regression",
10
+ "Polynomial Regression",
11
+ "Lasso and Ridge Regression",
12
+ "Logistic Regression",
13
+ "Artificial Neural Network",
14
+ "K-NN Classifier",
15
+ "Decision Tree Classification",
16
+ "SVM Classification",
17
+ "K-Means Clustering",
18
+ "Hierarchical Clustering",
19
+ )
20
+
21
+
22
+ def export_solution(number, directory):
23
+ destination = directory / f"q{number}.py"
24
+ source = files("ml_practicals").joinpath("solutions", f"practical_{number:02d}.txt")
25
+ try:
26
+ content = source.read_bytes()
27
+ with destination.open("xb") as output:
28
+ output.write(content)
29
+ except FileExistsError:
30
+ print(f"{destination.name} already exists. Move or rename it to export a fresh copy.")
31
+ except OSError as error:
32
+ print(f"Could not create {destination.name}: {error}", file=sys.stderr)
33
+ else:
34
+ print(f"Created {destination}")
35
+
36
+
37
+ def main():
38
+ directory = Path.cwd()
39
+ questions = {str(number): number for number in range(1, len(PRACTICALS) + 1)}
40
+ print("Machine Learning Practicals")
41
+ print(f"Output folder: {directory}\n")
42
+ for number, title in enumerate(PRACTICALS, start=1):
43
+ print(f"{number}. {title}")
44
+ print("0. Exit")
45
+
46
+ while True:
47
+ try:
48
+ choice = input(f"\nChoose a question (1-{len(PRACTICALS)}), or 0 to exit: ").strip()
49
+ except (EOFError, KeyboardInterrupt):
50
+ print()
51
+ return
52
+ if choice == "0":
53
+ return
54
+ if choice in questions:
55
+ export_solution(questions[choice], directory)
56
+ else:
57
+ print(f"Enter a number from 1 to {len(PRACTICALS)}, or 0 to exit.")
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
@@ -0,0 +1,31 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.model_selection import train_test_split, cross_val_score
3
+ from sklearn.metrics import (
4
+ accuracy_score, confusion_matrix, recall_score, f1_score, roc_auc_score
5
+ )
6
+ from sklearn.naive_bayes import GaussianNB
7
+
8
+ X, y = load_iris(return_X_y=True)
9
+ X_train, X_test, y_train, y_test = train_test_split(
10
+ X, y, test_size=0.2, random_state=42, stratify=y
11
+ )
12
+ model = GaussianNB()
13
+ model.fit(X_train, y_train)
14
+ predictions = model.predict(X_test)
15
+
16
+ matrix = confusion_matrix(y_test, predictions)
17
+ tp = matrix.diagonal()
18
+ fp = matrix.sum(axis=0) - tp
19
+ fn = matrix.sum(axis=1) - tp
20
+ tn = matrix.sum() - tp - fp - fn
21
+
22
+ accuracy = accuracy_score(y_test, predictions)
23
+ print("TP, TN, FP, FN (by class):", tp, tn, fp, fn)
24
+ print("Accuracy:", accuracy)
25
+ print("Error:", 1 - accuracy)
26
+ print("Recall:", recall_score(y_test, predictions, average="macro"))
27
+ print("Specificity:", (tn / (tn + fp)).mean())
28
+ print("F1:", f1_score(y_test, predictions, average="macro"))
29
+ auc = roc_auc_score(y_test, model.predict_proba(X_test), multi_class="ovr")
30
+ print("AUC:", auc)
31
+ print("5-fold CV accuracy:", cross_val_score(model, X_train, y_train, cv=5).mean())
@@ -0,0 +1,24 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.metrics import mean_squared_error, r2_score
3
+ from sklearn.model_selection import KFold, cross_validate, train_test_split
4
+ from sklearn.linear_model import LinearRegression
5
+
6
+ iris = load_iris()
7
+ X = iris.data[:, [2]]
8
+ y = iris.data[:, 3] # Predict petal width.
9
+ X_train, X_test, y_train, y_test = train_test_split(
10
+ X, y, test_size=0.2, random_state=42
11
+ )
12
+ folds = KFold(n_splits=5, shuffle=True, random_state=42)
13
+
14
+ model = LinearRegression()
15
+ model.fit(X_train, y_train)
16
+ predictions = model.predict(X_test)
17
+ print("Test MSE:", mean_squared_error(y_test, predictions))
18
+ print("Test R2:", r2_score(y_test, predictions))
19
+
20
+ scores = cross_validate(
21
+ model, X_train, y_train, cv=folds, scoring=("neg_mean_squared_error", "r2")
22
+ )
23
+ print("5-fold CV MSE:", -scores["test_neg_mean_squared_error"].mean())
24
+ print("5-fold CV R2:", scores["test_r2"].mean())
@@ -0,0 +1,24 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.metrics import mean_squared_error, r2_score
3
+ from sklearn.model_selection import KFold, cross_validate, train_test_split
4
+ from sklearn.linear_model import LinearRegression
5
+
6
+ iris = load_iris()
7
+ X = iris.data[:, :3]
8
+ y = iris.data[:, 3] # Predict petal width.
9
+ X_train, X_test, y_train, y_test = train_test_split(
10
+ X, y, test_size=0.2, random_state=42
11
+ )
12
+ folds = KFold(n_splits=5, shuffle=True, random_state=42)
13
+
14
+ model = LinearRegression()
15
+ model.fit(X_train, y_train)
16
+ predictions = model.predict(X_test)
17
+ print("Test MSE:", mean_squared_error(y_test, predictions))
18
+ print("Test R2:", r2_score(y_test, predictions))
19
+
20
+ scores = cross_validate(
21
+ model, X_train, y_train, cv=folds, scoring=("neg_mean_squared_error", "r2")
22
+ )
23
+ print("5-fold CV MSE:", -scores["test_neg_mean_squared_error"].mean())
24
+ print("5-fold CV R2:", scores["test_r2"].mean())
@@ -0,0 +1,26 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.metrics import mean_squared_error, r2_score
3
+ from sklearn.model_selection import KFold, cross_validate, train_test_split
4
+ from sklearn.linear_model import LinearRegression
5
+ from sklearn.pipeline import make_pipeline
6
+ from sklearn.preprocessing import PolynomialFeatures
7
+
8
+ iris = load_iris()
9
+ X = iris.data[:, [2]]
10
+ y = iris.data[:, 3] # Predict petal width.
11
+ X_train, X_test, y_train, y_test = train_test_split(
12
+ X, y, test_size=0.2, random_state=42
13
+ )
14
+ folds = KFold(n_splits=5, shuffle=True, random_state=42)
15
+
16
+ model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())
17
+ model.fit(X_train, y_train)
18
+ predictions = model.predict(X_test)
19
+ print("Test MSE:", mean_squared_error(y_test, predictions))
20
+ print("Test R2:", r2_score(y_test, predictions))
21
+
22
+ scores = cross_validate(
23
+ model, X_train, y_train, cv=folds, scoring=("neg_mean_squared_error", "r2")
24
+ )
25
+ print("5-fold CV MSE:", -scores["test_neg_mean_squared_error"].mean())
26
+ print("5-fold CV R2:", scores["test_r2"].mean())
@@ -0,0 +1,31 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.metrics import mean_squared_error, r2_score
3
+ from sklearn.model_selection import KFold, cross_validate, train_test_split
4
+ from sklearn.linear_model import Lasso, Ridge
5
+ from sklearn.pipeline import make_pipeline
6
+ from sklearn.preprocessing import StandardScaler
7
+
8
+ iris = load_iris()
9
+ X = iris.data[:, :3]
10
+ y = iris.data[:, 3] # Predict petal width.
11
+ X_train, X_test, y_train, y_test = train_test_split(
12
+ X, y, test_size=0.2, random_state=42
13
+ )
14
+ folds = KFold(n_splits=5, shuffle=True, random_state=42)
15
+
16
+ models = {
17
+ "Lasso": make_pipeline(StandardScaler(), Lasso(alpha=0.05)),
18
+ "Ridge": make_pipeline(StandardScaler(), Ridge(alpha=1.0)),
19
+ }
20
+ for name, model in models.items():
21
+ print(name)
22
+ model.fit(X_train, y_train)
23
+ predictions = model.predict(X_test)
24
+ print("Test MSE:", mean_squared_error(y_test, predictions))
25
+ print("Test R2:", r2_score(y_test, predictions))
26
+
27
+ scores = cross_validate(
28
+ model, X_train, y_train, cv=folds, scoring=("neg_mean_squared_error", "r2")
29
+ )
30
+ print("5-fold CV MSE:", -scores["test_neg_mean_squared_error"].mean())
31
+ print("5-fold CV R2:", scores["test_r2"].mean())
@@ -0,0 +1,33 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.model_selection import train_test_split, cross_val_score
3
+ from sklearn.metrics import (
4
+ accuracy_score, confusion_matrix, recall_score, f1_score, roc_auc_score
5
+ )
6
+ from sklearn.linear_model import LogisticRegression
7
+ from sklearn.pipeline import make_pipeline
8
+ from sklearn.preprocessing import StandardScaler
9
+
10
+ X, y = load_iris(return_X_y=True)
11
+ X_train, X_test, y_train, y_test = train_test_split(
12
+ X, y, test_size=0.2, random_state=42, stratify=y
13
+ )
14
+ model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
15
+ model.fit(X_train, y_train)
16
+ predictions = model.predict(X_test)
17
+
18
+ matrix = confusion_matrix(y_test, predictions)
19
+ tp = matrix.diagonal()
20
+ fp = matrix.sum(axis=0) - tp
21
+ fn = matrix.sum(axis=1) - tp
22
+ tn = matrix.sum() - tp - fp - fn
23
+
24
+ accuracy = accuracy_score(y_test, predictions)
25
+ print("TP, TN, FP, FN (by class):", tp, tn, fp, fn)
26
+ print("Accuracy:", accuracy)
27
+ print("Error:", 1 - accuracy)
28
+ print("Recall:", recall_score(y_test, predictions, average="macro"))
29
+ print("Specificity:", (tn / (tn + fp)).mean())
30
+ print("F1:", f1_score(y_test, predictions, average="macro"))
31
+ auc = roc_auc_score(y_test, model.predict_proba(X_test), multi_class="ovr")
32
+ print("AUC:", auc)
33
+ print("5-fold CV accuracy:", cross_val_score(model, X_train, y_train, cv=5).mean())
@@ -0,0 +1,35 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.model_selection import train_test_split, cross_val_score
3
+ from sklearn.metrics import (
4
+ accuracy_score, confusion_matrix, recall_score, f1_score, roc_auc_score
5
+ )
6
+ from sklearn.neural_network import MLPClassifier
7
+ from sklearn.pipeline import make_pipeline
8
+ from sklearn.preprocessing import StandardScaler
9
+
10
+ X, y = load_iris(return_X_y=True)
11
+ X_train, X_test, y_train, y_test = train_test_split(
12
+ X, y, test_size=0.2, random_state=42, stratify=y
13
+ )
14
+ model = make_pipeline(StandardScaler(), MLPClassifier(
15
+ hidden_layer_sizes=(10,), solver="lbfgs", max_iter=1000, random_state=42
16
+ ))
17
+ model.fit(X_train, y_train)
18
+ predictions = model.predict(X_test)
19
+
20
+ matrix = confusion_matrix(y_test, predictions)
21
+ tp = matrix.diagonal()
22
+ fp = matrix.sum(axis=0) - tp
23
+ fn = matrix.sum(axis=1) - tp
24
+ tn = matrix.sum() - tp - fp - fn
25
+
26
+ accuracy = accuracy_score(y_test, predictions)
27
+ print("TP, TN, FP, FN (by class):", tp, tn, fp, fn)
28
+ print("Accuracy:", accuracy)
29
+ print("Error:", 1 - accuracy)
30
+ print("Recall:", recall_score(y_test, predictions, average="macro"))
31
+ print("Specificity:", (tn / (tn + fp)).mean())
32
+ print("F1:", f1_score(y_test, predictions, average="macro"))
33
+ auc = roc_auc_score(y_test, model.predict_proba(X_test), multi_class="ovr")
34
+ print("AUC:", auc)
35
+ print("5-fold CV accuracy:", cross_val_score(model, X_train, y_train, cv=5).mean())
@@ -0,0 +1,34 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.model_selection import train_test_split, cross_val_score
3
+ from sklearn.metrics import (
4
+ accuracy_score, confusion_matrix, recall_score, f1_score, roc_auc_score
5
+ )
6
+ from sklearn.neighbors import KNeighborsClassifier
7
+ from sklearn.pipeline import make_pipeline
8
+ from sklearn.preprocessing import StandardScaler
9
+
10
+ X, y = load_iris(return_X_y=True)
11
+ X_train, X_test, y_train, y_test = train_test_split(
12
+ X, y, test_size=0.2, random_state=42, stratify=y
13
+ )
14
+ k = int(input("Enter the number of neighbors (example: 5): "))
15
+ model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
16
+ model.fit(X_train, y_train)
17
+ predictions = model.predict(X_test)
18
+
19
+ matrix = confusion_matrix(y_test, predictions)
20
+ tp = matrix.diagonal()
21
+ fp = matrix.sum(axis=0) - tp
22
+ fn = matrix.sum(axis=1) - tp
23
+ tn = matrix.sum() - tp - fp - fn
24
+
25
+ accuracy = accuracy_score(y_test, predictions)
26
+ print("TP, TN, FP, FN (by class):", tp, tn, fp, fn)
27
+ print("Accuracy:", accuracy)
28
+ print("Error:", 1 - accuracy)
29
+ print("Recall:", recall_score(y_test, predictions, average="macro"))
30
+ print("Specificity:", (tn / (tn + fp)).mean())
31
+ print("F1:", f1_score(y_test, predictions, average="macro"))
32
+ auc = roc_auc_score(y_test, model.predict_proba(X_test), multi_class="ovr")
33
+ print("AUC:", auc)
34
+ print("5-fold CV accuracy:", cross_val_score(model, X_train, y_train, cv=5).mean())
@@ -0,0 +1,31 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.model_selection import train_test_split, cross_val_score
3
+ from sklearn.metrics import (
4
+ accuracy_score, confusion_matrix, recall_score, f1_score, roc_auc_score
5
+ )
6
+ from sklearn.tree import DecisionTreeClassifier
7
+
8
+ X, y = load_iris(return_X_y=True)
9
+ X_train, X_test, y_train, y_test = train_test_split(
10
+ X, y, test_size=0.2, random_state=42, stratify=y
11
+ )
12
+ model = DecisionTreeClassifier(max_depth=3, random_state=42)
13
+ model.fit(X_train, y_train)
14
+ predictions = model.predict(X_test)
15
+
16
+ matrix = confusion_matrix(y_test, predictions)
17
+ tp = matrix.diagonal()
18
+ fp = matrix.sum(axis=0) - tp
19
+ fn = matrix.sum(axis=1) - tp
20
+ tn = matrix.sum() - tp - fp - fn
21
+
22
+ accuracy = accuracy_score(y_test, predictions)
23
+ print("TP, TN, FP, FN (by class):", tp, tn, fp, fn)
24
+ print("Accuracy:", accuracy)
25
+ print("Error:", 1 - accuracy)
26
+ print("Recall:", recall_score(y_test, predictions, average="macro"))
27
+ print("Specificity:", (tn / (tn + fp)).mean())
28
+ print("F1:", f1_score(y_test, predictions, average="macro"))
29
+ auc = roc_auc_score(y_test, model.predict_proba(X_test), multi_class="ovr")
30
+ print("AUC:", auc)
31
+ print("5-fold CV accuracy:", cross_val_score(model, X_train, y_train, cv=5).mean())
@@ -0,0 +1,36 @@
1
+ from sklearn.datasets import load_iris
2
+ from sklearn.model_selection import train_test_split, cross_val_score
3
+ from sklearn.metrics import (
4
+ accuracy_score, confusion_matrix, recall_score, f1_score, roc_auc_score
5
+ )
6
+ from sklearn.svm import SVC
7
+ from sklearn.pipeline import make_pipeline
8
+ from sklearn.preprocessing import StandardScaler
9
+ from sklearn.preprocessing import label_binarize
10
+
11
+ X, y = load_iris(return_X_y=True)
12
+ X_train, X_test, y_train, y_test = train_test_split(
13
+ X, y, test_size=0.2, random_state=42, stratify=y
14
+ )
15
+ model = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
16
+ model.fit(X_train, y_train)
17
+ predictions = model.predict(X_test)
18
+
19
+ matrix = confusion_matrix(y_test, predictions)
20
+ tp = matrix.diagonal()
21
+ fp = matrix.sum(axis=0) - tp
22
+ fn = matrix.sum(axis=1) - tp
23
+ tn = matrix.sum() - tp - fp - fn
24
+
25
+ accuracy = accuracy_score(y_test, predictions)
26
+ print("TP, TN, FP, FN (by class):", tp, tn, fp, fn)
27
+ print("Accuracy:", accuracy)
28
+ print("Error:", 1 - accuracy)
29
+ print("Recall:", recall_score(y_test, predictions, average="macro"))
30
+ print("Specificity:", (tn / (tn + fp)).mean())
31
+ print("F1:", f1_score(y_test, predictions, average="macro"))
32
+ # Compute one-vs-rest AUC from the SVM scores for each class.
33
+ labels = label_binarize(y_test, classes=model.classes_)
34
+ scores = model.decision_function(X_test)
35
+ print("AUC:", roc_auc_score(labels, scores, average="macro"))
36
+ print("5-fold CV accuracy:", cross_val_score(model, X_train, y_train, cv=5).mean())
@@ -0,0 +1,17 @@
1
+ import matplotlib.pyplot as plt
2
+ from sklearn.cluster import KMeans
3
+ from sklearn.datasets import load_iris
4
+ from sklearn.metrics import silhouette_score
5
+ from sklearn.preprocessing import StandardScaler
6
+
7
+ X, _ = load_iris(return_X_y=True)
8
+ X_scaled = StandardScaler().fit_transform(X)
9
+ model = KMeans(n_clusters=3, n_init=10, random_state=42)
10
+ labels = model.fit_predict(X_scaled)
11
+ print("Silhouette score:", silhouette_score(X_scaled, labels))
12
+
13
+ plt.scatter(X_scaled[:, 2], X_scaled[:, 3], c=labels)
14
+ plt.xlabel("Petal length (scaled)")
15
+ plt.ylabel("Petal width (scaled)")
16
+ plt.title("K-means clusters")
17
+ plt.show()
@@ -0,0 +1,17 @@
1
+ import matplotlib.pyplot as plt
2
+ from scipy.cluster.hierarchy import cut_tree, dendrogram, linkage
3
+ from sklearn.datasets import load_iris
4
+ from sklearn.metrics import silhouette_score
5
+ from sklearn.preprocessing import StandardScaler
6
+
7
+ X, _ = load_iris(return_X_y=True)
8
+ X_scaled = StandardScaler().fit_transform(X)
9
+ tree = linkage(X_scaled, method="ward")
10
+ labels = cut_tree(tree, n_clusters=3).ravel()
11
+ print("Silhouette score:", silhouette_score(X_scaled, labels))
12
+
13
+ dendrogram(tree, truncate_mode="lastp", p=20)
14
+ plt.xlabel("Sample or cluster")
15
+ plt.ylabel("Distance")
16
+ plt.title("Hierarchical clustering")
17
+ plt.show()