foml-toolkit 0.2.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 (29) hide show
  1. foml_toolkit-0.2.0/.github/workflows/tests.yml +12 -0
  2. foml_toolkit-0.2.0/.gitignore +8 -0
  3. foml_toolkit-0.2.0/LICENSE +21 -0
  4. foml_toolkit-0.2.0/PKG-INFO +136 -0
  5. foml_toolkit-0.2.0/README.md +109 -0
  6. foml_toolkit-0.2.0/pyproject.toml +35 -0
  7. foml_toolkit-0.2.0/src/foml_toolkit/__init__.py +56 -0
  8. foml_toolkit-0.2.0/src/foml_toolkit/clustering.py +136 -0
  9. foml_toolkit-0.2.0/src/foml_toolkit/codebook.py +188 -0
  10. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab01_linalg.py +77 -0
  11. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab01_numpy_basics.py +56 -0
  12. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab02_gd_simple.py +46 -0
  13. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab02_gd_two_var.py +45 -0
  14. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab03_gd_matrix.py +50 -0
  15. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab04_logistic_gd.py +63 -0
  16. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab05_nn_forward.py +88 -0
  17. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab06_nn_scratch.py +96 -0
  18. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab07_keras_nn.py +85 -0
  19. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab08_pca_manual.py +41 -0
  20. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab08_pca_sklearn.py +58 -0
  21. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab09_pca_faces.py +49 -0
  22. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab09_pca_images.py +64 -0
  23. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab10_lda.py +68 -0
  24. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab11_kmeans.py +43 -0
  25. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab12_hierarchical.py +43 -0
  26. foml_toolkit-0.2.0/src/foml_toolkit/labs_code/lab14_concrete.py +269 -0
  27. foml_toolkit-0.2.0/src/foml_toolkit/regression.py +284 -0
  28. foml_toolkit-0.2.0/tests/test_codebook.py +74 -0
  29. foml_toolkit-0.2.0/tests/test_toolkit.py +94 -0
