-
Notifications
You must be signed in to change notification settings - Fork 1
/
clustering_fuzzy.py
223 lines (170 loc) · 7.6 KB
/
clustering_fuzzy.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
__author__ = 'Michael Kern'
__version__ = '0.0.3'
__email__ = '[email protected]'
########################################################################################################################
# libraries
# module to load own configurations
import caleydo_server.config
# request config if needed for the future
config = caleydo_server.config.view('caleydo-clustering')
# library to conduct matrix/vector calculus
import numpy as np
from clustering_util import similarityMeasurement
########################################################################################################################
# class definition
class Fuzzy(object):
"""
Formulas: https://en.wikipedia.org/wiki/Fuzzy_clustering
"""
def __init__(self, obs, numClusters, m=2.0, threshold=-1, distance='euclidean', init=None, error=0.0001):
"""
Initializes algorithm.
:param obs: observation matrix / genomic data
:param numClusters: number of clusters
:param m: fuzzifier, controls degree of fuzziness, from [1; inf]
:return:
"""
# observation
self.__obs = np.nan_to_num(obs)
self.__n = obs.shape[0]
# fuzzifier value
self.__m = np.float(m)
# number of clusters
self.__c = numClusters
# matrix u containing all the weights describing the degree of membership of each patient to the centroid
if init is None:
init = np.random.rand(self.__c, self.__n)
self.__u = np.copy(init)
# TODO! scikit normalizes the values at the beginning and at each step to [0; 1]
self.__u /= np.ones((self.__c, 1)).dot(np.atleast_2d(np.sum(self.__u, axis=0))).astype(np.float64)
# remove all zero values and set them to smallest possible value
self.__u = np.fmax(self.__u, np.finfo(np.float64).eps)
# centroids
self.__centroids = np.zeros(self.__c)
# threshold for stopping criterion
self.__error = error
# distance function
self.__distance = distance
# threshold or minimum probability used for cluster assignments
if threshold == -1:
self.__threshold = 1.0 / numClusters
else:
self.__threshold = threshold
# ------------------------------------------------------------------------------------------------------------------
def __call__(self):
"""
Caller function for server API
:return:
"""
return self.run()
# ------------------------------------------------------------------------------------------------------------------
def computeCentroid(self):
"""
Compute the new centroids using the computed partition matrix.
:return:
"""
uM = self.__u ** self.__m
sumDataWeights = np.dot(uM, self.__obs)
if self.__obs.ndim == 1:
m = 1
else:
m = self.__obs.shape[1]
sumWeights = np.sum(uM, axis=1)
# tile array (sum of weights repeated in every row)
sumWeights = np.ones((m, 1)).dot(np.atleast_2d(sumWeights)).T
if self.__obs.ndim == 1:
sumWeights = sumWeights.flatten()
# divide by total sum to get new centroids
self.__centroids = sumDataWeights / sumWeights
# ------------------------------------------------------------------------------------------------------------------
def computeCoefficients(self):
"""
Compute new partition matrix / weights describing the degree of membership of each patient to all clusters.
:return:
"""
# TODO you can also use cdist of scipy.spatial.distance module
distMat = np.zeros((self.__c, self.__n))
for ii in range(self.__c):
distMat[ii] = similarityMeasurement(self.__obs, self.__centroids[ii], self.__distance)
# set zero values to smallest values to prevent inf results
distMat = np.fmax(distMat, np.finfo(np.float64).eps)
# apply coefficient formula
denom = np.float(self.__m - 1.0)
self.__u = distMat ** (-2.0 / denom)
sumCoeffs = np.sum(self.__u, axis=0)
self.__u /= np.ones((self.__c, 1)).dot(np.atleast_2d(sumCoeffs))
self.__u = np.fmax(self.__u, np.finfo(np.float64).eps)
# ------------------------------------------------------------------------------------------------------------------
def run(self):
"""
Perform the c-means fuzzy clustering.
:return:
"""
MAX_ITER = 100
iter = 0
while iter < MAX_ITER:
# save last partition matrix
uOld = np.copy(self.__u)
# compute centroids with given weights
self.computeCentroid()
# compute new coefficient matrix
self.computeCoefficients()
# normalize weight / partition matrix u
self.__u /= np.ones((self.__c, 1)).dot(np.atleast_2d(np.sum(self.__u, axis=0)))
self.__u = np.fmax(self.__u, np.finfo(np.float64).eps)
# compute the difference between the old and new matrix
epsilon = np.linalg.norm(self.__u - uOld)
# stop if difference (epsilon) is smaller than the user-defined threshold
if epsilon < self.__error:
break
iter += 1
self.__end()
u = self.__u.T
# print(self.__u.T)
return self.__centroids.tolist(), self.__clusterLabels, u.tolist(), self.__threshold
# ------------------------------------------------------------------------------------------------------------------
def __end(self):
"""
Conduct the cluster assignments and creates clusterLabel array.
:return:
"""
# assign patient to clusters
# transpose to get a (n, c) matrix
u = self.__u.T
self.__labels = np.zeros(self.__n, dtype=np.int)
self.__clusterLabels = [[] for _ in range(self.__c)]
# gather all probabilities / degree of memberships of each patient to the clusters
# self.__clusterProbs = [[] for _ in range(self.__c)]
# probability that the patients belongs to each cluster
maxProb = np.float64(self.__threshold)
for ii in range(self.__n):
# clusterID = np.argmax(u[ii])
# self.__labels = clusterID
# self.__clusterLabels[clusterID].append(ii)
for jj in range(self.__c):
if u[ii][jj] >= maxProb:
clusterID = jj
self.__labels = clusterID
self.__clusterLabels[clusterID].append(int(ii))
# for ii in range(self.__c):
# self.__clusterLabels[ii], _ = computeClusterInternDistances(self.__obs, self.__clusterLabels[ii])
########################################################################################################################
def _plugin_initialize():
"""
optional initialization method of this module, will be called once
:return:
"""
pass
# ----------------------------------------------------------------------------------------------------------------------
def create(data, numCluster, m, threshold, distance):
"""
by convention contain a factory called create returning the extension implementation
:return:
"""
return Fuzzy(data, numCluster, m, threshold, distance)
########################################################################################################################
if __name__ == '__main__':
data = np.array([[1,1,2],[5,4,5],[3,2,2],[8,8,7],[9,8,9],[2,2,2]])
# data = np.array([1,1.1,5,8,5.2,8.3])
fuz = Fuzzy(data, 3, 1.5)
print(fuz.run())