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.
Files changed (30) hide show
  1. {toyml-0.3.0.dev1/toyml.egg-info → toyml-0.3.1}/PKG-INFO +6 -17
  2. {toyml-0.3.0.dev1 → toyml-0.3.1}/README.md +4 -16
  3. {toyml-0.3.0.dev1 → toyml-0.3.1}/pyproject.toml +3 -3
  4. toyml-0.3.1/toyml/classification/__init__.py +5 -0
  5. toyml-0.3.1/toyml/classification/knn.py +229 -0
  6. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/agnes.py +37 -30
  7. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/bisect_kmeans.py +62 -36
  8. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/dbscan.py +77 -69
  9. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/kmeans.py +35 -29
  10. toyml-0.3.1/toyml/ensemble/__init__.py +5 -0
  11. toyml-0.3.1/toyml/ensemble/adaboost.py +278 -0
  12. {toyml-0.3.0.dev1 → toyml-0.3.1/toyml.egg-info}/PKG-INFO +6 -17
  13. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/SOURCES.txt +1 -4
  14. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/requires.txt +1 -0
  15. toyml-0.3.0.dev1/toyml/classification/__init__.py +0 -0
  16. toyml-0.3.0.dev1/toyml/classification/knn.py +0 -67
  17. toyml-0.3.0.dev1/toyml/ensemble/__init__.py +0 -0
  18. toyml-0.3.0.dev1/toyml/ensemble/ada_boost.py +0 -163
  19. toyml-0.3.0.dev1/toyml/utils/__init__.py +0 -0
  20. toyml-0.3.0.dev1/toyml/utils/linear_algebra.py +0 -89
  21. toyml-0.3.0.dev1/toyml/utils/types.py +0 -34
  22. {toyml-0.3.0.dev1 → toyml-0.3.1}/LICENSE +0 -0
  23. {toyml-0.3.0.dev1 → toyml-0.3.1}/setup.cfg +0 -0
  24. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/__init__.py +0 -0
  25. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/clustering/__init__.py +0 -0
  26. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/exception.py +0 -0
  27. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml/py.typed +0 -0
  28. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/dependency_links.txt +0 -0
  29. {toyml-0.3.0.dev1 → toyml-0.3.1}/toyml.egg-info/top_level.txt +0 -0
  30. {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.0.dev1
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
- [![Python](https://img.shields.io/badge/Python-3.10,%203.11,%203.12,%203.13-blue)](https://devguide.python.org/versions/)
55
- [![PyPI](https://badge.fury.io/py/toyml.svg)](https://pypi.org/project/toyml/)
55
+ [![Python](https://img.shields.io/pypi/pyversions/toyml.svg?color=%2334D058)](https://pypi.org/project/toyml/)
56
+ [![PyPI](https://img.shields.io/pypi/v/toyml?color=%2334D058&label=pypi%20package)](https://pypi.org/project/toyml/)
56
57
 
57
58
  ![Codecov](https://codecov.io/gh/ai-glimpse/toyml/branch/master/graph/badge.svg)
58
59
  [![Build Docs](https://github.com/ai-glimpse/toyml/actions/workflows/build_docs.yml/badge.svg)](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
- ## Links
83
- - Documentation: [https://ai-glimpse.github.io/toyml/](https://ai-glimpse.github.io/toyml/)
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
- [![Python](https://img.shields.io/badge/Python-3.10,%203.11,%203.12,%203.13-blue)](https://devguide.python.org/versions/)
5
- [![PyPI](https://badge.fury.io/py/toyml.svg)](https://pypi.org/project/toyml/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/toyml.svg?color=%2334D058)](https://pypi.org/project/toyml/)
5
+ [![PyPI](https://img.shields.io/pypi/v/toyml?color=%2334D058&label=pypi%20package)](https://pypi.org/project/toyml/)
6
6
 
7
7
  ![Codecov](https://codecov.io/gh/ai-glimpse/toyml/branch/master/graph/badge.svg)
8
8
  [![Build Docs](https://github.com/ai-glimpse/toyml/actions/workflows/build_docs.yml/badge.svg)](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
- ## Links
33
- - Documentation: [https://ai-glimpse.github.io/toyml/](https://ai-glimpse.github.io/toyml/)
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.0.dev1"
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
- # TODO: change cov percent to 90
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,5 @@
1
+ from .knn import KNN
2
+
3
+ __all__ = [
4
+ "KNN",
5
+ ]
@@ -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
- euclidean_distance(dataset[i], dataset[j]) for i in cluster1.sample_indices for j in cluster2.sample_indices
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
- G: Optional[nx.Graph] = None,
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 G is None:
87
- G = nx.Graph()
87
+ if graph is None:
88
+ graph = nx.Graph()
88
89
  pos = {}
89
90
 
90
91
  node_id = id(node)
91
- G.add_node(node_id)
92
+ graph.add_node(node_id)
92
93
  pos[node_id] = (x, y) # type: ignore
93
- G.nodes[node_id]["label"] = f"{node.cluster}"
94
- G.nodes[node_id]["size"] = len(node.cluster) * 1000 # Adjust node size based on cluster size
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
- G.add_edge(node_id, left_id)
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, G, pos, l_x, l_y, layer + 1)
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
- G.add_edge(node_id, right_id)
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, G, pos, r_x, r_y, layer + 1)
107
+ _build_graph(node.right, graph, pos, r_x, r_y, layer + 1)
107
108
 
108
- return G, pos # type: ignore
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
- Tip: References
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
- cluster_tree: ClusterTree = field(default_factory=ClusterTree)
153
+ cluster_tree_: ClusterTree = field(default_factory=ClusterTree)
146
154
  """The cluster tree"""
147
- labels: list[int] = field(default_factory=list)
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.cluster_tree.cluster = cluster
170
- self.cluster_tree.centroid = self._get_cluster_centroids(dataset, cluster)
171
- self.labels = self._get_dataset_labels(dataset)
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.cluster_tree.get_clusters()) < self.k:
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.cluster_tree.leaf_cluster_nodes()):
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.labels = self._get_dataset_labels(dataset)
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).labels
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.cluster_tree.centroid is None:
235
+ if self.cluster_tree_.centroid is None:
228
236
  raise ValueError("The model has not been fitted yet.")
229
237
 
230
- clusters = self.cluster_tree.get_clusters()
238
+ clusters = self.cluster_tree_.get_clusters()
231
239
  predictions = []
232
240
  for point in points:
233
- node = self.cluster_tree
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.clusters is not None
255
- cluster1, cluster2 = kmeans.clusters[0], kmeans.clusters[1]
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 _get_dataset_labels(self, dataset: list[list[float]]) -> list[int]:
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.cluster_tree.get_clusters()):
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
- def _get_cluster_centroids(self, dataset: list[list[float]], cluster: list[int]) -> list[float]:
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.cluster_tree.get_clusters())
303
- print(diana.labels)
328
+ print(diana.cluster_tree_.get_clusters())
329
+ print(diana.labels_)
304
330
  # diana.cluster_tree.plot()
305
331
  print(diana.predict(dataset))