toyml 0.3.0.dev1__tar.gz → 0.3.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.
- {toyml-0.3.0.dev1/toyml.egg-info → toyml-0.3.1}/PKG-INFO +6 -17
- {toyml-0.3.0.dev1 → toyml-0.3.1}/README.md +4 -16
- {toyml-0.3.0.dev1 → toyml-0.3.1}/pyproject.toml +3 -3
- toyml-0.3.1/toyml/classification/__init__.py +5 -0
- toyml-0.3.1/toyml/classification/knn.py +229 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/agnes.py +37 -30
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/bisect_kmeans.py +62 -36
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/dbscan.py +77 -69
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/kmeans.py +35 -29
- toyml-0.3.1/toyml/ensemble/__init__.py +5 -0
- toyml-0.3.1/toyml/ensemble/adaboost.py +278 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1/toyml.egg-info}/PKG-INFO +6 -17
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/SOURCES.txt +1 -4
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/requires.txt +1 -0
- toyml-0.3.0.dev1/toyml/classification/__init__.py +0 -0
- toyml-0.3.0.dev1/toyml/classification/knn.py +0 -67
- toyml-0.3.0.dev1/toyml/ensemble/__init__.py +0 -0
- toyml-0.3.0.dev1/toyml/ensemble/ada_boost.py +0 -163
- toyml-0.3.0.dev1/toyml/utils/__init__.py +0 -0
- toyml-0.3.0.dev1/toyml/utils/linear_algebra.py +0 -89
- toyml-0.3.0.dev1/toyml/utils/types.py +0 -34
- {toyml-0.3.0.dev1 → toyml-0.3.1}/LICENSE +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/setup.cfg +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/__init__.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/__init__.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/exception.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/py.typed +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/dependency_links.txt +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/top_level.txt +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/zip-safe +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: toyml
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.1
|
|
4
4
|
Summary: ToyML: Machine Learning from Scratch
|
|
5
5
|
Author-email: Xiangzhuang Shen <datahonor@gmail.com>
|
|
6
6
|
License: Apache 2.0
|
|
@@ -34,6 +34,7 @@ Requires-Dist: isort; extra == "dev"
|
|
|
34
34
|
Requires-Dist: ruff; extra == "dev"
|
|
35
35
|
Requires-Dist: pytest; extra == "dev"
|
|
36
36
|
Requires-Dist: pytest-cov; extra == "dev"
|
|
37
|
+
Requires-Dist: hypothesis>=6.112.0; extra == "dev"
|
|
37
38
|
Provides-Extra: docs
|
|
38
39
|
Requires-Dist: mkdocs; extra == "docs"
|
|
39
40
|
Requires-Dist: mkdocs-material; extra == "docs"
|
|
@@ -51,8 +52,8 @@ Requires-Dist: scipy; extra == "plot"
|
|
|
51
52
|
# ToyML: Machine Learning from Scratch
|
|
52
53
|
|
|
53
54
|
|
|
54
|
-
[](https://pypi.org/project/toyml/)
|
|
56
|
+
[](https://pypi.org/project/toyml/)
|
|
56
57
|
|
|
57
58
|

|
|
58
59
|
[](https://github.com/ai-glimpse/toyml/actions/workflows/build_docs.yml)
|
|
@@ -79,17 +80,5 @@ pip install toyml
|
|
|
79
80
|
```
|
|
80
81
|
|
|
81
82
|
|
|
82
|
-
##
|
|
83
|
-
-
|
|
84
|
-
- PyPi: [https://pypi.org/project/toyml/](https://pypi.org/project/toyml/)
|
|
85
|
-
- Changelog: [https://ai-glimpse.github.io/toyml/CHANGELOG/](https://ai-glimpse.github.io/toyml/CHANGELOG/)
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
## RoadMap
|
|
89
|
-
|
|
90
|
-
- [x] Clustering: DBSCAN, Hierarchical(Agnes&Diana), Kmeans
|
|
91
|
-
- [x] Classification: KNN
|
|
92
|
-
- [x] Ensemble: Boosting(AdaBoost)
|
|
93
|
-
- [ ] Classification: NaiveBayes, DecisionTree, SVM
|
|
94
|
-
- [ ] Association Analysis: Apriori
|
|
95
|
-
- [ ] Ensemble: GBDT
|
|
83
|
+
## Changelog
|
|
84
|
+
- [https://ai-glimpse.github.io/toyml/CHANGELOG/](https://ai-glimpse.github.io/toyml/CHANGELOG/)
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# ToyML: Machine Learning from Scratch
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
[](https://pypi.org/project/toyml/)
|
|
5
|
+
[](https://pypi.org/project/toyml/)
|
|
6
6
|
|
|
7
7
|

|
|
8
8
|
[](https://github.com/ai-glimpse/toyml/actions/workflows/build_docs.yml)
|
|
@@ -29,17 +29,5 @@ pip install toyml
|
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
|
|
32
|
-
##
|
|
33
|
-
-
|
|
34
|
-
- PyPi: [https://pypi.org/project/toyml/](https://pypi.org/project/toyml/)
|
|
35
|
-
- Changelog: [https://ai-glimpse.github.io/toyml/CHANGELOG/](https://ai-glimpse.github.io/toyml/CHANGELOG/)
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
## RoadMap
|
|
39
|
-
|
|
40
|
-
- [x] Clustering: DBSCAN, Hierarchical(Agnes&Diana), Kmeans
|
|
41
|
-
- [x] Classification: KNN
|
|
42
|
-
- [x] Ensemble: Boosting(AdaBoost)
|
|
43
|
-
- [ ] Classification: NaiveBayes, DecisionTree, SVM
|
|
44
|
-
- [ ] Association Analysis: Apriori
|
|
45
|
-
- [ ] Ensemble: GBDT
|
|
32
|
+
## Changelog
|
|
33
|
+
- [https://ai-glimpse.github.io/toyml/CHANGELOG/](https://ai-glimpse.github.io/toyml/CHANGELOG/)
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "toyml"
|
|
7
|
-
version = "0.3.
|
|
7
|
+
version = "0.3.1"
|
|
8
8
|
description = "ToyML: Machine Learning from Scratch"
|
|
9
9
|
keywords=["machine learning", "statistics", "engineering"]
|
|
10
10
|
license = {text = "Apache 2.0"}
|
|
@@ -41,6 +41,7 @@ dev = [
|
|
|
41
41
|
"ruff",
|
|
42
42
|
"pytest",
|
|
43
43
|
"pytest-cov",
|
|
44
|
+
"hypothesis>=6.112.0",
|
|
44
45
|
]
|
|
45
46
|
docs = [
|
|
46
47
|
"mkdocs",
|
|
@@ -95,8 +96,7 @@ profile = "black"
|
|
|
95
96
|
lines_between_types = 1
|
|
96
97
|
|
|
97
98
|
[tool.pytest.ini_options]
|
|
98
|
-
|
|
99
|
-
addopts = "-v --cov=toyml --cov-fail-under 60 --cov-report=term --cov-report=xml --cov-report=html"
|
|
99
|
+
addopts = "-v --cov=toyml --cov-fail-under 90 --cov-report=term --cov-report=xml --cov-report=html"
|
|
100
100
|
testpaths = [
|
|
101
101
|
"tests",
|
|
102
102
|
]
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import statistics
|
|
5
|
+
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class KNN:
|
|
13
|
+
"""
|
|
14
|
+
K-Nearest Neighbors classification algorithm implementation.
|
|
15
|
+
|
|
16
|
+
This class implements the K-Nearest Neighbors algorithm for classification tasks.
|
|
17
|
+
It supports optional standardization of the input data.
|
|
18
|
+
|
|
19
|
+
Examples:
|
|
20
|
+
>>> dataset = [[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0]]
|
|
21
|
+
>>> labels = ['A', 'A', 'B', 'B']
|
|
22
|
+
>>> knn = KNN(k=3, std_transform=True).fit(dataset, labels)
|
|
23
|
+
>>> knn.predict([2.5, 3.5])
|
|
24
|
+
'A'
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
k: The number of nearest neighbors to consider for classification.
|
|
28
|
+
std_transform: Whether to standardize the input data (default: True).
|
|
29
|
+
dataset_: The fitted dataset (standardized if std_transform is True).
|
|
30
|
+
labels_: The labels corresponding to the fitted dataset.
|
|
31
|
+
standardizationer_: The Standardizationer instance if std_transform is True.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
References:
|
|
35
|
+
1. Li Hang
|
|
36
|
+
2. Tan
|
|
37
|
+
3. Zhou Zhihua
|
|
38
|
+
4. Murphy
|
|
39
|
+
5. Harrington
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
k: int
|
|
43
|
+
std_transform: bool = True
|
|
44
|
+
dataset_: Optional[list[list[float]]] = None
|
|
45
|
+
labels_: Optional[list[Any]] = None
|
|
46
|
+
standardizationer_: Optional[Standardizationer] = None
|
|
47
|
+
|
|
48
|
+
def fit(self, dataset: list[list[float]], labels: list[Any]) -> KNN:
|
|
49
|
+
"""
|
|
50
|
+
Fit the KNN model to the given dataset and labels.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
dataset: The input dataset to fit the model to.
|
|
54
|
+
labels: The labels corresponding to the input dataset.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
The fitted KNN instance.
|
|
58
|
+
"""
|
|
59
|
+
self.dataset_ = dataset
|
|
60
|
+
self.labels_ = labels
|
|
61
|
+
if self.std_transform:
|
|
62
|
+
self.standardizationer_ = Standardizationer()
|
|
63
|
+
self.dataset_ = self.standardizationer_.fit_transform(self.dataset_)
|
|
64
|
+
return self
|
|
65
|
+
|
|
66
|
+
def predict(self, x: list[float]) -> Any:
|
|
67
|
+
"""
|
|
68
|
+
Predict the label of the input data.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
x: The input data to predict.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
The predicted label.
|
|
75
|
+
|
|
76
|
+
Raises:
|
|
77
|
+
ValueError: If the model is not fitted yet.
|
|
78
|
+
"""
|
|
79
|
+
if self.dataset_ is None or self.labels_ is None:
|
|
80
|
+
raise ValueError("The model is not fitted yet!")
|
|
81
|
+
|
|
82
|
+
if self.std_transform:
|
|
83
|
+
if self.standardizationer_ is None:
|
|
84
|
+
raise ValueError("Cannot find the standardization!")
|
|
85
|
+
x = self.standardizationer_.transform([x])[0]
|
|
86
|
+
distances = [self._calculate_distance(x, point) for point in self.dataset_]
|
|
87
|
+
# get k-nearest neighbors' label
|
|
88
|
+
k_nearest_labels = [label for _, label in sorted(zip(distances, self.labels_), key=lambda x: x[0])][:: self.k]
|
|
89
|
+
label = Counter(k_nearest_labels).most_common(1)[0][0]
|
|
90
|
+
return label
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def _calculate_distance(x: list[float], y: list[float]) -> float:
|
|
94
|
+
"""
|
|
95
|
+
Calculate the Euclidean distance between two points using a numerically stable method.
|
|
96
|
+
|
|
97
|
+
This implementation avoids overflow by using the two-pass algorithm.
|
|
98
|
+
"""
|
|
99
|
+
assert len(x) == len(y), f"{x} and {y} have different length!"
|
|
100
|
+
|
|
101
|
+
# First pass: find the maximum absolute difference
|
|
102
|
+
max_diff = max(abs(xi - yi) for xi, yi in zip(x, y))
|
|
103
|
+
|
|
104
|
+
if math.isclose(max_diff, 0, abs_tol=1e-9):
|
|
105
|
+
return 0.0 # All elements are identical
|
|
106
|
+
|
|
107
|
+
# Second pass: calculate the normalized sum of squares
|
|
108
|
+
sum_squares = sum(((xi - yi) / max_diff) ** 2 for xi, yi in zip(x, y))
|
|
109
|
+
|
|
110
|
+
return max_diff * math.sqrt(sum_squares)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class Standardizationer:
|
|
115
|
+
"""
|
|
116
|
+
A class for standardizing numerical datasets.
|
|
117
|
+
|
|
118
|
+
Provides methods to fit a standardization model to a dataset,
|
|
119
|
+
transform datasets using the fitted model, and perform both operations
|
|
120
|
+
in a single step.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
_means: list[float] = field(default_factory=list)
|
|
124
|
+
_stds: list[float] = field(default_factory=list)
|
|
125
|
+
_dimension: Optional[int] = None
|
|
126
|
+
|
|
127
|
+
def fit(self, dataset: list[list[float]]) -> Standardizationer:
|
|
128
|
+
"""
|
|
129
|
+
Fit the standardization model to the given dataset.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
dataset: The input dataset to fit the model to.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
The fitted Standardizationer instance.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
ValueError: If the dataset has inconsistent dimensions.
|
|
139
|
+
"""
|
|
140
|
+
self._dimension = self._get_dataset_dimension(dataset)
|
|
141
|
+
self._means = self._dataset_column_means(dataset)
|
|
142
|
+
self._stds = self._dataset_column_stds(dataset)
|
|
143
|
+
return self
|
|
144
|
+
|
|
145
|
+
def transform(self, dataset: list[list[float]]) -> list[list[float]]:
|
|
146
|
+
"""
|
|
147
|
+
Transform the given dataset using the fitted standardization model.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
dataset: The input dataset to transform.
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
The standardized dataset.
|
|
154
|
+
|
|
155
|
+
Raises:
|
|
156
|
+
ValueError: If the model has not been fitted yet.
|
|
157
|
+
"""
|
|
158
|
+
if self._dimension is None:
|
|
159
|
+
raise ValueError("The model is not fitted yet!")
|
|
160
|
+
return self.standardization(dataset)
|
|
161
|
+
|
|
162
|
+
def fit_transform(self, dataset: list[list[float]]) -> list[list[float]]:
|
|
163
|
+
"""
|
|
164
|
+
Fit the standardization model to the dataset and transform it in one step.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
dataset: The input dataset to fit and transform.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
The standardized dataset.
|
|
171
|
+
"""
|
|
172
|
+
self.fit(dataset)
|
|
173
|
+
return self.transform(dataset)
|
|
174
|
+
|
|
175
|
+
def standardization(self, dataset: list[list[float]]) -> list[list[float]]:
|
|
176
|
+
"""
|
|
177
|
+
Standardize the given numerical dataset.
|
|
178
|
+
The standardization is performed by subtracting the mean and dividing by the standard deviation for each feature.
|
|
179
|
+
When the standard deviation is 0, all the values in the column are the same,
|
|
180
|
+
here we set std to 1 to make every value in the column become 0 and avoid division by zero.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
dataset: The input dataset to standardize.
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
The standardized dataset.
|
|
187
|
+
|
|
188
|
+
Raises:
|
|
189
|
+
ValueError: If the model has not been fitted yet.
|
|
190
|
+
"""
|
|
191
|
+
if self._dimension is None:
|
|
192
|
+
raise ValueError("The model is not fitted yet!")
|
|
193
|
+
for j, column in enumerate(zip(*dataset)):
|
|
194
|
+
mean, std = self._means[j], self._stds[j]
|
|
195
|
+
# ref: https://github.com/scikit-learn/scikit-learn/blob/7389dbac82d362f296dc2746f10e43ffa1615660/sklearn/preprocessing/data.py#L70
|
|
196
|
+
if math.isclose(std, 0, abs_tol=1e-9):
|
|
197
|
+
std = 1
|
|
198
|
+
for i, value in enumerate(column):
|
|
199
|
+
dataset[i][j] = (value - mean) / std
|
|
200
|
+
return dataset
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def _get_dataset_dimension(dataset: list[list[float]]) -> int:
|
|
204
|
+
dimension = len(dataset[0])
|
|
205
|
+
if not all([len(row) == dimension for row in dataset]):
|
|
206
|
+
raise ValueError("All rows must have the same number of columns")
|
|
207
|
+
return dimension
|
|
208
|
+
|
|
209
|
+
@staticmethod
|
|
210
|
+
def _dataset_column_means(dataset: list[list[float]]) -> list[float]:
|
|
211
|
+
"""
|
|
212
|
+
Calculate vectors mean
|
|
213
|
+
"""
|
|
214
|
+
return [statistics.mean(column) for column in zip(*dataset)]
|
|
215
|
+
|
|
216
|
+
@staticmethod
|
|
217
|
+
def _dataset_column_stds(dataset: list[list[float]]) -> list[float]:
|
|
218
|
+
"""
|
|
219
|
+
Calculate vectors(every column) standard variance
|
|
220
|
+
"""
|
|
221
|
+
return [statistics.stdev(column) for column in zip(*dataset)]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
if __name__ == "__main__":
|
|
225
|
+
dataset: list[list[float]] = [[0.0], [1], [2], [3]]
|
|
226
|
+
labels: list[Any] = [0, 0, 1, 1]
|
|
227
|
+
knn = KNN(3).fit(dataset, labels)
|
|
228
|
+
print(knn.labels_)
|
|
229
|
+
print(knn.predict([1.1]))
|
|
@@ -5,35 +5,6 @@ import math
|
|
|
5
5
|
from dataclasses import dataclass, field
|
|
6
6
|
from typing import Literal, Optional, Tuple
|
|
7
7
|
|
|
8
|
-
from toyml.utils.linear_algebra import euclidean_distance
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
@dataclass
|
|
12
|
-
class ClusterTree:
|
|
13
|
-
"""
|
|
14
|
-
Represents a node in the hierarchical clustering tree.
|
|
15
|
-
|
|
16
|
-
Each node is a cluster containing sample indices.
|
|
17
|
-
Leaf nodes represent individual samples, while internal nodes
|
|
18
|
-
represent merged clusters. The root node contains all samples.
|
|
19
|
-
"""
|
|
20
|
-
|
|
21
|
-
cluster_index: int
|
|
22
|
-
parent: Optional[ClusterTree] = None
|
|
23
|
-
"""Parent node."""
|
|
24
|
-
children: list[ClusterTree] = field(default_factory=list)
|
|
25
|
-
"""Children nodes."""
|
|
26
|
-
sample_indices: list[int] = field(default_factory=list)
|
|
27
|
-
"""The cluster: dataset sample indices."""
|
|
28
|
-
children_cluster_distance: Optional[float] = None
|
|
29
|
-
|
|
30
|
-
def add_child(self, child: ClusterTree) -> None:
|
|
31
|
-
child.parent = self
|
|
32
|
-
self.children.append(child)
|
|
33
|
-
|
|
34
|
-
def __repr__(self) -> str:
|
|
35
|
-
return f"CT({self.cluster_index}): {self.sample_indices}"
|
|
36
|
-
|
|
37
8
|
|
|
38
9
|
@dataclass
|
|
39
10
|
class AGNES:
|
|
@@ -73,6 +44,8 @@ class AGNES:
|
|
|
73
44
|
"""The number of clusters, specified by user."""
|
|
74
45
|
linkage: Literal["single", "complete", "average"] = "single"
|
|
75
46
|
"""The linkage method to use."""
|
|
47
|
+
distance_metric: Literal["euclidean"] = "euclidean"
|
|
48
|
+
"""The distance metric to use.(For now we only support euclidean)."""
|
|
76
49
|
distance_matrix_: list[list[float]] = field(default_factory=list)
|
|
77
50
|
"""The distance matrix."""
|
|
78
51
|
clusters_: list[ClusterTree] = field(default_factory=list)
|
|
@@ -146,7 +119,7 @@ class AGNES:
|
|
|
146
119
|
Get the distance between clusters c1 and c2 using the specified linkage method.
|
|
147
120
|
"""
|
|
148
121
|
distances = [
|
|
149
|
-
|
|
122
|
+
self._get_distance(dataset[i], dataset[j]) for i in cluster1.sample_indices for j in cluster2.sample_indices
|
|
150
123
|
]
|
|
151
124
|
|
|
152
125
|
if self.linkage == "single":
|
|
@@ -238,6 +211,13 @@ class AGNES:
|
|
|
238
211
|
for sample_index in cluster.sample_indices:
|
|
239
212
|
self.labels_[sample_index] = cluster_label
|
|
240
213
|
|
|
214
|
+
def _get_distance(self, x: list[float], y: list[float]) -> float:
|
|
215
|
+
assert len(x) == len(y), f"{x} and {y} have different length!"
|
|
216
|
+
if self.distance_metric == "euclidean":
|
|
217
|
+
return math.sqrt(sum(pow(x[i] - y[i], 2) for i in range(len(x))))
|
|
218
|
+
else:
|
|
219
|
+
raise ValueError(f"Distance metric {self.distance_metric} not supported!")
|
|
220
|
+
|
|
241
221
|
def plot_dendrogram(
|
|
242
222
|
self,
|
|
243
223
|
figure_name: str = "agnes_dendrogram.png",
|
|
@@ -279,6 +259,33 @@ class AGNES:
|
|
|
279
259
|
plt.show()
|
|
280
260
|
|
|
281
261
|
|
|
262
|
+
@dataclass
|
|
263
|
+
class ClusterTree:
|
|
264
|
+
"""
|
|
265
|
+
Represents a node in the hierarchical clustering tree.
|
|
266
|
+
|
|
267
|
+
Each node is a cluster containing sample indices.
|
|
268
|
+
Leaf nodes represent individual samples, while internal nodes
|
|
269
|
+
represent merged clusters. The root node contains all samples.
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
cluster_index: int
|
|
273
|
+
parent: Optional[ClusterTree] = None
|
|
274
|
+
"""Parent node."""
|
|
275
|
+
children: list[ClusterTree] = field(default_factory=list)
|
|
276
|
+
"""Children nodes."""
|
|
277
|
+
sample_indices: list[int] = field(default_factory=list)
|
|
278
|
+
"""The cluster: dataset sample indices."""
|
|
279
|
+
children_cluster_distance: Optional[float] = None
|
|
280
|
+
|
|
281
|
+
def add_child(self, child: ClusterTree) -> None:
|
|
282
|
+
child.parent = self
|
|
283
|
+
self.children.append(child)
|
|
284
|
+
|
|
285
|
+
def __repr__(self) -> str:
|
|
286
|
+
return f"CT({self.cluster_index}): {self.sample_indices}"
|
|
287
|
+
|
|
288
|
+
|
|
282
289
|
if __name__ == "__main__":
|
|
283
290
|
dataset: list[list[float]] = [[1.0, 2], [1, 5], [1, 0], [10, 2], [10, 5], [10, 0]]
|
|
284
291
|
n_cluster: int = 2
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import math
|
|
4
|
+
import statistics
|
|
5
|
+
|
|
3
6
|
from dataclasses import dataclass, field
|
|
4
7
|
from typing import Optional
|
|
5
8
|
|
|
6
|
-
import matplotlib.pyplot as plt
|
|
7
|
-
import networkx as nx
|
|
8
|
-
|
|
9
9
|
from toyml.clustering.kmeans import Kmeans
|
|
10
|
-
from toyml.utils.linear_algebra import euclidean_distance, sum_square_error
|
|
11
10
|
|
|
12
11
|
|
|
13
12
|
@dataclass
|
|
@@ -74,38 +73,40 @@ class ClusterTree:
|
|
|
74
73
|
"""
|
|
75
74
|
Plot the cluster tree with adaptive node sizes.
|
|
76
75
|
"""
|
|
76
|
+
import matplotlib.pyplot as plt
|
|
77
|
+
import networkx as nx
|
|
77
78
|
|
|
78
79
|
def _build_graph(
|
|
79
80
|
node: ClusterTree,
|
|
80
|
-
|
|
81
|
+
graph: Optional[nx.Graph] = None,
|
|
81
82
|
pos: Optional[dict[int, tuple[float, float]]] = None,
|
|
82
83
|
x: float = 0,
|
|
83
84
|
y: float = 0,
|
|
84
85
|
layer: int = 1,
|
|
85
86
|
) -> tuple[nx.Graph, dict[int, tuple[float, float]]]:
|
|
86
|
-
if
|
|
87
|
-
|
|
87
|
+
if graph is None:
|
|
88
|
+
graph = nx.Graph()
|
|
88
89
|
pos = {}
|
|
89
90
|
|
|
90
91
|
node_id = id(node)
|
|
91
|
-
|
|
92
|
+
graph.add_node(node_id)
|
|
92
93
|
pos[node_id] = (x, y) # type: ignore
|
|
93
|
-
|
|
94
|
-
|
|
94
|
+
graph.nodes[node_id]["label"] = f"{node.cluster}"
|
|
95
|
+
graph.nodes[node_id]["size"] = len(node.cluster) * 1000 # Adjust node size based on cluster size
|
|
95
96
|
|
|
96
97
|
if node.left:
|
|
97
98
|
left_id = id(node.left)
|
|
98
|
-
|
|
99
|
+
graph.add_edge(node_id, left_id)
|
|
99
100
|
l_x, l_y = x - 1 / 2 ** (layer + 1), y - 0.5
|
|
100
|
-
_build_graph(node.left,
|
|
101
|
+
_build_graph(node.left, graph, pos, l_x, l_y, layer + 1)
|
|
101
102
|
|
|
102
103
|
if node.right:
|
|
103
104
|
right_id = id(node.right)
|
|
104
|
-
|
|
105
|
+
graph.add_edge(node_id, right_id)
|
|
105
106
|
r_x, r_y = x + 1 / 2 ** (layer + 1), y - 0.5
|
|
106
|
-
_build_graph(node.right,
|
|
107
|
+
_build_graph(node.right, graph, pos, r_x, r_y, layer + 1)
|
|
107
108
|
|
|
108
|
-
return
|
|
109
|
+
return graph, pos # type: ignore
|
|
109
110
|
|
|
110
111
|
G, pos = _build_graph(self)
|
|
111
112
|
|
|
@@ -132,7 +133,14 @@ class BisectingKmeans:
|
|
|
132
133
|
Bisecting K-means algorithm.
|
|
133
134
|
Belong to Divisive hierarchical clustering (DIANA) algorithm.(top-down)
|
|
134
135
|
|
|
135
|
-
|
|
136
|
+
Examples:
|
|
137
|
+
>>> from toyml.clustering import BisectingKmeans
|
|
138
|
+
>>> dataset = [[1.0, 1.0], [1.0, 2.0], [2.0, 1.0], [10.0, 1.0], [10.0, 2.0], [11.0, 1.0]]
|
|
139
|
+
>>> bisect_kmeans = BisectingKmeans(k=3)
|
|
140
|
+
>>> labels = bisect_kmeans.fit_predict(dataset)
|
|
141
|
+
>>> clusters = bisect_kmeans.cluster_tree_.get_clusters()
|
|
142
|
+
|
|
143
|
+
References:
|
|
136
144
|
1. Harrington
|
|
137
145
|
2. Tan
|
|
138
146
|
|
|
@@ -142,9 +150,9 @@ class BisectingKmeans:
|
|
|
142
150
|
|
|
143
151
|
k: int
|
|
144
152
|
"""The number of clusters, specified by user."""
|
|
145
|
-
|
|
153
|
+
cluster_tree_: ClusterTree = field(default_factory=ClusterTree)
|
|
146
154
|
"""The cluster tree"""
|
|
147
|
-
|
|
155
|
+
labels_: list[int] = field(default_factory=list)
|
|
148
156
|
"""The cluster labels of the dataset."""
|
|
149
157
|
|
|
150
158
|
def fit(self, dataset: list[list[float]]) -> "BisectingKmeans":
|
|
@@ -166,16 +174,16 @@ class BisectingKmeans:
|
|
|
166
174
|
)
|
|
167
175
|
# start with only one cluster which contains all the data points in dataset
|
|
168
176
|
cluster = list(range(n))
|
|
169
|
-
self.
|
|
170
|
-
self.
|
|
171
|
-
self.
|
|
177
|
+
self.cluster_tree_.cluster = cluster
|
|
178
|
+
self.cluster_tree_.centroid = self._get_cluster_centroids(dataset, cluster)
|
|
179
|
+
self.labels_ = self._predict_dataset_labels(dataset)
|
|
172
180
|
total_error = sum_square_error([dataset[i] for i in cluster])
|
|
173
181
|
# iterate until got k clusters
|
|
174
|
-
while len(self.
|
|
182
|
+
while len(self.cluster_tree_.get_clusters()) < self.k:
|
|
175
183
|
# init values for later iteration
|
|
176
184
|
to_splot_cluster_node = None
|
|
177
185
|
split_cluster_into: Optional[tuple[list[int], list[int]]] = None
|
|
178
|
-
for cluster_index, cluster_node in enumerate(self.
|
|
186
|
+
for cluster_index, cluster_node in enumerate(self.cluster_tree_.leaf_cluster_nodes()):
|
|
179
187
|
# perform K-means with k=2
|
|
180
188
|
cluster_data = [dataset[i] for i in cluster_node.cluster]
|
|
181
189
|
# If the cluster cannot be split further, skip it
|
|
@@ -193,7 +201,7 @@ class BisectingKmeans:
|
|
|
193
201
|
|
|
194
202
|
if to_splot_cluster_node is not None and split_cluster_into is not None:
|
|
195
203
|
self._commit_split(to_splot_cluster_node, split_cluster_into, dataset)
|
|
196
|
-
self.
|
|
204
|
+
self.labels_ = self._predict_dataset_labels(dataset)
|
|
197
205
|
else:
|
|
198
206
|
break
|
|
199
207
|
|
|
@@ -209,7 +217,7 @@ class BisectingKmeans:
|
|
|
209
217
|
Returns:
|
|
210
218
|
Cluster labels of the dataset samples.
|
|
211
219
|
"""
|
|
212
|
-
return self.fit(dataset).
|
|
220
|
+
return self.fit(dataset).labels_
|
|
213
221
|
|
|
214
222
|
def predict(self, points: list[list[float]]) -> list[int]:
|
|
215
223
|
"""
|
|
@@ -224,13 +232,13 @@ class BisectingKmeans:
|
|
|
224
232
|
Raises:
|
|
225
233
|
ValueError: If the model has not been fitted yet.
|
|
226
234
|
"""
|
|
227
|
-
if self.
|
|
235
|
+
if self.cluster_tree_.centroid is None:
|
|
228
236
|
raise ValueError("The model has not been fitted yet.")
|
|
229
237
|
|
|
230
|
-
clusters = self.
|
|
238
|
+
clusters = self.cluster_tree_.get_clusters()
|
|
231
239
|
predictions = []
|
|
232
240
|
for point in points:
|
|
233
|
-
node = self.
|
|
241
|
+
node = self.cluster_tree_
|
|
234
242
|
while not node.is_leaf():
|
|
235
243
|
if node.left is None or node.right is None:
|
|
236
244
|
raise ValueError("Invalid cluster tree structure.")
|
|
@@ -244,15 +252,15 @@ class BisectingKmeans:
|
|
|
244
252
|
|
|
245
253
|
return predictions
|
|
246
254
|
|
|
255
|
+
@staticmethod
|
|
247
256
|
def _bisect_by_kmeans(
|
|
248
|
-
self,
|
|
249
257
|
cluster_data: list[list[float]],
|
|
250
258
|
cluster_node: ClusterTree,
|
|
251
259
|
dataset: list[list[float]],
|
|
252
260
|
) -> tuple[float, float, tuple[list[int], list[int]]]:
|
|
253
261
|
kmeans = Kmeans(k=2).fit(cluster_data)
|
|
254
|
-
assert kmeans.
|
|
255
|
-
cluster1, cluster2 = kmeans.
|
|
262
|
+
assert kmeans.clusters_ is not None
|
|
263
|
+
cluster1, cluster2 = kmeans.clusters_[0], kmeans.clusters_[1]
|
|
256
264
|
# Note: map the cluster's inner index to the truth index in dataset
|
|
257
265
|
cluster1 = [cluster_node.cluster[i] for i in cluster1]
|
|
258
266
|
cluster2 = [cluster_node.cluster[i] for i in cluster2]
|
|
@@ -281,25 +289,43 @@ class BisectingKmeans:
|
|
|
281
289
|
)
|
|
282
290
|
)
|
|
283
291
|
|
|
284
|
-
def
|
|
292
|
+
def _predict_dataset_labels(self, dataset: list[list[float]]) -> list[int]:
|
|
285
293
|
labels = [-1] * len(dataset)
|
|
286
|
-
for cluster_label, cluster in enumerate(self.
|
|
294
|
+
for cluster_label, cluster in enumerate(self.cluster_tree_.get_clusters()):
|
|
287
295
|
for data_point_index in cluster:
|
|
288
296
|
labels[data_point_index] = cluster_label
|
|
289
297
|
return labels
|
|
290
298
|
|
|
291
|
-
|
|
299
|
+
@staticmethod
|
|
300
|
+
def _get_cluster_centroids(dataset: list[list[float]], cluster: list[int]) -> list[float]:
|
|
292
301
|
cluster_points = [dataset[i] for i in cluster]
|
|
293
302
|
centroid = [sum(t) / len(cluster) for t in zip(*cluster_points)]
|
|
294
303
|
return centroid
|
|
295
304
|
|
|
296
305
|
|
|
306
|
+
def euclidean_distance(v1: list[float], v2: list[float]) -> float:
|
|
307
|
+
"""
|
|
308
|
+
Calculate the L2 distance between two vectors
|
|
309
|
+
|
|
310
|
+
"""
|
|
311
|
+
assert len(v1) == len(v2), f"{v1} and {v2} have different length!"
|
|
312
|
+
return math.sqrt(sum(pow(v1[i] - v2[i], 2) for i in range(len(v1))))
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def sum_square_error(c: list[list[float]]) -> float:
|
|
316
|
+
"""
|
|
317
|
+
Calc the sum of squared errors.
|
|
318
|
+
"""
|
|
319
|
+
mean_c = [statistics.mean([v[i] for v in c]) for i in range(len(c[0]))]
|
|
320
|
+
return sum(euclidean_distance(mean_c, v) ** 2 for v in c)
|
|
321
|
+
|
|
322
|
+
|
|
297
323
|
if __name__ == "__main__":
|
|
298
324
|
dataset: list[list[float]] = [[1.0, 1.0], [1.0, 2.0], [2.0, 1.0], [10.0, 1.0], [10.0, 2.0], [11.0, 1.0]]
|
|
299
325
|
k = 6
|
|
300
326
|
# Bisecting K-means testing
|
|
301
327
|
diana = BisectingKmeans(k).fit(dataset)
|
|
302
|
-
print(diana.
|
|
303
|
-
print(diana.
|
|
328
|
+
print(diana.cluster_tree_.get_clusters())
|
|
329
|
+
print(diana.labels_)
|
|
304
330
|
# diana.cluster_tree.plot()
|
|
305
331
|
print(diana.predict(dataset))
|