hac_bic.py 9.85 KB
Newer Older
Sylvain Meignier's avatar
Origin  
Sylvain Meignier committed
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
__author__ = 'meignier'

import numpy as np
import logging
import copy
from s4d.clustering.hac_utils import argmin, roll, set_new_label
from s4d.clustering.hac_utils import bic_square_root
from s4d.clustering.gauss import GaussFull

class HAC_BIC:
    """
    BIC Hierarchical Agglomerative Clustering (HAC) with gaussian models

    The algorithm is based upon a hierarchical agglomerative clustering. The
    initial set of clusters is composed of one segment per cluster. Each cluster
    is modeled by a Gaussian with a full covariance matrix (see
    :class:`gauss.GaussFull`). :math:`\Delta BIC`
    measure is employed to select the candidate clusters to group as well as
    to stop the merging process. The two closest clusters :math:`i` and
    :math:`j` are merged at each iteration until :math:`\\Delta BIC_{i,j} > 0`.


        :math:`\\Delta BIC_{i,j} = PBIC_{i+j} - PBIC_{i} - PBIC_{j} - P`

        :math:`PBIC_{x}  = \\frac{n_x}{2} \\log|\\Sigma_x|`

        :math:`cst  = \\frac{1}{2} \\alpha \\left(d + \\frac{d(d+1)}{2}\\right)`

        :math:`P  = cst + log(n_i+n_j)`

    where :math:`|\\Sigma_i|`, :math:`|\\Sigma_j|` and :math:`|\\Sigma|` are the
    determinants of gaussians associated to the clusters :math:`i`, :math:`j`
    and :math:`i+j`. :math:`\\alpha` is a parameter to set up. The penalty
    factor :math:`P` depends on :math:`d`, the dimension of the features, as well as
    on :math:`n_i` and :math:`n_j`, refering to the total length of cluster
    :math:`i` and cluster :math:`j` respectively.


    """
    def __init__(self, features_server, table, alpha=1.0, sr=False):
        self.fs = features_server
        self.alpha = alpha
        self.diar = copy.deepcopy(table)
        self.models = []
        self.merge = []
        self.nb_merge = 0
        self.sr = sr
        self._init_train()
        self._init_distance()

    def _init_train(self):
        """
        Train initial models

        """
        map = self.diar.make_index(['label', 'show'])
        for label in map:
            model = GaussFull(label, self.fs.dim())
            self.models.append(model)
            for show in map[label]:
                tmp, vad = self.fs.load(show)
                cep = tmp[0]
                self.dim = cep.shape[1];
                self.cst_bic = GaussFull.cst_bic(self.dim, self.alpha)
                for row in map[label][show]:
                    start = row['start']
                    stop = row['stop']
                    model.add(cep[start:stop])

        for model in self.models:
            model.compute()

    def _init_distance(self):
        """ Compute distance matrix
        """
        nb = len(self.models)
        self.dist = np.full((nb, nb), np.nan)
        # for i in range(0, nb):
        #    mi = self.models[i]
        for i, mi in enumerate(self.models):
            #self.merge.append([])
            # for j, mj in enumerate(self.models, start=i+1):
            #    logging.debug('i %d j %d n %d', i, j ,nb)
            for j in range(i + 1, nb):
                mj = self.models[j]
                self.dist[i, j] = self.dist[j, i] = self._dist(mi, mj)

    def _dist(self, mi, mj):
        """
        Compute the BIC distance d(i,j)
        :param mi: a GaussFull object
        :param mj: a GaussFull object
        :return: float
        """
        if self.sr:
            return GaussFull.merge_partial_bic(mi, mj) - \
            mi.partial_bic - mj.partial_bic - bic_square_root(mi.count, mj.count, self.alpha, self.dim)
        return GaussFull.merge_partial_bic(mi, mj) - \
            mi.partial_bic - mj.partial_bic - self.cst_bic * np.log(mi.count + mj.count)

    def _merge_model(self, mi, mj):
        """
        Merge two a GaussFull objects
        :param mi: a GaussFull object
        :param mj: a GaussFull object
        :return: a GaussFull object
        """
        return GaussFull.merge(mi, mj)

    def _update_dist(self, i):
        """
        Update row and column i of the distance matrix
        :param i: int

        """
        nb = len(self.models)
        mi = self.models[i]
        for j in (x for x in range(nb) if x != i):
            mj = self.models[j]
            self.dist[i, j] = self.dist[j, i] = self._dist(mi, mj)

    def information(self, i, j, value):
        self.merge.append([self.nb_merge, self.models[i].name, self.models[j].name, value])

    # def link(self, thr):
    #     labels = list()
    #     idx = dict()
    #     qt = dict()
    #     k=0;
    #     while self.merge[k][0] < 0:
    #         name = self.merge[k][1]
    #         labels.append(name)
    #         idx[name] = k
    #         qt[name] = 1
    #         k += 1
    #
    #     l = k
    #     link = np.zeros((l-1, 4))
    #
    #     while k < len(self.merge):
    #         m = self.merge[k][0]
    #         name_i = self.merge[k][1]
    #         name_j = self.merge[k][2]
    #         v_ij = self.merge[k][3]
    #
    #         qt[name_i] += 1
    #         link[m, 0] = idx[name_i]
    #         link[m, 1] = idx[name_j]
    #         link[m, 2] = v_ij
    #         link[m, 3] = qt[name_i]
    #         idx[name_i] = m+l
    #         idx[name_j] = -1
    #
    #         k+= 1
    #
    #     min = np.min(link[:,2])
    #     link[:,2] += -1*min
    #
    #     return labels, link, thr-min

    def perform(self, to_the_end=False):
        """
        perform the HAC algorithm
        :return: a Diar object and a dictonary mapping the old labels to the
        new lables
        """
        nb = len(self.models)
        self.nb_merge = -1
        for i in range(nb):
            self.information(i, i, 0)

        i, j, v = argmin(self.dist, nb)
        self.nb_merge = 0
        while v < 0.0 and nb > 1:
            self.information(i, j, v)
            self.nb_merge += 1
            logging.debug('merge: %d c1: %s (%d) c2: %s (%d) dist: %f %d',
                          self.nb_merge, self.models[i].name, i,
                          self.models[j].name, j, v, nb)
            # update merge
            #self.merge[i].append(
            #    [self.nb_merge, self.models[i].name, self.models[j].name, v])
            #self.merge[i] += self.merge[j]
            #self.merge.pop(j)
            self.diar.rename('label', [self.models[j].name], self.models[i].name)
            # update model
            self.models[i] = self._merge_model(self.models[i], self.models[j])
            self.models.pop(j)
            #nb = len(self.models)
            # update distances
            self.dist = roll(self.dist, j)
            self._update_dist(i)
            nb -= 1
            i, j, v = argmin(self.dist, nb)

        out_diar = copy.deepcopy(self.diar)
        n = self.nb_merge

        if to_the_end:
            while nb > 1:
                self.information(i, j, v)
                self.nb_merge += 1
                logging.debug('merge: %d c1: %s (%d) c2: %s (%d) dist: %f %d',
                          self.nb_merge, self.models[i].name, i,
                          self.models[j].name, j, v, nb)
                self.diar.rename('label', [self.models[j].name], self.models[i].name)
                # update model
                self.models[i] = self._merge_model(self.models[i], self.models[j])
                self.models.pop(j)
                #nb = len(self.models)
                # update distances
                self.dist = roll(self.dist, j)
                self._update_dist(i)
                nb -= 1
                i, j, v = argmin(self.dist, nb)


        # make a map between old and new label
        #return set_new_label(self.merge, self.diar, [x.name for x in self.models])

        # labels_dict = dict()
        # for i in range(0, len(self.merge)):
        #     if self.models[i].name not in labels_dict:
        #         labels_dict[self.models[i].name] = self.models[i].name
        #     for info in self.merge[i]:
        #         labels_dict[info[2]] = self.models[i].name
        # for row in self.diar:
        #     name = row['label']
        #     name2 = labels_dict[name]
        #     row['label'] = name2

        return out_diar

    # def perform(self):
    #     """
    #     perform the HAC algorithm
    #     :return: a Diar object and a dictonary mapping the old labels to the
    #     new lables
    #     """
    #     nb = len(self.models)
    #     i, j, v = argmin(self.dist, nb)
    #     self.nb_merge = 0
    #     while v < 0.0 and nb > 1:
    #         self.nb_merge += 1
    #         logging.debug('merge: %d c1: %s (%d) c2: %s (%d) dist: %f',
    #                       self.nb_merge, self.models[i].name, i,
    #                       self.models[j].name, j, v)
    #         # update merge
    #         self.merge[i].append(
    #             [self.nb_merge, self.models[i].name, self.models[j].name, v])
    #         self.merge[i] += self.merge[j]
    #         self.merge.pop(j)
    #         # update model
    #         self.models[i] = self._merge_model(self.models[i], self.models[j])
    #         self.models.pop(j)
    #         nb = len(self.models)
    #         # update distances
    #         self.dist = roll(self.dist, j)
    #         self._update_dist(i)
    #         i, j, v = argmin(self.dist, nb)
    #     logging.debug('exit merge %d c1: %s (%d) c2: %s (%d) dist: %f',
    #                   self.nb_merge, self.models[i].name, i,
    #                   self.models[j].name, j, v)
    #
    #     # make a map between old and new label
    #     #return set_new_label(self.merge, self.diar, [x.name for x in self.models])
    #
    #     labels_dict = dict()
    #     for i in range(0, len(self.merge)):
    #         if self.models[i].name not in labels_dict:
    #             labels_dict[self.models[i].name] = self.models[i].name
    #         for info in self.merge[i]:
    #             labels_dict[info[2]] = self.models[i].name
    #     for row in self.diar:
    #         name = row['label']
    #         name2 = labels_dict[name]
    #         row['label'] = name2
    #
    #     return self.diar, labels_dict