-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
517 lines (427 loc) · 16.9 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
from __future__ import annotations
import collections
import csv
import datetime
import enum
from math import isclose
from pathlib import Path
from typing import (
cast,
Any,
Optional,
Union,
Iterator,
Iterable,
Counter,
Callable,
Protocol,
)
import weakref
class Sample:
"""Abstract superclass for all samples."""
def __init__(
self,
sepal_length: float,
sepal_width: float,
petal_length: float,
petal_width: float,
) -> None:
self.sepal_length = sepal_length
self.sepal_width = sepal_width
self.petal_length = petal_length
self.petal_width = petal_width
def __eq__(self, other: Any) -> bool:
if type(other) != type(self):
return False
other = cast(Sample, other)
return all(
[
self.sepal_length == other.sepal_length,
self.sepal_width == other.sepal_width,
self.petal_length == other.petal_length,
self.petal_width == other.petal_width,
]
)
@property
def attr_dict(self) -> dict[str, str]:
return dict(
sepal_length=f"{self.sepal_length!r}",
sepal_width=f"{self.sepal_width!r}",
petal_length=f"{self.petal_length!r}",
petal_width=f"{self.petal_width!r}",
)
def __repr__(self) -> str:
base_attributes = self.attr_dict
attrs = ", ".join(f"{k}={v}" for k, v in base_attributes.items())
return f"{self.__class__.__name__}({attrs})"
class Purpose(enum.IntEnum):
Classification = 0
Testing = 1
Training = 2
class KnownSample(Sample):
"""Represents a sample of testing or training data, the species is set once
The purpose determines if it can or cannot be classified.
"""
def __init__(
self,
sepal_length: float,
sepal_width: float,
petal_length: float,
petal_width: float,
purpose: int,
species: str,
) -> None:
purpose_enum = Purpose(purpose)
if purpose_enum not in {Purpose.Training, Purpose.Testing}:
raise ValueError(f"Invalid purpose: {purpose!r}: {purpose_enum}")
super().__init__(
sepal_length=sepal_length,
sepal_width=sepal_width,
petal_length=petal_length,
petal_width=petal_width,
)
self.purpose = purpose_enum
self.species = species
self._classification: Optional[str] = None
def matches(self) -> bool:
return self.species == self.classification
@property
def classification(self) -> Optional[str]:
if self.purpose == Purpose.Testing:
return self._classification
else:
raise AttributeError(f"Training samples have no classification")
@classification.setter
def classification(self, value: str) -> None:
if self.purpose == Purpose.Testing:
self._classification = value
else:
raise AttributeError(f"Training samples cannot be classified")
def __repr__(self) -> str:
base_attributes = self.attr_dict
base_attributes["purpose"] = f"{self.purpose.value}"
base_attributes["species"] = f"{self.species!r}"
if self.purpose == Purpose.Testing and self._classification:
base_attributes["classification"] = f"{self._classification!r}"
attrs = ", ".join(f"{k}={v}" for k, v in base_attributes.items())
return f"{self.__class__.__name__}({attrs})"
class UnknownSample(Sample):
"""A sample provided by a User, to be classified."""
def __init__(
self,
sepal_length: float,
sepal_width: float,
petal_length: float,
petal_width: float,
) -> None:
super().__init__(
sepal_length=sepal_length,
sepal_width=sepal_width,
petal_length=petal_length,
petal_width=petal_width,
)
self._classification: Optional[str] = None
@property
def classification(self) -> Optional[str]:
return self._classification
@classification.setter
def classification(self, value: str) -> None:
self._classification = value
def __repr__(self) -> str:
base_attributes = self.attr_dict
base_attributes["classification"] = f"{self.classification!r}"
attrs = ", ".join(f"{k}={v}" for k, v in base_attributes.items())
return f"{self.__class__.__name__}({attrs})"
class Distance:
"""A distance computation"""
def distance(self, s1: Sample, s2: Sample) -> float:
raise NotImplementedError
class Chebyshev(Distance):
"""
Computes the Chebyshev distance between two samples.
::
>>> from math import isclose
>>> from model import KnownSample, Purpose, UnknownSample, Chebyshev
>>> s1 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa",
... purpose=Purpose.Training)
>>> u = UnknownSample(**{"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4})
>>> algorithm = Chebyshev()
>>> isclose(3.3, algorithm.distance(s1, u))
True
"""
def distance(self, s1: Sample, s2: Sample) -> float:
return max(
[
abs(s1.sepal_length - s2.sepal_length),
abs(s1.sepal_width - s2.sepal_width),
abs(s1.petal_length - s2.petal_length),
abs(s1.petal_width - s2.petal_width),
]
)
class Minkowski(Distance):
"""An abstraction to provide a way to implement Manhattan and Euclidean."""
m: int
def distance(self, s1: Sample, s2: Sample) -> float:
return (
sum(
[
abs(s1.sepal_length - s2.sepal_length) ** self.m,
abs(s1.sepal_width - s2.sepal_width) ** self.m,
abs(s1.petal_length - s2.petal_length) ** self.m,
abs(s1.petal_width - s2.petal_width) ** self.m,
]
)
** (1 / self.m)
)
class Euclidean(Minkowski):
m = 2
class Manhattan(Minkowski):
m = 1
class Sorensen(Distance):
def distance(self, s1: Sample, s2: Sample) -> float:
return sum(
[
abs(s1.sepal_length - s2.sepal_length),
abs(s1.sepal_width - s2.sepal_width),
abs(s1.petal_length - s2.petal_length),
abs(s1.petal_width - s2.petal_width),
]
) / sum(
[
s1.sepal_length + s2.sepal_length,
s1.sepal_width + s2.sepal_width,
s1.petal_length + s2.petal_length,
s1.petal_width + s2.petal_width,
]
)
class Reduce_Function(Protocol):
"""Define a callable object with specific parameters."""
def __call__(self, values: list[float]) -> float:
pass
class Minkowski_2(Distance):
"""A generic way to implement Manhattan, Euclidean, and Chebyshev.
::
>>> from math import isclose
>>> from model import KnownSample, Purpose, UnknownSample, Minkowski_2
>>> class CD(Minkowski_2):
... m = 1
... reduction = max
>>> s1 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa",
... purpose=Purpose.Training)
>>> u = UnknownSample(**{"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4})
>>> algorithm = CD()
>>> isclose(3.3, algorithm.distance(s1, u))
True
"""
m: int
reduction: Reduce_Function
def distance(self, s1: Sample, s2: Sample) -> float:
# Required to prevent Python from passing `self` as the first argument.
summarize = self.reduction
return (
summarize(
[
abs(s1.sepal_length - s2.sepal_length) ** self.m,
abs(s1.sepal_width - s2.sepal_width) ** self.m,
abs(s1.petal_length - s2.petal_length) ** self.m,
abs(s1.petal_width - s2.petal_width) ** self.m,
]
)
** (1 / self.m)
)
class Hyperparameter:
"""A hyperparameter value and the overall quality of the classification."""
def __init__(self, k: int, algorithm: "Distance", training: "TrainingData") -> None:
self.k = k
self.algorithm = algorithm
self.data: weakref.ReferenceType["TrainingData"] = weakref.ref(training)
self.quality: float
def test(self) -> None:
"""Run the entire test suite."""
training_data: Optional["TrainingData"] = self.data()
if not training_data:
raise RuntimeError("Broken Weak Reference")
pass_count, fail_count = 0, 0
for sample in training_data.testing:
sample.classification = self.classify(sample)
if sample.matches():
pass_count += 1
else:
fail_count += 1
self.quality = pass_count / (pass_count + fail_count)
def classify(self, sample: Sample) -> str:
"""The k-NN algorithm"""
training_data = self.data()
if not training_data:
raise RuntimeError("No TrainingData object")
distances: list[tuple[float, KnownSample]] = sorted(
(self.algorithm.distance(sample, known), known)
for known in training_data.training
)
k_nearest = (known.species for d, known in distances[: self.k])
frequency: Counter[str] = collections.Counter(k_nearest)
best_fit, *others = frequency.most_common()
species, votes = best_fit
return species
class TrainingData:
"""A set of training data and testing data with methods to load and test the samples."""
def __init__(self, name: str) -> None:
self.name = name
self.uploaded: datetime.datetime
self.tested: datetime.datetime
self.training: list[KnownSample] = []
self.testing: list[KnownSample] = []
self.tuning: list[Hyperparameter] = []
def load(self, raw_data_iter: Iterable[dict[str, str]]) -> None:
"""Extract TestingKnownSample and TrainingKnownSample from raw data"""
for n, row in enumerate(raw_data_iter):
purpose = Purpose.Testing if n % 5 == 0 else Purpose.Training
sample = KnownSample(
sepal_length=float(row["sepal_length"]),
sepal_width=float(row["sepal_width"]),
petal_length=float(row["petal_length"]),
petal_width=float(row["petal_width"]),
purpose=purpose,
species=row["species"],
)
if sample.purpose == Purpose.Testing:
self.testing.append(sample)
else:
self.training.append(sample)
self.uploaded = datetime.datetime.now(tz=datetime.timezone.utc)
def test(self, parameter: Hyperparameter) -> None:
"""Test this hyperparamater value."""
parameter.test()
self.tuning.append(parameter)
self.tested = datetime.datetime.now(tz=datetime.timezone.utc)
def classify(self, parameter: Hyperparameter, sample: UnknownSample) -> str:
return parameter.classify(sample)
class BadSampleRow(ValueError):
pass
class SampleReader:
"""See iris.names for attribute ordering in bezdekIris.data file"""
target_class = Sample
header = ["sepal_length", "sepal_width", "petal_length", "petal_width", "class"]
def __init__(self, source: Path) -> None:
self.source = source
def sample_iter(self) -> Iterator[Sample]:
target_class = self.target_class
with self.source.open() as source_file:
reader = csv.DictReader(source_file, self.header)
for row in reader:
try:
sample = target_class(
sepal_length=float(row["sepal_length"]),
sepal_width=float(row["sepal_width"]),
petal_length=float(row["petal_length"]),
petal_width=float(row["petal_width"]),
)
except ValueError as ex:
raise BadSampleRow(f"Invalid {row!r}") from ex
yield sample
# Special case, we don't *often* test abstract superclasses.
# In this example, however, we can create instances of the abstract class.
test_Sample = """
>>> x = Sample(1, 2, 3, 4)
>>> x
Sample(sepal_length=1, sepal_width=2, petal_length=3, petal_width=4)
"""
test_Training_KnownSample = """
>>> s1 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa", purpose=Purpose.Training.value)
>>> s1
KnownSample(sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, purpose=2, species='Iris-setosa')
>>> s1.classification
Traceback (most recent call last):
...
AttributeError: Training samples have no classification
>>> s1.classification("rejected")
Traceback (most recent call last):
...
AttributeError: Training samples have no classification
"""
test_Testing_KnownSample = """
>>> s2 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa", purpose=Purpose.Testing.value)
>>> s2
KnownSample(sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, purpose=1, species='Iris-setosa')
>>> s2.classification
>>> s2.classification = "wrong"
>>> s2
KnownSample(sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, purpose=1, species='Iris-setosa', classification='wrong')
"""
test_UnknownSample = """
>>> u = UnknownSample(sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, )
>>> u
UnknownSample(sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, classification=None)
>>> u.classification = "something"
>>> u
UnknownSample(sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, classification='something')
"""
test_Chebyshev = """
>>> s1 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa", purpose=Purpose.Training.value)
>>> u = UnknownSample(**{"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4})
>>> algorithm = Chebyshev()
>>> isclose(3.3, algorithm.distance(s1, u))
True
"""
test_Euclidean = """
>>> s1 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa", purpose=Purpose.Training.value)
>>> u = UnknownSample(**{"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4})
>>> algorithm = Euclidean()
>>> isclose(4.50111097, algorithm.distance(s1, u))
True
"""
test_Manhattan = """
>>> s1 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa", purpose=Purpose.Training.value)
>>> u = UnknownSample(**{"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4})
>>> algorithm = Manhattan()
>>> isclose(7.6, algorithm.distance(s1, u))
True
"""
test_Sorensen = """
>>> s1 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa", purpose=Purpose.Training.value)
>>> u = UnknownSample(**{"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4})
>>> algorithm = Sorensen()
>>> isclose(0.2773722627, algorithm.distance(s1, u))
True
"""
test_Hyperparameter = """
>>> td = TrainingData('test')
>>> s2 = KnownSample(
... sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2, species="Iris-setosa", purpose=Purpose.Testing.value)
>>> td.testing = [s2]
>>> t1 = KnownSample(**{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2, "species": "Iris-setosa", "purpose": 1})
>>> t2 = KnownSample(**{"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4, "species": "Iris-versicolor", "purpose": 1})
>>> td.training = [t1, t2]
>>> h = Hyperparameter(k=3, algorithm=Chebyshev(), training=td)
>>> u = UnknownSample(sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2)
>>> h.classify(u)
'Iris-setosa'
>>> h.test()
>>> print(f"data={td.name!r}, k={h.k}, quality={h.quality}")
data='test', k=3, quality=1.0
"""
test_TrainingData = """
>>> td = TrainingData('test')
>>> raw_data = [
... {"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2, "species": "Iris-setosa"},
... {"sepal_length": 7.9, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4, "species": "Iris-versicolor"},
... ]
>>> td.load(raw_data)
>>> h = Hyperparameter(k=3, algorithm=Chebyshev(), training=td)
>>> len(td.training)
1
>>> len(td.testing)
1
>>> td.test(h)
>>> print(f"data={td.name!r}, k={h.k}, quality={h.quality}")
data='test', k=3, quality=0.0
"""
__test__ = {name: case for name, case in globals().items() if name.startswith("test_")}