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

|
|
59
58
|
[](https://github.com/ai-glimpse/toyml/actions/workflows/build_docs.yml)
|
|
@@ -80,5 +79,17 @@ pip install toyml
|
|
|
80
79
|
```
|
|
81
80
|
|
|
82
81
|
|
|
83
|
-
##
|
|
84
|
-
- [https://ai-glimpse.github.io/toyml/
|
|
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
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# ToyML: Machine Learning from Scratch
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
[](https://devguide.python.org/versions/)
|
|
5
|
+
[](https://pypi.org/project/toyml/)
|
|
6
6
|
|
|
7
7
|

|
|
8
8
|
[](https://github.com/ai-glimpse/toyml/actions/workflows/build_docs.yml)
|
|
@@ -29,5 +29,17 @@ pip install toyml
|
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
|
|
32
|
-
##
|
|
33
|
-
- [https://ai-glimpse.github.io/toyml/
|
|
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
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "toyml"
|
|
7
|
-
version = "0.3.0"
|
|
7
|
+
version = "0.3.0.dev1"
|
|
8
8
|
description = "ToyML: Machine Learning from Scratch"
|
|
9
9
|
keywords=["machine learning", "statistics", "engineering"]
|
|
10
10
|
license = {text = "Apache 2.0"}
|
|
@@ -41,7 +41,6 @@ dev = [
|
|
|
41
41
|
"ruff",
|
|
42
42
|
"pytest",
|
|
43
43
|
"pytest-cov",
|
|
44
|
-
"hypothesis>=6.112.0",
|
|
45
44
|
]
|
|
46
45
|
docs = [
|
|
47
46
|
"mkdocs",
|
|
@@ -96,7 +95,8 @@ profile = "black"
|
|
|
96
95
|
lines_between_types = 1
|
|
97
96
|
|
|
98
97
|
[tool.pytest.ini_options]
|
|
99
|
-
|
|
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"
|
|
100
100
|
testpaths = [
|
|
101
101
|
"tests",
|
|
102
102
|
]
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from collections import Counter
|
|
2
|
+
from typing import Callable
|
|
3
|
+
|
|
4
|
+
from toyml.utils.linear_algebra import (
|
|
5
|
+
euclidean_distance,
|
|
6
|
+
standardization,
|
|
7
|
+
vectors_mean,
|
|
8
|
+
vectors_std,
|
|
9
|
+
)
|
|
10
|
+
from toyml.utils.types import DataSet, Label, Labels, Vector
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class KNeighborsClassifier:
|
|
14
|
+
"""
|
|
15
|
+
The implementation of K-Nearest Neighbors.
|
|
16
|
+
|
|
17
|
+
Ref:
|
|
18
|
+
1. Li Hang
|
|
19
|
+
2. Tan
|
|
20
|
+
3. Zhou
|
|
21
|
+
4. Murphy
|
|
22
|
+
5. Harrington
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
dataset: DataSet,
|
|
28
|
+
labels: Labels,
|
|
29
|
+
k: int,
|
|
30
|
+
dist: Callable[[Vector, Vector], float] = euclidean_distance,
|
|
31
|
+
std: bool = True,
|
|
32
|
+
) -> None:
|
|
33
|
+
if not isinstance(dataset, list):
|
|
34
|
+
raise TypeError(f"invalid type in {type(dataset)} for the 'dataset' argument")
|
|
35
|
+
self._dataset = dataset
|
|
36
|
+
self._labels = labels
|
|
37
|
+
self._k = k
|
|
38
|
+
self._dist = dist
|
|
39
|
+
# for standardization
|
|
40
|
+
self._is_std = std
|
|
41
|
+
self._means = vectors_mean(dataset)
|
|
42
|
+
self._stds = vectors_std(dataset)
|
|
43
|
+
|
|
44
|
+
def fit(self) -> None:
|
|
45
|
+
if self._is_std:
|
|
46
|
+
standardization(self._dataset, self._means, self._stds)
|
|
47
|
+
else:
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
def predict(self, x: Vector) -> Label:
|
|
51
|
+
# x -> standardization -> v
|
|
52
|
+
d = len(x)
|
|
53
|
+
v = [0.0] * d
|
|
54
|
+
for i in range(d):
|
|
55
|
+
v[i] = (x[i] - self._means[i]) / self._stds[i]
|
|
56
|
+
dists = [self._dist(v, point) for point in self._dataset]
|
|
57
|
+
# get k-nearest neighbors' label
|
|
58
|
+
labels = [x for _, x in sorted(zip(dists, self._labels))][:: self._k]
|
|
59
|
+
return Counter(labels).most_common(1)[0][0]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
if __name__ == "__main__":
|
|
63
|
+
dataset: DataSet = [[0.0], [1], [2], [3]]
|
|
64
|
+
labels: Labels = [0, 0, 1, 1]
|
|
65
|
+
knn = KNeighborsClassifier(dataset, labels, 3)
|
|
66
|
+
knn.fit()
|
|
67
|
+
print(knn.predict([1.1]))
|
|
@@ -5,6 +5,35 @@ 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
|
+
|
|
8
37
|
|
|
9
38
|
@dataclass
|
|
10
39
|
class AGNES:
|
|
@@ -44,8 +73,6 @@ class AGNES:
|
|
|
44
73
|
"""The number of clusters, specified by user."""
|
|
45
74
|
linkage: Literal["single", "complete", "average"] = "single"
|
|
46
75
|
"""The linkage method to use."""
|
|
47
|
-
distance_metric: Literal["euclidean"] = "euclidean"
|
|
48
|
-
"""The distance metric to use.(For now we only support euclidean)."""
|
|
49
76
|
distance_matrix_: list[list[float]] = field(default_factory=list)
|
|
50
77
|
"""The distance matrix."""
|
|
51
78
|
clusters_: list[ClusterTree] = field(default_factory=list)
|
|
@@ -119,7 +146,7 @@ class AGNES:
|
|
|
119
146
|
Get the distance between clusters c1 and c2 using the specified linkage method.
|
|
120
147
|
"""
|
|
121
148
|
distances = [
|
|
122
|
-
|
|
149
|
+
euclidean_distance(dataset[i], dataset[j]) for i in cluster1.sample_indices for j in cluster2.sample_indices
|
|
123
150
|
]
|
|
124
151
|
|
|
125
152
|
if self.linkage == "single":
|
|
@@ -211,13 +238,6 @@ class AGNES:
|
|
|
211
238
|
for sample_index in cluster.sample_indices:
|
|
212
239
|
self.labels_[sample_index] = cluster_label
|
|
213
240
|
|
|
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
|
-
|
|
221
241
|
def plot_dendrogram(
|
|
222
242
|
self,
|
|
223
243
|
figure_name: str = "agnes_dendrogram.png",
|
|
@@ -259,33 +279,6 @@ class AGNES:
|
|
|
259
279
|
plt.show()
|
|
260
280
|
|
|
261
281
|
|
|
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
|
-
|
|
289
282
|
if __name__ == "__main__":
|
|
290
283
|
dataset: list[list[float]] = [[1.0, 2], [1, 5], [1, 0], [10, 2], [10, 5], [10, 0]]
|
|
291
284
|
n_cluster: int = 2
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
-
import math
|
|
4
|
-
import statistics
|
|
5
|
-
|
|
6
3
|
from dataclasses import dataclass, field
|
|
7
4
|
from typing import Optional
|
|
8
5
|
|
|
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
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
@dataclass
|
|
@@ -73,8 +74,6 @@ class ClusterTree:
|
|
|
73
74
|
"""
|
|
74
75
|
Plot the cluster tree with adaptive node sizes.
|
|
75
76
|
"""
|
|
76
|
-
import matplotlib.pyplot as plt
|
|
77
|
-
import networkx as nx
|
|
78
77
|
|
|
79
78
|
def _build_graph(
|
|
80
79
|
node: ClusterTree,
|
|
@@ -133,14 +132,7 @@ class BisectingKmeans:
|
|
|
133
132
|
Bisecting K-means algorithm.
|
|
134
133
|
Belong to Divisive hierarchical clustering (DIANA) algorithm.(top-down)
|
|
135
134
|
|
|
136
|
-
|
|
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:
|
|
135
|
+
Tip: References
|
|
144
136
|
1. Harrington
|
|
145
137
|
2. Tan
|
|
146
138
|
|
|
@@ -302,23 +294,6 @@ class BisectingKmeans:
|
|
|
302
294
|
return centroid
|
|
303
295
|
|
|
304
296
|
|
|
305
|
-
def euclidean_distance(v1: list[float], v2: list[float]) -> float:
|
|
306
|
-
"""
|
|
307
|
-
Calculate the L2 distance between two vectors
|
|
308
|
-
|
|
309
|
-
"""
|
|
310
|
-
assert len(v1) == len(v2), f"{v1} and {v2} have different length!"
|
|
311
|
-
return math.sqrt(sum(pow(v1[i] - v2[i], 2) for i in range(len(v1))))
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
def sum_square_error(c: list[list[float]]) -> float:
|
|
315
|
-
"""
|
|
316
|
-
Calc the sum of squared errors.
|
|
317
|
-
"""
|
|
318
|
-
mean_c = [statistics.mean([v[i] for v in c]) for i in range(len(c[0]))]
|
|
319
|
-
return sum(euclidean_distance(mean_c, v) ** 2 for v in c)
|
|
320
|
-
|
|
321
|
-
|
|
322
297
|
if __name__ == "__main__":
|
|
323
298
|
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]]
|
|
324
299
|
k = 6
|
|
@@ -1,15 +1,81 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
|
-
import math
|
|
5
4
|
|
|
6
5
|
from collections import deque
|
|
7
6
|
from dataclasses import dataclass, field
|
|
8
|
-
|
|
7
|
+
|
|
8
|
+
from toyml.utils.linear_algebra import euclidean_distance
|
|
9
9
|
|
|
10
10
|
logger = logging.getLogger(__name__)
|
|
11
11
|
|
|
12
12
|
|
|
13
|
+
@dataclass
|
|
14
|
+
class Dataset:
|
|
15
|
+
"""
|
|
16
|
+
Dataset for DBSCAN
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
data: The dataset.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
data: The dataset.
|
|
23
|
+
n: The number of data points.
|
|
24
|
+
distance_matrix_: The distance matrix.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
data: list[list[float]]
|
|
28
|
+
n: int = field(init=False)
|
|
29
|
+
distance_matrix_: list[list[float]] = field(init=False)
|
|
30
|
+
|
|
31
|
+
def __post_init__(self) -> None:
|
|
32
|
+
self.n = len(self.data)
|
|
33
|
+
self.distance_matrix_ = self._calculate_distance_matrix()
|
|
34
|
+
|
|
35
|
+
def _calculate_distance_matrix(self) -> list[list[float]]:
|
|
36
|
+
dist_mat = [[0.0 for _ in range(self.n)] for _ in range(self.n)]
|
|
37
|
+
for i in range(self.n):
|
|
38
|
+
for j in range(i, self.n):
|
|
39
|
+
dist_mat[i][j] = euclidean_distance(self.data[i], self.data[j])
|
|
40
|
+
dist_mat[j][i] = dist_mat[i][j]
|
|
41
|
+
return dist_mat
|
|
42
|
+
|
|
43
|
+
def get_neighbors(self, i: int, eps: float) -> list[int]:
|
|
44
|
+
"""
|
|
45
|
+
Get the neighbors of the i-th data point.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
i: The index of the data point.
|
|
49
|
+
eps: The maximum distance between two samples for one to be considered as in the neighborhood of the other.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
The indices of the neighbors(Don't include the point itself).
|
|
53
|
+
"""
|
|
54
|
+
return [j for j in range(self.n) if i != j and self.distance_matrix_[i][j] <= eps]
|
|
55
|
+
|
|
56
|
+
def get_core_objects(self, eps: float, min_samples: int) -> tuple[set[int], list[int]]:
|
|
57
|
+
"""
|
|
58
|
+
Get the core objects and noises of the dataset.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
eps: The maximum distance between two samples for one to be considered as in the neighborhood of the other.
|
|
62
|
+
min_samples: The number of samples (or total weight) in a neighborhood for a point to be considered as a core point.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
core_objects: The indices of the core objects.
|
|
66
|
+
noises: The indices of the noises.
|
|
67
|
+
"""
|
|
68
|
+
core_objects = set()
|
|
69
|
+
noises = []
|
|
70
|
+
for i in range(self.n):
|
|
71
|
+
neighbors = self.get_neighbors(i, eps)
|
|
72
|
+
if len(neighbors) + 1 >= min_samples: # +1 to include the point itself
|
|
73
|
+
core_objects.add(i)
|
|
74
|
+
else:
|
|
75
|
+
noises.append(i)
|
|
76
|
+
return core_objects, noises
|
|
77
|
+
|
|
78
|
+
|
|
13
79
|
@dataclass
|
|
14
80
|
class DBSCAN:
|
|
15
81
|
"""
|
|
@@ -117,81 +183,6 @@ class DBSCAN:
|
|
|
117
183
|
return self.fit(data).labels_
|
|
118
184
|
|
|
119
185
|
|
|
120
|
-
@dataclass
|
|
121
|
-
class Dataset:
|
|
122
|
-
"""
|
|
123
|
-
Dataset for DBSCAN
|
|
124
|
-
|
|
125
|
-
Args:
|
|
126
|
-
data: The dataset.
|
|
127
|
-
|
|
128
|
-
Attributes:
|
|
129
|
-
data: The dataset.
|
|
130
|
-
n: The number of data points.
|
|
131
|
-
distance_matrix_: The distance matrix.
|
|
132
|
-
"""
|
|
133
|
-
|
|
134
|
-
data: list[list[float]]
|
|
135
|
-
n: int = field(init=False)
|
|
136
|
-
distance_metric: Literal["euclidean"] = "euclidean"
|
|
137
|
-
"""The distance metric to use.(For now we only support euclidean)."""
|
|
138
|
-
distance_matrix_: list[list[float]] = field(init=False)
|
|
139
|
-
|
|
140
|
-
def __post_init__(self) -> None:
|
|
141
|
-
self.n = len(self.data)
|
|
142
|
-
self.distance_matrix_ = self._calculate_distance_matrix()
|
|
143
|
-
|
|
144
|
-
def _calculate_distance_matrix(self) -> list[list[float]]:
|
|
145
|
-
dist_mat = [[0.0 for _ in range(self.n)] for _ in range(self.n)]
|
|
146
|
-
for i in range(self.n):
|
|
147
|
-
for j in range(i, self.n):
|
|
148
|
-
dist_mat[i][j] = self._get_distance(self.data[i], self.data[j])
|
|
149
|
-
dist_mat[j][i] = dist_mat[i][j]
|
|
150
|
-
return dist_mat
|
|
151
|
-
|
|
152
|
-
def get_neighbors(self, i: int, eps: float) -> list[int]:
|
|
153
|
-
"""
|
|
154
|
-
Get the neighbors of the i-th data point.
|
|
155
|
-
|
|
156
|
-
Args:
|
|
157
|
-
i: The index of the data point.
|
|
158
|
-
eps: The maximum distance between two samples for one to be considered as in the neighborhood of the other.
|
|
159
|
-
|
|
160
|
-
Returns:
|
|
161
|
-
The indices of the neighbors (Don't include the point itself).
|
|
162
|
-
"""
|
|
163
|
-
return [j for j in range(self.n) if i != j and self.distance_matrix_[i][j] <= eps]
|
|
164
|
-
|
|
165
|
-
def get_core_objects(self, eps: float, min_samples: int) -> tuple[set[int], list[int]]:
|
|
166
|
-
"""
|
|
167
|
-
Get the core objects and noises of the dataset.
|
|
168
|
-
|
|
169
|
-
Args:
|
|
170
|
-
eps: The maximum distance between two samples for one to be considered as in the neighborhood of the other.
|
|
171
|
-
min_samples: The number of samples (or total weight) in a neighborhood for a point to be considered as a core point.
|
|
172
|
-
|
|
173
|
-
Returns:
|
|
174
|
-
core_objects: The indices of the core objects.
|
|
175
|
-
noises: The indices of the noises.
|
|
176
|
-
"""
|
|
177
|
-
core_objects = set()
|
|
178
|
-
noises = []
|
|
179
|
-
for i in range(self.n):
|
|
180
|
-
neighbors = self.get_neighbors(i, eps)
|
|
181
|
-
if len(neighbors) + 1 >= min_samples: # +1 to include the point itself
|
|
182
|
-
core_objects.add(i)
|
|
183
|
-
else:
|
|
184
|
-
noises.append(i)
|
|
185
|
-
return core_objects, noises
|
|
186
|
-
|
|
187
|
-
def _get_distance(self, x: list[float], y: list[float]) -> float:
|
|
188
|
-
assert len(x) == len(y), f"{x} and {y} have different length!"
|
|
189
|
-
if self.distance_metric == "euclidean":
|
|
190
|
-
return math.sqrt(sum(pow(x[i] - y[i], 2) for i in range(len(x))))
|
|
191
|
-
else:
|
|
192
|
-
raise ValueError(f"Distance metric {self.distance_metric} not supported!")
|
|
193
|
-
|
|
194
|
-
|
|
195
186
|
if __name__ == "__main__":
|
|
196
187
|
dataset: list[list[float]] = [[1.0, 2], [2, 2], [2, 3], [8, 7], [8, 8], [25, 80]]
|
|
197
188
|
dbscan = DBSCAN(eps=3, min_samples=2).fit(dataset)
|
|
@@ -7,6 +7,8 @@ import random
|
|
|
7
7
|
from dataclasses import dataclass, field
|
|
8
8
|
from typing import Literal, Optional
|
|
9
9
|
|
|
10
|
+
from toyml.utils.linear_algebra import euclidean_distance
|
|
11
|
+
|
|
10
12
|
logger = logging.getLogger(__name__)
|
|
11
13
|
|
|
12
14
|
|
|
@@ -59,8 +61,6 @@ class Kmeans:
|
|
|
59
61
|
"""The method to initialize the centroids."""
|
|
60
62
|
random_seed: Optional[int] = None
|
|
61
63
|
"""The random seed used to initialize the centroids."""
|
|
62
|
-
distance_metric: Literal["euclidean"] = "euclidean"
|
|
63
|
-
"""The distance metric to use.(For now we only support euclidean)."""
|
|
64
64
|
iter_: int = 0
|
|
65
65
|
clusters: dict[int, list[int]] = field(default_factory=dict)
|
|
66
66
|
"""The clusters of the dataset."""
|
|
@@ -126,13 +126,6 @@ class Kmeans:
|
|
|
126
126
|
raise ValueError("The model is not fitted yet")
|
|
127
127
|
return self._get_centroid_label(point, self.centroids)
|
|
128
128
|
|
|
129
|
-
def _get_distance(self, x: list[float], y: list[float]) -> float:
|
|
130
|
-
assert len(x) == len(y), f"{x} and {y} have different length!"
|
|
131
|
-
if self.distance_metric == "euclidean":
|
|
132
|
-
return math.sqrt(sum(pow(x[i] - y[i], 2) for i in range(len(x))))
|
|
133
|
-
else:
|
|
134
|
-
raise ValueError(f"Distance metric {self.distance_metric} not supported!")
|
|
135
|
-
|
|
136
129
|
def _get_dataset_labels(self, dataset: list[list[float]]) -> list[int]:
|
|
137
130
|
labels = [-1] * len(dataset)
|
|
138
131
|
for cluster_label, cluster in self.clusters.items():
|
|
@@ -214,15 +207,16 @@ class Kmeans:
|
|
|
214
207
|
The minimum square distance
|
|
215
208
|
"""
|
|
216
209
|
return min(
|
|
217
|
-
(
|
|
210
|
+
(euclidean_distance(point, centroid) ** 2 for centroid in self.centroids.values() if centroid),
|
|
218
211
|
default=math.inf,
|
|
219
212
|
)
|
|
220
213
|
|
|
221
|
-
|
|
214
|
+
@staticmethod
|
|
215
|
+
def _get_centroid_label(point: list[float], centroids: dict[int, list[float]]) -> int:
|
|
222
216
|
"""
|
|
223
217
|
Get the label of the centroid, which is closest to the point
|
|
224
218
|
"""
|
|
225
|
-
distances = [(i,
|
|
219
|
+
distances = [(i, euclidean_distance(point, centroid)) for i, centroid in centroids.items()]
|
|
226
220
|
return min(distances, key=lambda x: x[1])[0]
|
|
227
221
|
|
|
228
222
|
def _get_clusters(self, dataset: list[list[float]]) -> dict[int, list[int]]:
|