toyml 0.3.0.dev1__tar.gz → 0.3.0rc0__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.0rc0}/PKG-INFO +4 -3
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/README.md +2 -2
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/pyproject.toml +3 -3
- toyml-0.3.0rc0/toyml/classification/knn.py +228 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/clustering/agnes.py +10 -3
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/clustering/bisect_kmeans.py +22 -4
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/clustering/dbscan.py +13 -4
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/clustering/kmeans.py +12 -6
- toyml-0.3.0rc0/toyml/ensemble/ada_boost.py +267 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0/toyml.egg-info}/PKG-INFO +4 -3
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml.egg-info/SOURCES.txt +1 -4
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml.egg-info/requires.txt +1 -0
- toyml-0.3.0.dev1/toyml/classification/knn.py +0 -67
- 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.0rc0}/LICENSE +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/setup.cfg +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/__init__.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/classification/__init__.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/clustering/__init__.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/ensemble/__init__.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/exception.py +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml/py.typed +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml.egg-info/dependency_links.txt +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/toyml.egg-info/top_level.txt +0 -0
- {toyml-0.3.0.dev1 → toyml-0.3.0rc0}/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.0rc0
|
|
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)
|
|
@@ -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)
|
|
@@ -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.rc0"
|
|
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,228 @@
|
|
|
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
|
+
Attributes:
|
|
20
|
+
k: The number of nearest neighbors to consider for classification.
|
|
21
|
+
std_transform: Whether to standardize the input data (default: True).
|
|
22
|
+
dataset_: The fitted dataset (standardized if std_transform is True).
|
|
23
|
+
labels_: The labels corresponding to the fitted dataset.
|
|
24
|
+
standarizationer_: The Standardizationer instance if std_transform is True.
|
|
25
|
+
|
|
26
|
+
Examples:
|
|
27
|
+
>>> dataset = [[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0]]
|
|
28
|
+
>>> labels = ['A', 'A', 'B', 'B']
|
|
29
|
+
>>> knn = KNN(k=3, std_transform=True).fit(dataset, labels)
|
|
30
|
+
>>> knn.predict([2.5, 3.5])
|
|
31
|
+
'A'
|
|
32
|
+
|
|
33
|
+
References:
|
|
34
|
+
1. Li Hang
|
|
35
|
+
2. Tan
|
|
36
|
+
3. Zhou
|
|
37
|
+
4. Murphy
|
|
38
|
+
5. Harrington
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
k: int
|
|
42
|
+
std_transform: bool = True
|
|
43
|
+
dataset_: Optional[list[list[float]]] = None
|
|
44
|
+
labels_: Optional[list[Any]] = None
|
|
45
|
+
standarizationer_: Optional[Standardizationer] = None
|
|
46
|
+
|
|
47
|
+
def fit(self, dataset: list[list[float]], labels: list[Any]) -> KNN:
|
|
48
|
+
"""
|
|
49
|
+
Fit the KNN model to the given dataset and labels.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
dataset: The input dataset to fit the model to.
|
|
53
|
+
labels: The labels corresponding to the input dataset.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
The fitted KNN instance.
|
|
57
|
+
"""
|
|
58
|
+
self.dataset_ = dataset
|
|
59
|
+
self.labels_ = labels
|
|
60
|
+
if self.std_transform:
|
|
61
|
+
self.standarizationer_ = Standardizationer()
|
|
62
|
+
self.dataset_ = self.standarizationer_.fit_transform(self.dataset_)
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
def predict(self, x: list[float]) -> Any:
|
|
66
|
+
"""
|
|
67
|
+
Predict the label of the input data.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
x: The input data to predict.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
The predicted label.
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
ValueError: If the model is not fitted yet.
|
|
77
|
+
"""
|
|
78
|
+
if self.dataset_ is None or self.labels_ is None:
|
|
79
|
+
raise ValueError("The model is not fitted yet!")
|
|
80
|
+
|
|
81
|
+
if self.std_transform:
|
|
82
|
+
if self.standarizationer_ is None:
|
|
83
|
+
raise ValueError("Cannot find the standardization!")
|
|
84
|
+
x = self.standarizationer_.transform([x])[0]
|
|
85
|
+
distances = [self._calculate_distance(x, point) for point in self.dataset_]
|
|
86
|
+
# get k-nearest neighbors' label
|
|
87
|
+
k_nearest_labels = [label for _, label in sorted(zip(distances, self.labels_), key=lambda x: x[0])][:: self.k]
|
|
88
|
+
label = Counter(k_nearest_labels).most_common(1)[0][0]
|
|
89
|
+
return label
|
|
90
|
+
|
|
91
|
+
@staticmethod
|
|
92
|
+
def _calculate_distance(x: list[float], y: list[float]) -> float:
|
|
93
|
+
"""
|
|
94
|
+
Calculate the Euclidean distance between two points using a numerically stable method.
|
|
95
|
+
|
|
96
|
+
This implementation avoids overflow by using the two-pass algorithm.
|
|
97
|
+
"""
|
|
98
|
+
assert len(x) == len(y), f"{x} and {y} have different length!"
|
|
99
|
+
|
|
100
|
+
# First pass: find the maximum absolute difference
|
|
101
|
+
max_diff = max(abs(xi - yi) for xi, yi in zip(x, y))
|
|
102
|
+
|
|
103
|
+
if math.isclose(max_diff, 0):
|
|
104
|
+
return 0.0 # All elements are identical
|
|
105
|
+
|
|
106
|
+
# Second pass: calculate the normalized sum of squares
|
|
107
|
+
sum_squares = sum(((xi - yi) / max_diff) ** 2 for xi, yi in zip(x, y))
|
|
108
|
+
|
|
109
|
+
return max_diff * math.sqrt(sum_squares)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass
|
|
113
|
+
class Standardizationer:
|
|
114
|
+
"""
|
|
115
|
+
A class for standardizing numerical datasets.
|
|
116
|
+
|
|
117
|
+
Provides methods to fit a standardization model to a dataset,
|
|
118
|
+
transform datasets using the fitted model, and perform both operations
|
|
119
|
+
in a single step.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
_means: list[float] = field(default_factory=list)
|
|
123
|
+
_stds: list[float] = field(default_factory=list)
|
|
124
|
+
_dimension: Optional[int] = None
|
|
125
|
+
|
|
126
|
+
def fit(self, dataset: list[list[float]]) -> Standardizationer:
|
|
127
|
+
"""
|
|
128
|
+
Fit the standardization model to the given dataset.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
dataset: The input dataset to fit the model to.
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
The fitted Standardizationer instance.
|
|
135
|
+
|
|
136
|
+
Raises:
|
|
137
|
+
ValueError: If the dataset has inconsistent dimensions.
|
|
138
|
+
"""
|
|
139
|
+
self._dimension = self._get_dataset_dimension(dataset)
|
|
140
|
+
self._means = self._dataset_column_means(dataset)
|
|
141
|
+
self._stds = self._dataset_column_stds(dataset)
|
|
142
|
+
return self
|
|
143
|
+
|
|
144
|
+
def transform(self, dataset: list[list[float]]) -> list[list[float]]:
|
|
145
|
+
"""
|
|
146
|
+
Transform the given dataset using the fitted standardization model.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
dataset: The input dataset to transform.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
The standardized dataset.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
ValueError: If the model has not been fitted yet.
|
|
156
|
+
"""
|
|
157
|
+
if self._dimension is None:
|
|
158
|
+
raise ValueError("The model is not fitted yet!")
|
|
159
|
+
return self.standardization(dataset)
|
|
160
|
+
|
|
161
|
+
def fit_transform(self, dataset: list[list[float]]) -> list[list[float]]:
|
|
162
|
+
"""
|
|
163
|
+
Fit the standardization model to the dataset and transform it in one step.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
dataset: The input dataset to fit and transform.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
The standardized dataset.
|
|
170
|
+
"""
|
|
171
|
+
self.fit(dataset)
|
|
172
|
+
return self.transform(dataset)
|
|
173
|
+
|
|
174
|
+
def standardization(self, dataset: list[list[float]]) -> list[list[float]]:
|
|
175
|
+
"""
|
|
176
|
+
Standardize the given numerical dataset.
|
|
177
|
+
The standardization is performed by subtracting the mean and dividing by the standard deviation for each feature.
|
|
178
|
+
When the standard deviation is 0, all the values in the column are the same,
|
|
179
|
+
here we set std to 1 to make every value in the column become 0 and avoid division by zero.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
dataset: The input dataset to standardize.
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
The standardized dataset.
|
|
186
|
+
|
|
187
|
+
Raises:
|
|
188
|
+
ValueError: If the model has not been fitted yet.
|
|
189
|
+
"""
|
|
190
|
+
if self._dimension is None:
|
|
191
|
+
raise ValueError("The model is not fitted yet!")
|
|
192
|
+
for j, column in enumerate(zip(*dataset)):
|
|
193
|
+
mean, std = self._means[j], self._stds[j]
|
|
194
|
+
# ref: https://github.com/scikit-learn/scikit-learn/blob/7389dbac82d362f296dc2746f10e43ffa1615660/sklearn/preprocessing/data.py#L70
|
|
195
|
+
if math.isclose(std, 0):
|
|
196
|
+
std = 1
|
|
197
|
+
for i, value in enumerate(column):
|
|
198
|
+
dataset[i][j] = (value - mean) / std
|
|
199
|
+
return dataset
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
def _get_dataset_dimension(dataset: list[list[float]]) -> int:
|
|
203
|
+
dimension = len(dataset[0])
|
|
204
|
+
if not all([len(row) == dimension for row in dataset]):
|
|
205
|
+
raise ValueError("All rows must have the same number of columns")
|
|
206
|
+
return dimension
|
|
207
|
+
|
|
208
|
+
@staticmethod
|
|
209
|
+
def _dataset_column_means(dataset: list[list[float]]) -> list[float]:
|
|
210
|
+
"""
|
|
211
|
+
Calculate vectors mean
|
|
212
|
+
"""
|
|
213
|
+
return [statistics.mean(column) for column in zip(*dataset)]
|
|
214
|
+
|
|
215
|
+
@staticmethod
|
|
216
|
+
def _dataset_column_stds(dataset: list[list[float]]) -> list[float]:
|
|
217
|
+
"""
|
|
218
|
+
Calculate vectors(every column) standard variance
|
|
219
|
+
"""
|
|
220
|
+
return [statistics.stdev(column) for column in zip(*dataset)]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
if __name__ == "__main__":
|
|
224
|
+
dataset: list[list[float]] = [[0.0], [1], [2], [3]]
|
|
225
|
+
labels: list[Any] = [0, 0, 1, 1]
|
|
226
|
+
knn = KNN(3).fit(dataset, labels)
|
|
227
|
+
print(knn.labels_)
|
|
228
|
+
print(knn.predict([1.1]))
|
|
@@ -5,8 +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
8
|
|
|
11
9
|
@dataclass
|
|
12
10
|
class ClusterTree:
|
|
@@ -73,6 +71,8 @@ class AGNES:
|
|
|
73
71
|
"""The number of clusters, specified by user."""
|
|
74
72
|
linkage: Literal["single", "complete", "average"] = "single"
|
|
75
73
|
"""The linkage method to use."""
|
|
74
|
+
distance_metric: Literal["euclidean"] = "euclidean"
|
|
75
|
+
"""The distance metric to use.(For now we only support euclidean)."""
|
|
76
76
|
distance_matrix_: list[list[float]] = field(default_factory=list)
|
|
77
77
|
"""The distance matrix."""
|
|
78
78
|
clusters_: list[ClusterTree] = field(default_factory=list)
|
|
@@ -146,7 +146,7 @@ class AGNES:
|
|
|
146
146
|
Get the distance between clusters c1 and c2 using the specified linkage method.
|
|
147
147
|
"""
|
|
148
148
|
distances = [
|
|
149
|
-
|
|
149
|
+
self._get_distance(dataset[i], dataset[j]) for i in cluster1.sample_indices for j in cluster2.sample_indices
|
|
150
150
|
]
|
|
151
151
|
|
|
152
152
|
if self.linkage == "single":
|
|
@@ -238,6 +238,13 @@ class AGNES:
|
|
|
238
238
|
for sample_index in cluster.sample_indices:
|
|
239
239
|
self.labels_[sample_index] = cluster_label
|
|
240
240
|
|
|
241
|
+
def _get_distance(self, x: list[float], y: list[float]) -> float:
|
|
242
|
+
assert len(x) == len(y), f"{x} and {y} have different length!"
|
|
243
|
+
if self.distance_metric == "euclidean":
|
|
244
|
+
return math.sqrt(sum(pow(x[i] - y[i], 2) for i in range(len(x))))
|
|
245
|
+
else:
|
|
246
|
+
raise ValueError(f"Distance metric {self.distance_metric} not supported!")
|
|
247
|
+
|
|
241
248
|
def plot_dendrogram(
|
|
242
249
|
self,
|
|
243
250
|
figure_name: str = "agnes_dendrogram.png",
|
|
@@ -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,6 +73,8 @@ 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,
|
|
@@ -294,6 +295,23 @@ class BisectingKmeans:
|
|
|
294
295
|
return centroid
|
|
295
296
|
|
|
296
297
|
|
|
298
|
+
def euclidean_distance(v1: list[float], v2: list[float]) -> float:
|
|
299
|
+
"""
|
|
300
|
+
Calculate the L2 distance between two vectors
|
|
301
|
+
|
|
302
|
+
"""
|
|
303
|
+
assert len(v1) == len(v2), f"{v1} and {v2} have different length!"
|
|
304
|
+
return math.sqrt(sum(pow(v1[i] - v2[i], 2) for i in range(len(v1))))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def sum_square_error(c: list[list[float]]) -> float:
|
|
308
|
+
"""
|
|
309
|
+
Calc the sum of squared errors.
|
|
310
|
+
"""
|
|
311
|
+
mean_c = [statistics.mean([v[i] for v in c]) for i in range(len(c[0]))]
|
|
312
|
+
return sum(euclidean_distance(mean_c, v) ** 2 for v in c)
|
|
313
|
+
|
|
314
|
+
|
|
297
315
|
if __name__ == "__main__":
|
|
298
316
|
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
317
|
k = 6
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
3
|
import logging
|
|
4
|
+
import math
|
|
4
5
|
|
|
5
6
|
from collections import deque
|
|
6
7
|
from dataclasses import dataclass, field
|
|
7
|
-
|
|
8
|
-
from toyml.utils.linear_algebra import euclidean_distance
|
|
8
|
+
from typing import Literal
|
|
9
9
|
|
|
10
10
|
logger = logging.getLogger(__name__)
|
|
11
11
|
|
|
@@ -26,6 +26,8 @@ class Dataset:
|
|
|
26
26
|
|
|
27
27
|
data: list[list[float]]
|
|
28
28
|
n: int = field(init=False)
|
|
29
|
+
distance_metric: Literal["euclidean"] = "euclidean"
|
|
30
|
+
"""The distance metric to use.(For now we only support euclidean)."""
|
|
29
31
|
distance_matrix_: list[list[float]] = field(init=False)
|
|
30
32
|
|
|
31
33
|
def __post_init__(self) -> None:
|
|
@@ -36,7 +38,7 @@ class Dataset:
|
|
|
36
38
|
dist_mat = [[0.0 for _ in range(self.n)] for _ in range(self.n)]
|
|
37
39
|
for i in range(self.n):
|
|
38
40
|
for j in range(i, self.n):
|
|
39
|
-
dist_mat[i][j] =
|
|
41
|
+
dist_mat[i][j] = self._get_distance(self.data[i], self.data[j])
|
|
40
42
|
dist_mat[j][i] = dist_mat[i][j]
|
|
41
43
|
return dist_mat
|
|
42
44
|
|
|
@@ -49,7 +51,7 @@ class Dataset:
|
|
|
49
51
|
eps: The maximum distance between two samples for one to be considered as in the neighborhood of the other.
|
|
50
52
|
|
|
51
53
|
Returns:
|
|
52
|
-
The indices of the neighbors(Don't include the point itself).
|
|
54
|
+
The indices of the neighbors (Don't include the point itself).
|
|
53
55
|
"""
|
|
54
56
|
return [j for j in range(self.n) if i != j and self.distance_matrix_[i][j] <= eps]
|
|
55
57
|
|
|
@@ -75,6 +77,13 @@ class Dataset:
|
|
|
75
77
|
noises.append(i)
|
|
76
78
|
return core_objects, noises
|
|
77
79
|
|
|
80
|
+
def _get_distance(self, x: list[float], y: list[float]) -> float:
|
|
81
|
+
assert len(x) == len(y), f"{x} and {y} have different length!"
|
|
82
|
+
if self.distance_metric == "euclidean":
|
|
83
|
+
return math.sqrt(sum(pow(x[i] - y[i], 2) for i in range(len(x))))
|
|
84
|
+
else:
|
|
85
|
+
raise ValueError(f"Distance metric {self.distance_metric} not supported!")
|
|
86
|
+
|
|
78
87
|
|
|
79
88
|
@dataclass
|
|
80
89
|
class DBSCAN:
|
|
@@ -7,8 +7,6 @@ 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
|
-
|
|
12
10
|
logger = logging.getLogger(__name__)
|
|
13
11
|
|
|
14
12
|
|
|
@@ -61,6 +59,8 @@ class Kmeans:
|
|
|
61
59
|
"""The method to initialize the centroids."""
|
|
62
60
|
random_seed: Optional[int] = None
|
|
63
61
|
"""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,6 +126,13 @@ 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
|
+
|
|
129
136
|
def _get_dataset_labels(self, dataset: list[list[float]]) -> list[int]:
|
|
130
137
|
labels = [-1] * len(dataset)
|
|
131
138
|
for cluster_label, cluster in self.clusters.items():
|
|
@@ -207,16 +214,15 @@ class Kmeans:
|
|
|
207
214
|
The minimum square distance
|
|
208
215
|
"""
|
|
209
216
|
return min(
|
|
210
|
-
(
|
|
217
|
+
(self._get_distance(point, centroid) ** 2 for centroid in self.centroids.values() if centroid),
|
|
211
218
|
default=math.inf,
|
|
212
219
|
)
|
|
213
220
|
|
|
214
|
-
|
|
215
|
-
def _get_centroid_label(point: list[float], centroids: dict[int, list[float]]) -> int:
|
|
221
|
+
def _get_centroid_label(self, point: list[float], centroids: dict[int, list[float]]) -> int:
|
|
216
222
|
"""
|
|
217
223
|
Get the label of the centroid, which is closest to the point
|
|
218
224
|
"""
|
|
219
|
-
distances = [(i,
|
|
225
|
+
distances = [(i, self._get_distance(point, centroid)) for i, centroid in centroids.items()]
|
|
220
226
|
return min(distances, key=lambda x: x[1])[0]
|
|
221
227
|
|
|
222
228
|
def _get_clusters(self, dataset: list[list[float]]) -> dict[int, list[int]]:
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import abc
|
|
4
|
+
import logging
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Any, Callable, List, Optional, Type
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class BaseWeakLeaner:
|
|
16
|
+
@abc.abstractmethod
|
|
17
|
+
def fit(self, dataset: list[list[float]], weights: list[float], labels: list[int]) -> BaseWeakLeaner:
|
|
18
|
+
raise NotImplementedError
|
|
19
|
+
|
|
20
|
+
@abc.abstractmethod
|
|
21
|
+
def predict(self, x: list[float]) -> int:
|
|
22
|
+
raise NotImplementedError
|
|
23
|
+
|
|
24
|
+
@abc.abstractmethod
|
|
25
|
+
def get_predict_labels(self) -> list[int]:
|
|
26
|
+
raise NotImplementedError
|
|
27
|
+
|
|
28
|
+
@abc.abstractmethod
|
|
29
|
+
def get_error_rate(self) -> float:
|
|
30
|
+
raise NotImplementedError
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class AdaBoost:
|
|
35
|
+
"""
|
|
36
|
+
The implementation of AdaBoost algorithm.
|
|
37
|
+
|
|
38
|
+
Ref:
|
|
39
|
+
1. Li Hang
|
|
40
|
+
2. Zhou
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
weak_learner: Type[BaseWeakLeaner]
|
|
44
|
+
"""
|
|
45
|
+
The weak learner to be used in the AdaBoost algorithm.
|
|
46
|
+
"""
|
|
47
|
+
n_weak_learner: int = 5
|
|
48
|
+
"""
|
|
49
|
+
The number of weak learners to be used in the AdaBoost algorithm.
|
|
50
|
+
"""
|
|
51
|
+
predict_labels_: Optional[list[int]] = None
|
|
52
|
+
"""
|
|
53
|
+
The prediction labels of the training dataset.
|
|
54
|
+
"""
|
|
55
|
+
training_error_rate_: Optional[float] = None
|
|
56
|
+
"""
|
|
57
|
+
The error rate of the training dataset.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
_n: int = -1
|
|
61
|
+
"""
|
|
62
|
+
The number of samples in the training dataset.
|
|
63
|
+
"""
|
|
64
|
+
_labels: list[int] = field(default_factory=list)
|
|
65
|
+
"""
|
|
66
|
+
The labels of the training dataset.
|
|
67
|
+
"""
|
|
68
|
+
_weights: list[float] = field(default_factory=list)
|
|
69
|
+
"""
|
|
70
|
+
The weights of sampels in the training dataset.
|
|
71
|
+
"""
|
|
72
|
+
_base_clf_labels: list[list[int]] = field(default_factory=list)
|
|
73
|
+
"""
|
|
74
|
+
The prediction labels of the base classifiers.
|
|
75
|
+
"""
|
|
76
|
+
_weak_learner_predicts: List[Callable[..., Any]] = field(default_factory=list)
|
|
77
|
+
"""
|
|
78
|
+
The prediction functions of the weak learners.
|
|
79
|
+
"""
|
|
80
|
+
_alphas: list[float] = field(default_factory=list)
|
|
81
|
+
"""
|
|
82
|
+
The alpha values of the weak learners.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def fit(
|
|
86
|
+
self,
|
|
87
|
+
dataset: list[list[float]],
|
|
88
|
+
labels: list[int],
|
|
89
|
+
) -> AdaBoost:
|
|
90
|
+
"""
|
|
91
|
+
Fit the AdaBoost model.
|
|
92
|
+
"""
|
|
93
|
+
self._labels = labels
|
|
94
|
+
# for model training(Gm)
|
|
95
|
+
self._n = len(labels)
|
|
96
|
+
self._weights: Any = [1.0 / self._n] * self._n
|
|
97
|
+
# we use -2 to initialize the class which can handle cases
|
|
98
|
+
# such as multi-classes(0, 1, 2, ...) and binary classes(-1, 1)
|
|
99
|
+
self._base_clf_labels = [[-2] * self._n for _ in range(self.n_weak_learner)]
|
|
100
|
+
# base clf models
|
|
101
|
+
self._weak_learner_predicts: List[Callable[..., int]] = []
|
|
102
|
+
self._alphas = [0.0] * self.n_weak_learner
|
|
103
|
+
|
|
104
|
+
for m in range(self.n_weak_learner):
|
|
105
|
+
model = self.weak_learner().fit(dataset, self._weights, self._labels)
|
|
106
|
+
self._base_clf_labels[m] = model.get_predict_labels()
|
|
107
|
+
self._weak_learner_predicts.append(model.predict)
|
|
108
|
+
error_rate = model.get_error_rate()
|
|
109
|
+
# Warning when the error rate is too large
|
|
110
|
+
if error_rate > 0.5:
|
|
111
|
+
logger.warning(f"Weak learner error rate = {error_rate} < 0.5")
|
|
112
|
+
alpha = 0.5 * math.log((1 - error_rate) / error_rate)
|
|
113
|
+
self._alphas[m] = alpha
|
|
114
|
+
# update the weights
|
|
115
|
+
weights = [0.0] * self._n
|
|
116
|
+
for i in range(self._n):
|
|
117
|
+
weights[i] = self._weights[i] * math.exp(-alpha * self._labels[i] * self._base_clf_labels[m][i])
|
|
118
|
+
self._weights = [weight / sum(weights) for weight in weights]
|
|
119
|
+
# collect training dataset result
|
|
120
|
+
self.predict_labels_ = [self.predict(x) for x in dataset]
|
|
121
|
+
self.training_error_rate_ = sum(self.predict_labels_[i] != self._labels[i] for i in range(self._n)) / self._n
|
|
122
|
+
return self
|
|
123
|
+
|
|
124
|
+
def predict(self, x: list[float]) -> int:
|
|
125
|
+
"""
|
|
126
|
+
Predict the label of the input sample.
|
|
127
|
+
"""
|
|
128
|
+
ensemble_predict = 0
|
|
129
|
+
for m in range(self.n_weak_learner):
|
|
130
|
+
model_predict = self._weak_learner_predicts[m]
|
|
131
|
+
ensemble_predict += self._alphas[m] * model_predict(x)
|
|
132
|
+
if ensemble_predict >= 0:
|
|
133
|
+
return 1
|
|
134
|
+
else:
|
|
135
|
+
return -1
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass
|
|
139
|
+
class OneDimensionClassifier(BaseWeakLeaner):
|
|
140
|
+
"""
|
|
141
|
+
Binary classifier with one dimension feature.
|
|
142
|
+
|
|
143
|
+
Ref: Li Hang, 1 ed, E8.1.3
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
class SignMode(str, Enum):
|
|
147
|
+
POS_NEG = "POS_NEG"
|
|
148
|
+
NEG_POS = "NEG_POS"
|
|
149
|
+
|
|
150
|
+
_sign_mode: SignMode = SignMode.POS_NEG
|
|
151
|
+
_best_cut: float = math.inf
|
|
152
|
+
error_rate_: float = math.inf
|
|
153
|
+
predict_labels_: Optional[list[int]] = None
|
|
154
|
+
|
|
155
|
+
def fit(
|
|
156
|
+
self,
|
|
157
|
+
dataset: list[list[float]],
|
|
158
|
+
weights: list[float],
|
|
159
|
+
labels: list[int],
|
|
160
|
+
) -> OneDimensionClassifier:
|
|
161
|
+
"""
|
|
162
|
+
Fit the one-dimension classifier.
|
|
163
|
+
"""
|
|
164
|
+
# search for the best cut point
|
|
165
|
+
sign_mode, best_cut, best_error_rate = self.get_best_cut(dataset, weights, labels)
|
|
166
|
+
self.error_rate_ = best_error_rate
|
|
167
|
+
self._best_cut = best_cut
|
|
168
|
+
self._sign_mode = sign_mode
|
|
169
|
+
# get labels
|
|
170
|
+
self.predict_labels_ = [0] * len(labels)
|
|
171
|
+
for i, x in enumerate(dataset):
|
|
172
|
+
self.predict_labels_[i] = self.predict(x)
|
|
173
|
+
return self
|
|
174
|
+
|
|
175
|
+
def predict(self, x: list[float]) -> int:
|
|
176
|
+
"""
|
|
177
|
+
Predict the label of the input sample.
|
|
178
|
+
"""
|
|
179
|
+
if self._best_cut is None:
|
|
180
|
+
raise ValueError("The model is not fitted yet!")
|
|
181
|
+
if self._sign_mode == "POS_NEG":
|
|
182
|
+
if x[0] <= self._best_cut:
|
|
183
|
+
return 1
|
|
184
|
+
else:
|
|
185
|
+
return -1
|
|
186
|
+
if x[0] <= self._best_cut:
|
|
187
|
+
return -1
|
|
188
|
+
else:
|
|
189
|
+
return 1
|
|
190
|
+
|
|
191
|
+
def get_error_rate(self) -> float:
|
|
192
|
+
"""
|
|
193
|
+
Get the error rate of the training dataset.
|
|
194
|
+
"""
|
|
195
|
+
if self.error_rate_ is None:
|
|
196
|
+
raise ValueError("The model is not fitted yet!")
|
|
197
|
+
return self.error_rate_
|
|
198
|
+
|
|
199
|
+
def get_predict_labels(self) -> list[int]:
|
|
200
|
+
"""
|
|
201
|
+
Get the prediction labels of the training dataset.
|
|
202
|
+
"""
|
|
203
|
+
if self.predict_labels_ is None:
|
|
204
|
+
raise ValueError("The model is not fitted yet!")
|
|
205
|
+
return self.predict_labels_
|
|
206
|
+
|
|
207
|
+
@staticmethod
|
|
208
|
+
def _get_candidate_cuts(points: list[float]) -> list[float]:
|
|
209
|
+
"""
|
|
210
|
+
Get the candidate cuts of the training dataset.
|
|
211
|
+
"""
|
|
212
|
+
min_x_int = math.floor(min(points))
|
|
213
|
+
max_x_int = math.ceil(max(points))
|
|
214
|
+
return [i + 0.5 for i in range(min_x_int, max_x_int)]
|
|
215
|
+
|
|
216
|
+
def get_best_cut(
|
|
217
|
+
self, dataset: list[list[float]], weights: list[float], labels: list[int]
|
|
218
|
+
) -> tuple[SignMode, float, float]:
|
|
219
|
+
"""
|
|
220
|
+
Get the best cut of the training dataset.
|
|
221
|
+
"""
|
|
222
|
+
points = [x[0] for x in dataset]
|
|
223
|
+
candidate_cuts = self._get_candidate_cuts(points)
|
|
224
|
+
# (func_mode, cut, error_rate)
|
|
225
|
+
candidate_cuts_result = []
|
|
226
|
+
for cut in candidate_cuts:
|
|
227
|
+
pos_neg_error_rate = self._get_cut_error_rate(cut, points, weights, labels, self.SignMode.POS_NEG)
|
|
228
|
+
neg_pos_error_rate = self._get_cut_error_rate(cut, points, weights, labels, self.SignMode.NEG_POS)
|
|
229
|
+
candidate_cuts_result.extend(
|
|
230
|
+
[(self.SignMode.POS_NEG, cut, pos_neg_error_rate), (self.SignMode.NEG_POS, cut, neg_pos_error_rate)]
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
# sorted by error rate
|
|
234
|
+
best_cut_result = sorted(candidate_cuts_result, key=lambda x: x[2])[0]
|
|
235
|
+
sign_mode, best_cut, best_error_rate = best_cut_result
|
|
236
|
+
return sign_mode, best_cut, best_error_rate
|
|
237
|
+
|
|
238
|
+
def _get_cut_error_rate(
|
|
239
|
+
self,
|
|
240
|
+
cut: float,
|
|
241
|
+
points: list[float],
|
|
242
|
+
weights: list[float],
|
|
243
|
+
labels: list[int],
|
|
244
|
+
sign_mode: SignMode,
|
|
245
|
+
) -> float:
|
|
246
|
+
"""
|
|
247
|
+
Get the error rate of the training dataset.
|
|
248
|
+
"""
|
|
249
|
+
error_rate = 0.0
|
|
250
|
+
for i, x in enumerate(points):
|
|
251
|
+
if sign_mode == self.SignMode.POS_NEG:
|
|
252
|
+
if x <= cut and labels[i] != 1 or x > cut and labels[i] != -1:
|
|
253
|
+
error_rate += weights[i]
|
|
254
|
+
else:
|
|
255
|
+
if x <= cut and labels[i] != -1 or x > cut and labels[i] != 1:
|
|
256
|
+
error_rate += weights[i]
|
|
257
|
+
return error_rate
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
if __name__ == "__main__":
|
|
261
|
+
dataset_demo: list[list[float]] = [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
|
|
262
|
+
labels_demo: list[int] = [1, 1, 1, -1, -1, -1, 1, 1, 1, -1]
|
|
263
|
+
ada = AdaBoost(weak_learner=OneDimensionClassifier, n_weak_learner=3).fit(dataset_demo, labels_demo)
|
|
264
|
+
print(f"Training dataset prediction labels: {ada.predict_labels_}")
|
|
265
|
+
print(f"Training dataset error rate: {ada.training_error_rate_}")
|
|
266
|
+
test_sample = [1.5]
|
|
267
|
+
print(f"The label of {test_sample} is {ada.predict(test_sample)}")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: toyml
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.0rc0
|
|
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)
|
|
@@ -18,7 +18,4 @@ toyml/clustering/bisect_kmeans.py
|
|
|
18
18
|
toyml/clustering/dbscan.py
|
|
19
19
|
toyml/clustering/kmeans.py
|
|
20
20
|
toyml/ensemble/__init__.py
|
|
21
|
-
toyml/ensemble/ada_boost.py
|
|
22
|
-
toyml/utils/__init__.py
|
|
23
|
-
toyml/utils/linear_algebra.py
|
|
24
|
-
toyml/utils/types.py
|
|
21
|
+
toyml/ensemble/ada_boost.py
|
|
@@ -1,67 +0,0 @@
|
|
|
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]))
|
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
import math
|
|
2
|
-
|
|
3
|
-
from typing import Any, Callable, List
|
|
4
|
-
|
|
5
|
-
from toyml.utils.types import DataSet, Label, Labels, Weights
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class AdaBoost:
|
|
9
|
-
"""
|
|
10
|
-
The implementation of AdaBoost algorithm.
|
|
11
|
-
|
|
12
|
-
Ref:
|
|
13
|
-
1. Li Hang
|
|
14
|
-
2. Zhou
|
|
15
|
-
"""
|
|
16
|
-
|
|
17
|
-
def __init__(
|
|
18
|
-
self,
|
|
19
|
-
dataset: DataSet,
|
|
20
|
-
labels: Labels,
|
|
21
|
-
base_clf: Callable[..., Any], # TODO: change to clf class type
|
|
22
|
-
clf_num: int = 5,
|
|
23
|
-
) -> None:
|
|
24
|
-
self._dataset = dataset
|
|
25
|
-
self._labels = labels
|
|
26
|
-
self._base_clf = base_clf
|
|
27
|
-
self._clf_num = clf_num
|
|
28
|
-
# for model training(Gm)
|
|
29
|
-
self._n = len(labels)
|
|
30
|
-
self._weights: Any = [1.0 / self._n] * self._n
|
|
31
|
-
# we use -2 to initialize the class which can handle cases
|
|
32
|
-
# such as multi-classes(0, 1, 2, ...) and binary classes(-1, 1)
|
|
33
|
-
self._base_clf_results = [[-2] * self._n for _ in range(self._clf_num)]
|
|
34
|
-
# base clf models
|
|
35
|
-
self._sub_clf_models: List[Callable[..., Any]] = []
|
|
36
|
-
self._alphas: Any = [0] * self._clf_num
|
|
37
|
-
|
|
38
|
-
def fit(self) -> None:
|
|
39
|
-
for m in range(self._clf_num):
|
|
40
|
-
model = self._base_clf(self._dataset, self._weights, self._labels)
|
|
41
|
-
model.fit()
|
|
42
|
-
self._base_clf_results[m] = model.get_training_results()
|
|
43
|
-
self._sub_clf_models.append(model.predict)
|
|
44
|
-
error_rate = model.get_error_rate()
|
|
45
|
-
# Warning when the error rate is too large
|
|
46
|
-
if error_rate > 0.5:
|
|
47
|
-
Warning(f"Base Clf error rate = {error_rate}!")
|
|
48
|
-
alpha = 0.5 * math.log((1 - error_rate) / error_rate)
|
|
49
|
-
self._alphas[m] = alpha
|
|
50
|
-
# update the weights
|
|
51
|
-
weights = [0] * self._n
|
|
52
|
-
for i in range(self._n):
|
|
53
|
-
weights[i] = self._weights[i] * math.exp(-alpha * self._labels[i] * self._base_clf_results[m][i])
|
|
54
|
-
self._weights = [weight / sum(weights) for weight in weights]
|
|
55
|
-
|
|
56
|
-
def get_training_result(self) -> Labels:
|
|
57
|
-
predictions = [-2] * self._n
|
|
58
|
-
for i in range(self._n):
|
|
59
|
-
result = 0
|
|
60
|
-
for m in range(self._clf_num):
|
|
61
|
-
result += self._alphas[m] * self._base_clf_results[m][i]
|
|
62
|
-
if result >= 0:
|
|
63
|
-
predictions[i] = 1
|
|
64
|
-
else:
|
|
65
|
-
predictions[i] = -1
|
|
66
|
-
training_error = sum(predictions[i] != self._labels[i] for i in range(self._n)) / self._n
|
|
67
|
-
print("Training Error: ", training_error)
|
|
68
|
-
print("Predictions: ", predictions)
|
|
69
|
-
return predictions
|
|
70
|
-
|
|
71
|
-
def predict(self, x: float) -> Label:
|
|
72
|
-
result = 0
|
|
73
|
-
for m in range(self._clf_num):
|
|
74
|
-
model_predict = self._sub_clf_models[m]
|
|
75
|
-
result += self._alphas[m] * model_predict(x)
|
|
76
|
-
if result >= 0:
|
|
77
|
-
return 1
|
|
78
|
-
else:
|
|
79
|
-
return -1
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
class OneDimClf:
|
|
83
|
-
"""
|
|
84
|
-
Binary clf with only one feature.
|
|
85
|
-
|
|
86
|
-
Ref: Li Hang, 1ed, E8.1.3
|
|
87
|
-
"""
|
|
88
|
-
|
|
89
|
-
def __init__(self, dataset: DataSet, weights: Weights, labels: Labels) -> None:
|
|
90
|
-
self._dataset = dataset
|
|
91
|
-
self._xs = [x[0] for x in self._dataset]
|
|
92
|
-
self._weights = weights
|
|
93
|
-
self._labels = labels
|
|
94
|
-
self._n = len(self._labels)
|
|
95
|
-
# for training and prediction
|
|
96
|
-
self._error_rate = math.inf
|
|
97
|
-
self._best_cut = math.inf
|
|
98
|
-
self._func_mode = "pos-neg"
|
|
99
|
-
|
|
100
|
-
def fit(self) -> None:
|
|
101
|
-
min_x_int = math.floor(min(self._xs))
|
|
102
|
-
max_x_int = math.ceil(max(self._xs))
|
|
103
|
-
# search for the best cut point
|
|
104
|
-
best_cut: float = min_x_int
|
|
105
|
-
best_error_rate = math.inf
|
|
106
|
-
# pos-neg: 1, -1(default)
|
|
107
|
-
for i in range(min_x_int, max_x_int):
|
|
108
|
-
cut = i + 0.5
|
|
109
|
-
error_rate: float = 0
|
|
110
|
-
for j, x in enumerate(self._xs):
|
|
111
|
-
if x <= cut and self._labels[j] != 1:
|
|
112
|
-
error_rate += self._weights[j]
|
|
113
|
-
if x > cut and self._labels[j] != -1:
|
|
114
|
-
error_rate += self._weights[j]
|
|
115
|
-
if error_rate < best_error_rate:
|
|
116
|
-
best_error_rate = error_rate
|
|
117
|
-
best_cut = cut
|
|
118
|
-
# neg-pos: -1, 1
|
|
119
|
-
for i in range(min_x_int, max_x_int):
|
|
120
|
-
cut = i + 0.5
|
|
121
|
-
error_rate = 0
|
|
122
|
-
for j, x in enumerate(self._xs):
|
|
123
|
-
if x <= cut and self._labels[j] != -1:
|
|
124
|
-
error_rate += self._weights[j]
|
|
125
|
-
if x > cut and self._labels[j] != 1:
|
|
126
|
-
error_rate += self._weights[j]
|
|
127
|
-
if error_rate < best_error_rate:
|
|
128
|
-
self._func_mode = "neg-pos"
|
|
129
|
-
best_error_rate = error_rate
|
|
130
|
-
best_cut = cut
|
|
131
|
-
self._error_rate = best_error_rate
|
|
132
|
-
self._best_cut = best_cut
|
|
133
|
-
|
|
134
|
-
def get_error_rate(self) -> float:
|
|
135
|
-
return self._error_rate
|
|
136
|
-
|
|
137
|
-
def get_training_results(self) -> Labels:
|
|
138
|
-
results = [-2] * self._n
|
|
139
|
-
for i, x in enumerate(self._xs):
|
|
140
|
-
results[i] = self.predict(x)
|
|
141
|
-
return results
|
|
142
|
-
|
|
143
|
-
def predict(self, x: float) -> Label:
|
|
144
|
-
if self._func_mode == "pos-neg":
|
|
145
|
-
if x <= self._best_cut:
|
|
146
|
-
return 1
|
|
147
|
-
else:
|
|
148
|
-
return -1
|
|
149
|
-
if x <= self._best_cut:
|
|
150
|
-
return -1
|
|
151
|
-
else:
|
|
152
|
-
return 1
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
if __name__ == "__main__":
|
|
156
|
-
dataset: DataSet = [[0.0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
|
|
157
|
-
labels: Labels = [1, 1, 1, -1, -1, -1, 1, 1, 1, -1]
|
|
158
|
-
M: int = 3
|
|
159
|
-
ada = AdaBoost(dataset, labels, OneDimClf, M)
|
|
160
|
-
ada.fit()
|
|
161
|
-
ada.get_training_result()
|
|
162
|
-
TEST_X = 1.5
|
|
163
|
-
print(f"The label of {TEST_X} is {ada.predict(TEST_X)}")
|
|
File without changes
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import math
|
|
2
|
-
|
|
3
|
-
from toyml.utils.types import DataSet, Vector, Vectors
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
# Vector operations
|
|
7
|
-
def vectors_minus(v1: Vector, v2: Vector) -> Vector:
|
|
8
|
-
"""
|
|
9
|
-
v1 - v2
|
|
10
|
-
"""
|
|
11
|
-
assert len(v1) == len(v2), """Can not minus \
|
|
12
|
-
(vectors have different dimensions)"""
|
|
13
|
-
d = len(v1)
|
|
14
|
-
v = [0.0] * d
|
|
15
|
-
for i in range(d):
|
|
16
|
-
v[i] = v1[i] - v2[i]
|
|
17
|
-
return v
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
def vectors_mean(vectors: Vectors) -> Vector:
|
|
21
|
-
"""
|
|
22
|
-
Calculate vectors mean
|
|
23
|
-
|
|
24
|
-
Example1:
|
|
25
|
-
>>> vectors_mean([[1.0, 2.0], [3.0, 4.0]])
|
|
26
|
-
[2.0, 3.0]
|
|
27
|
-
"""
|
|
28
|
-
d = len(vectors[0])
|
|
29
|
-
n = len(vectors)
|
|
30
|
-
v = [0.0] * d
|
|
31
|
-
for i in range(d):
|
|
32
|
-
v[i] = sum(vector[i] for vector in vectors) / n
|
|
33
|
-
return v
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def vectors_std(vectors: Vectors) -> Vector:
|
|
37
|
-
"""
|
|
38
|
-
Calculate vectors(every column) standard variance
|
|
39
|
-
"""
|
|
40
|
-
d = len(vectors[0])
|
|
41
|
-
n = len(vectors)
|
|
42
|
-
means = vectors_mean(vectors)
|
|
43
|
-
v = [0.0] * d
|
|
44
|
-
for i in range(d):
|
|
45
|
-
v[i] = math.sqrt(sum((vector[i] - means[i]) ** 2 for vector in vectors) / n)
|
|
46
|
-
return v
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
"""Distance metrics"""
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
# p = 1
|
|
53
|
-
def manhattan_distance(v1: Vector, v2: Vector) -> float:
|
|
54
|
-
diffs = vectors_minus(v1, v2)
|
|
55
|
-
return sum(abs(diff) for diff in diffs)
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
# p = 2
|
|
59
|
-
def euclidean_distance(v1: Vector, v2: Vector) -> float:
|
|
60
|
-
"""
|
|
61
|
-
Calculate the L2 distance between two vectors
|
|
62
|
-
|
|
63
|
-
Example1:
|
|
64
|
-
>>> euclidean_distance([0.0, 0.0], [3.0, 4.0])
|
|
65
|
-
5.0
|
|
66
|
-
"""
|
|
67
|
-
assert len(v1) == len(v2), f"{v1} and {v2} have different length!"
|
|
68
|
-
return math.sqrt(sum(pow(v1[i] - v2[i], 2) for i in range(len(v1))))
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def sum_square_error(c: Vectors) -> float:
|
|
72
|
-
"""
|
|
73
|
-
Calc the sum of squared errors.
|
|
74
|
-
"""
|
|
75
|
-
mean_c = vectors_mean(c)
|
|
76
|
-
return sum(euclidean_distance(mean_c, v) ** 2 for v in c)
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
# data transformation
|
|
80
|
-
def standardization(dataset: DataSet, means: Vector, stds: Vector) -> None:
|
|
81
|
-
"""
|
|
82
|
-
The standardization of numerical dataset.
|
|
83
|
-
"""
|
|
84
|
-
d = len(means)
|
|
85
|
-
n = len(dataset)
|
|
86
|
-
for j in range(d):
|
|
87
|
-
for i in range(n):
|
|
88
|
-
ele = dataset[i][j]
|
|
89
|
-
dataset[i][j] = (ele - means[j]) / stds[j]
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
from typing import List, Union
|
|
2
|
-
|
|
3
|
-
"""General"""
|
|
4
|
-
Number = Union[float, int]
|
|
5
|
-
|
|
6
|
-
"""DataSet"""
|
|
7
|
-
# float vectors
|
|
8
|
-
Vector = List[float]
|
|
9
|
-
Vectors = List[Vector]
|
|
10
|
-
|
|
11
|
-
# dataset
|
|
12
|
-
DataSet = List[Vector]
|
|
13
|
-
|
|
14
|
-
# labels
|
|
15
|
-
Label = int
|
|
16
|
-
Labels = List[Label]
|
|
17
|
-
|
|
18
|
-
"""clustering"""
|
|
19
|
-
# cluster(we store sample index in cluster)
|
|
20
|
-
Cluster = List[int]
|
|
21
|
-
# clusters
|
|
22
|
-
Clusters = List[Cluster]
|
|
23
|
-
|
|
24
|
-
# distance matrix
|
|
25
|
-
DistMat = List[List[float]]
|
|
26
|
-
|
|
27
|
-
"""classification"""
|
|
28
|
-
# classifier with sample weight considered
|
|
29
|
-
Weights = List[Number]
|
|
30
|
-
|
|
31
|
-
"""Special"""
|
|
32
|
-
|
|
33
|
-
# Sometimes, we use Any to fight for the cases where pyright
|
|
34
|
-
# not works.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|