@@ -0,0 +1,12 @@
1
+ name: tests
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ubuntu-latest
6
+ steps:
7
+ - uses: actions/checkout@v4
8
+ - uses: actions/setup-python@v5
9
+ with:
10
+ python-version: "3.11"
11
+ - run: pip install -e ".[regression,dev]"
12
+ - run: pytest -q
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ .pytest_cache/
8
+ .ipynb_checkpoints/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Your Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.5
2
+ Name: foml-toolkit
3
+ Version: 0.2.0
4
+ Summary: All FOML lab code (Labs 1-14) with run("pca") and help() code lookup, plus clustering and regression helpers.
5
+ Project-URL: Homepage, https://github.com/YOUR_USERNAME/foml-toolkit
6
+ Author-email: Your Name <you@example.com>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.9
10
+ Requires-Dist: matplotlib
11
+ Requires-Dist: numpy
12
+ Requires-Dist: pandas
13
+ Requires-Dist: scikit-learn
14
+ Requires-Dist: scipy
15
+ Provides-Extra: cv
16
+ Requires-Dist: opencv-python; extra == 'cv'
17
+ Provides-Extra: deep
18
+ Requires-Dist: tensorflow; extra == 'deep'
19
+ Provides-Extra: dev
20
+ Requires-Dist: build; extra == 'dev'
21
+ Requires-Dist: pytest; extra == 'dev'
22
+ Requires-Dist: twine; extra == 'dev'
23
+ Provides-Extra: regression
24
+ Requires-Dist: statsmodels; extra == 'regression'
25
+ Requires-Dist: ucimlrepo; extra == 'regression'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # foml-toolkit
29
+
30
+ All FOML lab code (Labs 1-14) in one library. Type a topic name and get the code.
31
+
32
+ ```python
33
+ import foml_toolkit as ft # or: from foml_toolkit import *
34
+
35
+ ft.run("pca") # prints ALL PCA code (manual, sklearn, faces, your own images)
36
+ ft.run("kmeans") # K-Means (Lab 11)
37
+ ft.run("lda") # LDA (Lab 10)
38
+ ft.run("lab9") # everything from Lab 9
39
+ ft.run(ft.pca) # also works without quotes: run(pca) after from foml_toolkit import *
40
+ ft.run("kmeans", execute=True) # print the code AND run it
41
+ ft.topics() # list every topic
42
+ ft.search("silhouette") # find a topic by keyword
43
+ ft.show_all() # print every code in the library
44
+ help(ft) # opens the full index + ALL code in Python's help viewer
45
+ ```
46
+
47
+ | Topic name | Lab | What |
48
+ |---|---|---|
49
+ | `linalg`, `broadcasting` | 1 | solve/det/singular systems, NumPy speed, broadcasting, shapes |
50
+ | `gd_simple`, `gd_two_var` | 2 | gradient descent (1 and 2 features), SGDRegressor |
51
+ | `gd_matrix` | 3 | matrix gradient descent |
52
+ | `logistic_gd` | 4 | logistic regression from scratch |
53
+ | `nn_forward` | 5 | forward propagation, 2- and 3-layer |
54
+ | `nn_scratch` | 6 | full neural network, backprop, training |
55
+ | `keras_nn` | 7 | TensorFlow/Keras classification + regression |
56
+ | `pca_manual`, `pca_sklearn` | 8 | PCA by hand and with sklearn (Iris) |
57
+ | `pca_faces`, `pca_images` | 9 | image PCA (Olivetti faces, your own pictures) |
58
+ | `lda` | 10 | Linear Discriminant Analysis |
59
+ | `kmeans` | 11 | K-Means |
60
+ | `hierarchical` | 12 | agglomerative clustering, dendrogram, silhouette |
61
+ | `concrete_regression` | 14 | concrete strength, 9 models + GridSearchCV |
62
+
63
+ Groups: `pca`, `gd`, `nn`, `cluster`, `logistic`, `linear_regression`, `numpy_basics`.
64
+
65
+ Some snippets need extras: `pip install "foml-toolkit[regression,cv,deep]"`
66
+ (`regression` = ucimlrepo+statsmodels, `cv` = opencv for `pca_images`, `deep` = tensorflow for `keras_nn`).
67
+
68
+ Small bugs in the original notebooks are fixed and marked with `# NOTE:` comments in the code.
69
+
70
+ The clustering and regression labs are also real, importable functions
71
+ (`ft.run_kmeans`, `ft.compare_linkages`, `ft.evaluate_models`, ... see below).
72
+
73
+ ## Install
74
+
75
+ ```bash
76
+ pip install -e . # from the project folder (private / editable)
77
+ pip install -e ".[regression]" # also installs ucimlrepo + statsmodels (Lab 14)
78
+ # or straight from GitHub:
79
+ pip install "foml-toolkit[regression] @ git+https://github.com/YOUR_USERNAME/foml-toolkit.git"
80
+ ```
81
+
82
+ ## Quick examples
83
+
84
+ ```python
85
+ import foml_toolkit as ft
86
+
87
+ # Lab 11 - K-Means on Wine
88
+ X, y = ft.load_wine_df()
89
+ model, Xs = ft.run_kmeans(X, n_clusters=3, scale=True)
90
+ print(model.labels_, model.cluster_centers_)
91
+ ft.plot_clusters_2d(X, model.labels_, x_index=0, y_index=9,
92
+ xlabel="Alcohol", ylabel="Color Intensity")
93
+
94
+ # Lab 12 - Hierarchical clustering on Iris
95
+ X, y = ft.load_iris_df()
96
+ Xs, _ = ft.scale_features(X)
97
+ ft.plot_dendrogram(Xs)
98
+ print(ft.compare_linkages(Xs))
99
+ _, labels = ft.run_agglomerative(Xs, 3, "ward")
100
+ print(ft.cluster_vs_actual(y, labels))
101
+
102
+ # Lab 14 - Concrete strength
103
+ from sklearn.model_selection import train_test_split
104
+ import pandas as pd
105
+ df = ft.load_concrete()
106
+ X, y = ft.clean_data(df)
107
+ Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)
108
+ sets = ft.select_feature_sets(Xtr, Xte)
109
+
110
+ results, models = [], {}
111
+ for name, (a, b) in sets.items():
112
+ r, m = ft.evaluate_models(a, b, ytr, yte, name) # slow: full grids
113
+ results.append(r); models[name] = m
114
+ results_all = pd.concat(results, ignore_index=True)
115
+
116
+ model, fs, name, row = ft.select_best_model(results_all, models)
117
+ mix = {"Cement": [350], "Slag": [80], "Fly_Ash": [50], "Water": [180],
118
+ "Superplasticizer": [8], "Coarse_Aggregate": [1000],
119
+ "Fine_Aggregate": [750], "Age": [28]}
120
+ print(ft.predict_new_mix(model, fs, mix), "MPa")
121
+ ```
122
+
123
+ ## Develop
124
+
125
+ ```bash
126
+ pip install -e ".[regression,dev]"
127
+ pytest
128
+ ```
129
+
130
+ ## Publish
131
+
132
+ ```bash
133
+ python -m build
134
+ twine upload --repository testpypi dist/* # try first
135
+ twine upload dist/* # real PyPI
136
+ ```
@@ -0,0 +1,109 @@
1
+ # foml-toolkit
2
+
3
+ All FOML lab code (Labs 1-14) in one library. Type a topic name and get the code.
4
+
5
+ ```python
6
+ import foml_toolkit as ft # or: from foml_toolkit import *
7
+
8
+ ft.run("pca") # prints ALL PCA code (manual, sklearn, faces, your own images)
9
+ ft.run("kmeans") # K-Means (Lab 11)
10
+ ft.run("lda") # LDA (Lab 10)
11
+ ft.run("lab9") # everything from Lab 9
12
+ ft.run(ft.pca) # also works without quotes: run(pca) after from foml_toolkit import *
13
+ ft.run("kmeans", execute=True) # print the code AND run it
14
+ ft.topics() # list every topic
15
+ ft.search("silhouette") # find a topic by keyword
16
+ ft.show_all() # print every code in the library
17
+ help(ft) # opens the full index + ALL code in Python's help viewer
18
+ ```
19
+
20
+ | Topic name | Lab | What |
21
+ |---|---|---|
22
+ | `linalg`, `broadcasting` | 1 | solve/det/singular systems, NumPy speed, broadcasting, shapes |
23
+ | `gd_simple`, `gd_two_var` | 2 | gradient descent (1 and 2 features), SGDRegressor |
24
+ | `gd_matrix` | 3 | matrix gradient descent |
25
+ | `logistic_gd` | 4 | logistic regression from scratch |
26
+ | `nn_forward` | 5 | forward propagation, 2- and 3-layer |
27
+ | `nn_scratch` | 6 | full neural network, backprop, training |
28
+ | `keras_nn` | 7 | TensorFlow/Keras classification + regression |
29
+ | `pca_manual`, `pca_sklearn` | 8 | PCA by hand and with sklearn (Iris) |
30
+ | `pca_faces`, `pca_images` | 9 | image PCA (Olivetti faces, your own pictures) |
31
+ | `lda` | 10 | Linear Discriminant Analysis |
32
+ | `kmeans` | 11 | K-Means |
33
+ | `hierarchical` | 12 | agglomerative clustering, dendrogram, silhouette |
34
+ | `concrete_regression` | 14 | concrete strength, 9 models + GridSearchCV |
35
+
36
+ Groups: `pca`, `gd`, `nn`, `cluster`, `logistic`, `linear_regression`, `numpy_basics`.
37
+
38
+ Some snippets need extras: `pip install "foml-toolkit[regression,cv,deep]"`
39
+ (`regression` = ucimlrepo+statsmodels, `cv` = opencv for `pca_images`, `deep` = tensorflow for `keras_nn`).
40
+
41
+ Small bugs in the original notebooks are fixed and marked with `# NOTE:` comments in the code.
42
+
43
+ The clustering and regression labs are also real, importable functions
44
+ (`ft.run_kmeans`, `ft.compare_linkages`, `ft.evaluate_models`, ... see below).
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install -e . # from the project folder (private / editable)
50
+ pip install -e ".[regression]" # also installs ucimlrepo + statsmodels (Lab 14)
51
+ # or straight from GitHub:
52
+ pip install "foml-toolkit[regression] @ git+https://github.com/YOUR_USERNAME/foml-toolkit.git"
53
+ ```
54
+
55
+ ## Quick examples
56
+
57
+ ```python
58
+ import foml_toolkit as ft
59
+
60
+ # Lab 11 - K-Means on Wine
61
+ X, y = ft.load_wine_df()
62
+ model, Xs = ft.run_kmeans(X, n_clusters=3, scale=True)
63
+ print(model.labels_, model.cluster_centers_)
64
+ ft.plot_clusters_2d(X, model.labels_, x_index=0, y_index=9,
65
+ xlabel="Alcohol", ylabel="Color Intensity")
66
+
67
+ # Lab 12 - Hierarchical clustering on Iris
68
+ X, y = ft.load_iris_df()
69
+ Xs, _ = ft.scale_features(X)
70
+ ft.plot_dendrogram(Xs)
71
+ print(ft.compare_linkages(Xs))
72
+ _, labels = ft.run_agglomerative(Xs, 3, "ward")
73
+ print(ft.cluster_vs_actual(y, labels))
74
+
75
+ # Lab 14 - Concrete strength
76
+ from sklearn.model_selection import train_test_split
77
+ import pandas as pd
78
+ df = ft.load_concrete()
79
+ X, y = ft.clean_data(df)
80
+ Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)
81
+ sets = ft.select_feature_sets(Xtr, Xte)
82
+
83
+ results, models = [], {}
84
+ for name, (a, b) in sets.items():
85
+ r, m = ft.evaluate_models(a, b, ytr, yte, name) # slow: full grids
86
+ results.append(r); models[name] = m
87
+ results_all = pd.concat(results, ignore_index=True)
88
+
89
+ model, fs, name, row = ft.select_best_model(results_all, models)
90
+ mix = {"Cement": [350], "Slag": [80], "Fly_Ash": [50], "Water": [180],
91
+ "Superplasticizer": [8], "Coarse_Aggregate": [1000],
92
+ "Fine_Aggregate": [750], "Age": [28]}
93
+ print(ft.predict_new_mix(model, fs, mix), "MPa")
94
+ ```
95
+
96
+ ## Develop
97
+
98
+ ```bash
99
+ pip install -e ".[regression,dev]"
100
+ pytest
101
+ ```
102
+
103
+ ## Publish
104
+
105
+ ```bash
106
+ python -m build
107
+ twine upload --repository testpypi dist/* # try first
108
+ twine upload dist/* # real PyPI
109
+ ```
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "foml-toolkit"
7
+ version = "0.2.0"
8
+ description = "All FOML lab code (Labs 1-14) with run(\"pca\") and help() code lookup, plus clustering and regression helpers."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Your Name", email = "you@example.com" }]
13
+ dependencies = [
14
+ "numpy",
15
+ "pandas",
16
+ "matplotlib",
17
+ "scikit-learn",
18
+ "scipy",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ # needed only for load_concrete() and calculate_vif()
23
+ regression = ["ucimlrepo", "statsmodels"]
24
+ cv = ["opencv-python"]
25
+ deep = ["tensorflow"]
26
+ dev = ["pytest", "build", "twine"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/YOUR_USERNAME/foml-toolkit"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/foml_toolkit"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
@@ -0,0 +1,56 @@
1
+ """foml_toolkit: all FOML lab code (Labs 1-14) in one library."""
2
+
3
+ from .clustering import (
4
+ load_iris_df,
5
+ load_wine_df,
6
+ scale_features,
7
+ run_kmeans,
8
+ plot_clusters_2d,
9
+ plot_dendrogram,
10
+ run_agglomerative,
11
+ compare_linkages,
12
+ cluster_vs_actual,
13
+ )
14
+ from .regression import (
15
+ load_concrete,
16
+ clean_data,
17
+ engineer_features,
18
+ ORIGINAL_FEATURES,
19
+ ENGINEERED_REDUCED_FEATURES,
20
+ VIF_REDUCED_FEATURES,
21
+ select_feature_sets,
22
+ calculate_vif,
23
+ get_model_configs,
24
+ evaluate_models,
25
+ select_best_model,
26
+ plot_actual_vs_predicted,
27
+ plot_residuals,
28
+ predict_new_mix,
29
+ )
30
+
31
+ from .codebook import (
32
+ run, execute, topics, search, show_all, build_doc, topic_objects, Topic,
33
+ )
34
+
35
+ __version__ = "0.2.0"
36
+
37
+ # every topic is also available as a name: ft.pca, ft.kmeans, ft.lda ...
38
+ _TOPICS = topic_objects()
39
+ globals().update(_TOPICS)
40
+
41
+ # help(foml_toolkit) now lists every topic and prints all the code
42
+ __doc__ = build_doc()
43
+
44
+ __all__ = [
45
+ # clustering (Lab 11 + Lab 12)
46
+ "load_iris_df", "load_wine_df", "scale_features", "run_kmeans",
47
+ "plot_clusters_2d", "plot_dendrogram", "run_agglomerative",
48
+ "compare_linkages", "cluster_vs_actual",
49
+ # regression (Lab 14)
50
+ "load_concrete", "clean_data", "engineer_features",
51
+ "ORIGINAL_FEATURES", "ENGINEERED_REDUCED_FEATURES", "VIF_REDUCED_FEATURES",
52
+ "select_feature_sets", "calculate_vif", "get_model_configs",
53
+ "evaluate_models", "select_best_model", "plot_actual_vs_predicted",
54
+ "plot_residuals", "predict_new_mix",
55
+ ]
56
+ __all__ += ["run", "execute", "topics", "search", "show_all", *_TOPICS.keys()]
@@ -0,0 +1,136 @@
1
+ """Clustering helpers.
2
+
3
+ Lab 11: K-Means on the Wine dataset and on small 2-D arrays.
4
+ Lab 12: Hierarchical (agglomerative) clustering on the Iris dataset.
5
+ """
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
+ from sklearn.datasets import load_iris, load_wine
11
+ from sklearn.preprocessing import StandardScaler
12
+ from sklearn.cluster import KMeans, AgglomerativeClustering
13
+ from sklearn.metrics import silhouette_score
14
+ from scipy.cluster.hierarchy import linkage, dendrogram
15
+
16
+
17
+ # --------------------------------------------------------------------------
18
+ # Data loading
19
+ # --------------------------------------------------------------------------
20
+ def load_iris_df():
21
+ """Return (X as DataFrame, y as array) for the Iris dataset."""
22
+ iris = load_iris()
23
+ return pd.DataFrame(iris.data, columns=iris.feature_names), iris.target
24
+
25
+
26
+ def load_wine_df():
27
+ """Return (X as DataFrame, y as array) for the Wine dataset."""
28
+ wine = load_wine()
29
+ return pd.DataFrame(wine.data, columns=wine.feature_names), wine.target
30
+
31
+
32
+ # --------------------------------------------------------------------------
33
+ # Shared
34
+ # --------------------------------------------------------------------------
35
+ def scale_features(X):
36
+ """Standardise features (zero mean, unit variance).
37
+
38
+ Returns (X_scaled, fitted_scaler).
39
+ """
40
+ scaler = StandardScaler()
41
+ return scaler.fit_transform(X), scaler
42
+
43
+
44
+ def plot_clusters_2d(X, labels, x_index=0, y_index=1, xlabel="X1", ylabel="X2",
45
+ title="Clusters", cmap="viridis", centers=None, ax=None,
46
+ show=True):
47
+ """Scatter plot of two columns of X coloured by cluster label.
48
+
49
+ X can be a numpy array or a DataFrame. Pass ``centers`` (e.g.
50
+ ``kmeans.cluster_centers_``) to overlay centroids.
51
+ """
52
+ arr = X.to_numpy() if hasattr(X, "to_numpy") else np.asarray(X)
53
+ if ax is None:
54
+ _, ax = plt.subplots(figsize=(8, 5))
55
+ ax.scatter(arr[:, x_index], arr[:, y_index], c=labels, cmap=cmap)
56
+ if centers is not None:
57
+ c = np.asarray(centers)
58
+ ax.scatter(c[:, x_index], c[:, y_index], marker="X", s=200,
59
+ c="red", edgecolors="black", label="Centroids")
60
+ ax.legend()
61
+ ax.set_xlabel(xlabel)
62
+ ax.set_ylabel(ylabel)
63
+ ax.set_title(title)
64
+ if show:
65
+ plt.show()
66
+ return ax
67
+
68
+
69
+ # --------------------------------------------------------------------------
70
+ # Lab 11: K-Means
71
+ # --------------------------------------------------------------------------
72
+ def run_kmeans(X, n_clusters=3, scale=False, random_state=42, n_init=10):
73
+ """Fit K-Means.
74
+
75
+ Parameters
76
+ ----------
77
+ X : array-like or DataFrame
78
+ n_clusters : int
79
+ scale : bool
80
+ Standardise X before fitting (as done for the Wine data in Lab 11).
81
+
82
+ Returns
83
+ -------
84
+ model : fitted KMeans (use ``.labels_`` and ``.cluster_centers_``)
85
+ X_used : the data actually clustered (scaled if scale=True)
86
+ """
87
+ X_used = scale_features(X)[0] if scale else np.asarray(X)
88
+ model = KMeans(n_clusters=n_clusters, random_state=random_state,
89
+ n_init=n_init)
90
+ model.fit(X_used)
91
+ return model, X_used
92
+
93
+
94
+ # --------------------------------------------------------------------------
95
+ # Lab 12: Hierarchical clustering
96
+ # --------------------------------------------------------------------------
97
+ def plot_dendrogram(X, method="ward", figsize=(12, 6),
98
+ title="Agglomerative Clustering Dendrogram", show=True):
99
+ """Draw a dendrogram. Returns the linkage matrix Z."""
100
+ Z = linkage(X, method=method)
101
+ plt.figure(figsize=figsize)
102
+ dendrogram(Z)
103
+ plt.title(title)
104
+ plt.xlabel("Observations")
105
+ plt.ylabel("Merge Distance")
106
+ if show:
107
+ plt.show()
108
+ return Z
109
+
110
+
111
+ def run_agglomerative(X, n_clusters=3, linkage_method="ward"):
112
+ """Fit AgglomerativeClustering and return (model, labels)."""
113
+ model = AgglomerativeClustering(n_clusters=n_clusters,
114
+ linkage=linkage_method)
115
+ labels = model.fit_predict(X)
116
+ return model, labels
117
+
118
+
119
+ def compare_linkages(X, n_clusters=3,
120
+ methods=("single", "complete", "average", "ward")):
121
+ """Silhouette score for each linkage method.
122
+
123
+ The silhouette score ranges from -1 to 1; higher means better-separated
124
+ clusters. Returns a DataFrame with columns Linkage / Silhouette Score.
125
+ """
126
+ rows = []
127
+ for m in methods:
128
+ _, labels = run_agglomerative(X, n_clusters, m)
129
+ rows.append([m, silhouette_score(X, labels)])
130
+ return pd.DataFrame(rows, columns=["Linkage", "Silhouette Score"])
131
+
132
+
133
+ def cluster_vs_actual(y_true, labels):
134
+ """Crosstab of actual classes vs. predicted clusters."""
135
+ return pd.crosstab(np.asarray(y_true), np.asarray(labels),
136
+ rownames=["Actual Class"], colnames=["Cluster"])