1
|
|
|
import logging |
2
|
|
|
import attr |
3
|
|
|
import numpy as np |
4
|
|
|
import somoclu |
5
|
|
|
from sklearn.cluster import KMeans |
6
|
|
|
|
7
|
|
|
logger = logging.getLogger(__name__) |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
def infer_map(nb_cols, nb_rows, dataset, **kwargs): |
11
|
|
|
"""Infer a self-organizing map from dataset.\n |
12
|
|
|
initialcodebook = None, kerneltype = 0, maptype = 'planar', gridtype = 'rectangular', |
13
|
|
|
compactsupport = False, neighborhood = 'gaussian', std_coeff = 0.5, initialization = None |
14
|
|
|
""" |
15
|
|
|
if not hasattr(dataset, 'feature_vectors'): |
16
|
|
|
raise NoFeatureVectorsError("Attempted to train a Som model, " |
17
|
|
|
"but did not find feature vectors in the dataset.") |
18
|
|
|
som = somoclu.Somoclu(nb_cols, nb_rows, **kwargs) |
19
|
|
|
som.train(data=np.array(dataset.feature_vectors, dtype=np.float32)) |
20
|
|
|
return som |
21
|
|
|
|
22
|
|
|
|
23
|
|
|
@attr.s(slots=True) |
24
|
|
|
class SomTrainer: |
25
|
|
|
infer_map: callable = attr.ib() |
26
|
|
|
|
27
|
|
|
@staticmethod |
28
|
|
|
def from_callable(): |
29
|
|
|
return SomTrainer(infer_map) |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
@attr.s |
33
|
|
|
class SelfOrganizingMap: |
34
|
|
|
som = attr.ib(init=True) |
35
|
|
|
dataset_name = attr.ib(init=True) |
36
|
|
|
|
37
|
|
|
@property |
38
|
|
|
def height(self): |
39
|
|
|
return self.som._n_rows |
40
|
|
|
|
41
|
|
|
@property |
42
|
|
|
def width(self): |
43
|
|
|
return self.som._n_columns |
44
|
|
|
|
45
|
|
|
@property |
46
|
|
|
def type(self): |
47
|
|
|
return self.som._map_type |
48
|
|
|
|
49
|
|
|
@property |
50
|
|
|
def grid_type(self): |
51
|
|
|
return self.som._grid_type |
52
|
|
|
|
53
|
|
|
def __getattr__(self, item): |
54
|
|
|
if item in ('n_rows', 'n_columns', 'initialization', 'map_type', 'grid_type'): |
55
|
|
|
item = f'_{item}' |
56
|
|
|
return getattr(self.som, item) |
57
|
|
|
|
58
|
|
|
def get_map_id(self): |
59
|
|
|
_ = '-'.join(str(getattr(self, attribute)) for attribute in |
60
|
|
|
['dataset_name', 'n_columns', 'n_rows', 'initialization', 'map_type', 'grid_type']) |
61
|
|
|
if self.som.clusters: |
62
|
|
|
return f'{_}_cl{self.nb_clusters}' |
63
|
|
|
return _ |
64
|
|
|
|
65
|
|
|
@property |
66
|
|
|
def nb_clusters(self): |
67
|
|
|
if self.som.clusters is not None: |
68
|
|
|
return np.max(self.som.clusters) + 1 |
69
|
|
|
return 0 |
70
|
|
|
|
71
|
|
|
def neurons_coordinates(self): |
72
|
|
|
raise NotImplementedError |
73
|
|
|
# # iterate through the array of shape [nb_datapoints, 2]. Each row is the coordinates |
74
|
|
|
# for i, arr in enumerate(self.som.bmus): |
75
|
|
|
# # of the neuron the datapoint gets attributed to (closest distance) |
76
|
|
|
# attributed_cluster = self.som.clusters[arr[0], arr[1]] # >= 0 |
77
|
|
|
# id2members[attributed_cluster].add(dataset[i].id) |
78
|
|
|
|
79
|
|
|
def datapoint_coordinates(self, index): |
80
|
|
|
"""Get the best-matching unit (bmu) coordinates of the datapoint indexed by the input pointer.\n |
81
|
|
|
|
82
|
|
|
Bmu is simply the neuron on the som grid that is closest to the projected-into-2D-space datapoint.""" |
83
|
|
|
return self.som.bmus[index][0], self.som.bmus[index][1] |
84
|
|
|
|
85
|
|
|
def project(self, datapoint): |
86
|
|
|
"""Compute the coordinates of a (potentially unseen) datapoint. |
87
|
|
|
|
88
|
|
|
It is assumed that the codebook has been computed already.""" |
89
|
|
|
raise NotImplementedError |
90
|
|
|
|
91
|
|
|
def cluster(self, nb_clusters, random_state=None): |
92
|
|
|
self.som.cluster(algorithm=KMeans(n_clusters=nb_clusters, random_state=random_state)) |
93
|
|
|
|
94
|
|
|
@property |
95
|
|
|
def visual_umatrix(self): |
96
|
|
|
buffer = '' |
97
|
|
|
# i.e. a clustering of 11 clusters with ids 0, 1, .., 10 has a max_len = 2 |
98
|
|
|
max_len = len(str(np.max(self.som.clusters))) |
99
|
|
|
for j in range(self.som.umatrix.shape[0]): |
100
|
|
|
buffer += ' '.join(' ' * (max_len - len(str(i))) + str(i) for i in self.som.clusters[j, :]) + '\n' |
101
|
|
|
return buffer |
102
|
|
|
|
103
|
|
|
|
104
|
|
|
class NoFeatureVectorsError(Exception): pass |
105
|
|
|
|