-
Notifications
You must be signed in to change notification settings - Fork 1
/
mcc.py
511 lines (450 loc) · 19.4 KB
/
mcc.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
"""
Copyright (c) Meta Platforms, Inc. and affiliates.
This file is adapted from the MCC implementation for the iVAE by Ilyes Khemakhem.
https://github.com/ilkhem/iVAE/blob/master/metrics/mcc.py
Copyright (c) 2019 Ilyes Khemakhem
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
import torch
from scipy.optimize import linear_sum_assignment
from scipy.stats import spearmanr
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial.distance import cosine as np_cos
from torch.nn import CosineSimilarity
from itertools import permutations
torch.set_default_dtype(torch.double)
if torch.cuda.is_available():
torch.set_default_tensor_type(torch.cuda.DoubleTensor)
def auction_linear_assignment(x, eps=None, reduce='sum'):
"""
Solve the linear sum assignment problem using the auction algorithm.
Implementation in pytorch, GPU compatible.
x_ij is the affinity between row (person) i and column (object) j, the
algorithm aims to assign to each row i a column j_i such that the total benefit
\sum_i x_{ij_i} is maximized.
pytorch implementation, supports GPU.
Algorithm adapted from http://web.mit.edu/dimitrib/www/Auction_Survey.pdf
:param x: torch.Tensor
The affinity (or benefit) matrix of size (n, n)
:param eps: float, optional
Bid size. Smaller values yield higher accuracy at the price of
longer runtime.
:param reduce: str, optional
The reduction method to be applied to the score.
If `sum`, sum the entries of cost matrix after assignment.
If `mean`, compute the mean of the cost matrix after assignment.
If `none`, return the vector (n,) of assigned column entry per row.
:return: (torch.Tensor, torch.Tensor, int)
Tuple of (score after application of reduction method, assignment,
number of steps in the auction algorithm).
"""
eps = 1 / x.size(0) if eps is None else eps
price = torch.zeros((1, x.size(1))).to(x.device)
assignment = torch.zeros(x.size(0)).long().to(x.device) - 1
bids = torch.zeros_like(x).to(x.device)
n_iter = 0
while (assignment == -1).any():
n_iter += 1
# -- Bidding --
# set I of unassigned rows (persons)
# a person is unassigned if it is assigned to -1
I = (assignment == -1).nonzero().squeeze(dim=1)
# value matrix = affinity - price
value_I = x[I, :] - price
# find j_i, the best value v_i and second best value w_i for each i \in I
top_value, top_idx = value_I.topk(2, dim=1)
jI = top_idx[:, 0]
vI, wI = top_value[:, 0], top_value[:, 1]
# compute bid increments \gamma
gamma_I = vI - wI + eps
# fill entry (i, j_i) with \gamma_i for each i \in I
# every unassigned row i makes a bid at one j_i with value \gamma_i
bids_ = bids[I, :]
bids_.zero_()
bids_.scatter_(dim=1, index=jI.contiguous().view(-1, 1), src=gamma_I.view(-1, 1))
# -- Assignment --
# set J of columns (objects) that have at least a bidder
# if a column j in bids_ is empty, then no bid was made to object j
J = (bids_ > 0).sum(dim=0).nonzero().squeeze(dim=1)
# determine the highest bidder i_j and corresponding highest bid \gamma_{i_j}
# for each object j \in J
gamma_iJ, iJ = bids_[:, J].max(dim=0)
# since iJ is the index of highest bidder in the "smaller" array bids_,
# find its actual index among the unassigned rows I
# now iJ is a subset of I
iJ = I[iJ]
# raise the price of column j by \gamma_{i_j} for each j \in J
price[:, J] += gamma_iJ
# unassign any row that was assigned to object j at the beginning of the iteration
# for each j \in J
mask = (assignment.view(-1, 1) == J.view(1, -1)).sum(dim=1).byte()
assignment.masked_fill_(mask, -1)
# assign j to i_j for each j \in J
assignment[iJ] = J
score = x.gather(dim=1, index=assignment.view(-1, 1)).squeeze()
if reduce == 'sum':
score = torch.sum(score)
elif reduce == 'mean':
score = torch.mean(score)
elif reduce == 'none':
pass
else:
raise ValueError('not a valid reduction method: {}'.format(reduce))
return score, assignment, n_iter
def rankdata_pt(b, tie_method='ordinal', dim=0):
"""
pytorch equivalent of scipy.stats.rankdata, GPU compatible.
:param b: torch.Tensor
The 1-D or 2-D tensor of values to be ranked. The tensor is first flattened
if tie_method is not 'ordinal'.
:param tie_method: str, optional
The method used to assign ranks to tied elements.
The options are 'average', 'min', 'max', 'dense' and 'ordinal'.
'average':
The average of the ranks that would have been assigned to
all the tied values is assigned to each value.
Supports 1-D tensors only.
'min':
The minimum of the ranks that would have been assigned to all
the tied values is assigned to each value. (This is also
referred to as "competition" ranking.)
Supports 1-D tensors only.
'max':
The maximum of the ranks that would have been assigned to all
the tied values is assigned to each value.
Supports 1-D tensors only.
'dense':
Like 'min', but the rank of the next highest element is assigned
the rank immediately after those assigned to the tied elements.
Supports 1-D tensors only.
'ordinal':
All values are given a distinct rank, corresponding to the order
that the values occur in `a`.
The default is 'ordinal' to match argsort.
:param dim: int, optional
The axis of the observation in the data if the input is 2-D.
The default is 0.
:return: torch.Tensor
An array of length equal to the size of `b`, containing rank scores.
"""
# b = torch.flatten(b)
if b.dim() > 2:
raise ValueError('input has more than 2 dimensions')
if b.dim() < 1:
raise ValueError('input has less than 1 dimension')
order = torch.argsort(b, dim=dim)
if tie_method == 'ordinal':
ranks = order + 1
else:
if b.dim() != 1:
raise NotImplementedError('tie_method {} not supported for 2-D tensors'.format(tie_method))
else:
n = b.size(0)
ranks = torch.empty(n).to(b.device)
dupcount = 0
total_tie_count = 0
for i in range(n):
inext = i + 1
if i == n - 1 or b[order[i]] != b[order[inext]]:
if tie_method == 'average':
tie_rank = inext - 0.5 * dupcount
elif tie_method == 'min':
tie_rank = inext - dupcount
elif tie_method == 'max':
tie_rank = inext
elif tie_method == 'dense':
tie_rank = inext - dupcount - total_tie_count
total_tie_count += dupcount
else:
raise ValueError('not a valid tie_method: {}'.format(tie_method))
for j in range(i - dupcount, inext):
ranks[order[j]] = tie_rank
dupcount = 0
else:
dupcount += 1
return ranks
def cov_pt(x, y=None, rowvar=False):
"""
Estimate a covariance matrix given data in pytorch, GPU compatible.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element `C_{ij}` is the covariance of
`x_i` and `x_j`. The element `C_{ii}` is the variance of `x_i`.
:param x: torch.Tensor
A 1-D or 2-D array containing multiple variables and observations.
Each column of `x` represents a variable, and each row a single
observation of all those variables.
:param y: torch.Tensor, optional
An additional set of variables and observations. `y` has the same form
as that of `x`.
:param rowvar: bool, optional
If `rowvar` is True, then each row represents a
variable, with observations in the columns. Otherwise, the
relationship is transposed: each column represents a variable,
while the rows contain observations.
The default is False.
:return: torch.Tensor
The covariance matrix of the variables.
"""
if y is not None:
if not x.size() == y.size():
raise ValueError('x and y have different shapes')
if x.dim() > 2:
raise ValueError('x has more than 2 dimensions')
if x.dim() < 2:
x = x.view(1, -1)
if not rowvar and x.size(0) != 1:
x = x.t()
if y is not None:
if y.dim() < 2:
y = y.view(1, -1)
if not rowvar and y.size(0) != 1:
y = y.t()
x = torch.cat((x, y), dim=0)
fact = 1.0 / (x.size(1) - 1)
x -= torch.mean(x, dim=1, keepdim=True)
xt = x.t() # if complex: xt = x.t().conj()
return fact * x.matmul(xt).squeeze()
def corrcoef_pt(x, y=None, rowvar=False):
"""
Return Pearson product-moment correlation coefficients in pytorch, GPU compatible.
Implementation very similar to numpy.corrcoef using cov.
:param x: torch.Tensor
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables.
:param y: torch.Tensor, optional
An additional set of variables and observations. `y` has the same form
as that of `m`.
:param rowvar: bool, optional
If `rowvar` is True, then each row represents a
variable, with observations in the columns. Otherwise, the
relationship is transposed: each column represents a variable,
while the rows contain observations.
The default is False.
:return: torch.Tensor
The correlation coefficient matrix of the variables.
"""
c = cov_pt(x, y, rowvar)
try:
d = torch.diag(c)
except RuntimeError:
# scalar covariance
return c / c
stddev = torch.sqrt(d)
c /= stddev[:, None]
c /= stddev[None, :]
return c
def spearmanr_pt(x, y=None, rowvar=False):
"""
Calculates a Spearman rank-order correlation coefficient in pytorch, GPU compatible.
:param x: torch.Tensor
A 1-D or 2-D array containing multiple variables and observations.
Each column of `x` represents a variable, and each row a single
observation of all those variables.
:param y: torch.Tensor, optional
An additional set of variables and observations. `y` has the same form
as that of `x`.
:param rowvar: bool, optional
If `rowvar` is True, then each row represents a
variable, with observations in the columns. Otherwise, the
relationship is transposed: each column represents a variable,
while the rows contain observations.
The default is False.
:return: torch.Tensor
Spearman correlation matrix or correlation coefficient.
"""
# xr = rankdata_pt(x, dim=int(rowvar)).float()
d = x.ndim
xr = rankdata_pt(x, dim=-d).float()
yr = None
if y is not None:
# yr = rankdata_pt(y, dim=int(rowvar)).float()
yr = rankdata_pt(y, dim=-d).float()
rs = corrcoef_pt(xr, yr, rowvar)
return rs
def get_mcc_pt(x, y, method='pearson'):
"""
Get absolute MCC/MCS COLUMN-wise.
"""
d = x.size(1)
if method == 'pearson':
cc = corrcoef_pt(x, y)[:d, d:]
# elif method == 'spearman':
# cc = spearmanr_pt(x, y)[:d, d:]
# Pytorch implementation does not work!!! (Check again, it might work now after some modifications)
elif method == 'cos':
cos = CosineSimilarity(dim=0)
# proceed only if the matrices have the same dimensions
if x.shape == y.shape:
# take the correlation between each column of each matrix
cc = torch.zeros(x.shape)
for j in range(x.shape[0]):
for k in range(y.shape[1]):
cc[j, k] = cos(x[:,j], y[:,k]) # used for for columns
else:
raise ValueError('not a valid method: {}'.format(method))
return
cc = torch.abs(cc)
return cc
def mean_corr_coef_pt(x, y, method='pearson'):
"""
A differentiable pytorch implementation of the mean correlation coefficient metric.
Get correlations and then use linear assignment.
:param x: torch.Tensor
:param y: torch.Tensor
:param method: str, optional
The options are 'pearson', 'spearman', and 'cos'.
'pearson':
use Pearson's correlation coefficient
'spearman':
use Spearman's nonparametric rank correlation coefficient
'cos':
use pairwise cosine similarity to evaluate the mixing matrix.
:return: float
"""
cc = get_mcc_pt(x, y, method)
score, _, _ = auction_linear_assignment(cc, reduce='mean')
return score
def get_mcc_np(x, y, method='pearson'):
"""
Get absolute MCC/MCS COLUMN-wise.
method (str): Cosine similarity ('cos') or correlation ('pearson').
"""
d = x.shape[1]
if method == 'pearson':
cc = np.corrcoef(x, y, rowvar=False)[:d, d:]
# elif method == 'spearman':
# cc = spearmanr(x, y)[0][:d, d:]
elif method == 'cos':
# Sklearn computes the pairwise cosine similarity row-wise, so we need to transpose it to do column-wise
cc = cosine_similarity(x.T, y.T)
else:
raise ValueError('not a valid method: {}'.format(method))
cc = np.abs(cc)
return cc
def mean_corr_coef_np(x, y, method='pearson'):
"""
A numpy implementation of the mean correlation coefficient metric.
Get correlations and then use linear assignment.
:param x: numpy.ndarray
:param y: numpy.ndarray
:param method: str, optional
The method used to compute the correlation coefficients.
The options are 'pearson', 'spearman', and 'cos'.
'pearson':
use Pearson's correlation coefficient
'spearman':
use Spearman's nonparametric rank correlation coefficient
'cos':
use pairwise cosine similarity to evaluate the mixing matrix.
:return: float
"""
cc = get_mcc_np(x, y, method)
score = cc[linear_sum_assignment(-1 * cc)].mean()
return score
def mean_corr_coef(x, y, method='pearson'):
"""
MCC or MCS with linear assignment.
method (str): Cosine similarity ('cos') or correlation ('pearson' or 'spearman').
"""
if type(x) != type(y):
raise ValueError('inputs are of different types: ({}, {})'.format(type(x), type(y)))
if isinstance(x, np.ndarray):
return mean_corr_coef_np(x, y, method)
elif isinstance(x, torch.Tensor):
return mean_corr_coef_pt(x, y, method)
else:
raise ValueError('not a supported input type: {}'.format(type(x)))
def get_mcs_pt(x, y, method='cos'):
"""
Get absolute MCC/MCS COLUMN-wise.
method (str): Cosine similarity ('cos') or correlation ('pearson' or 'spearman').
"""
d = x.size(1)
all_perm = list(permutations(np.arange(d)))
if method == 'cos':
cos = CosineSimilarity(dim=0)
# proceed only if the matrices have the same dimensions
if x.shape == y.shape:
sbest = 0
for p in all_perm:
s = 0
for i in range(d):
s = s + torch.abs( cos(x[:,i], y[:,p[i]]) )
s = s / d
if s > sbest:
sbest = s
return sbest
elif method == 'pearson':
raise ValueError('not implemented: {}'.format(method))
return
# cc = corrcoef_pt(x, y)[:d, d:]
elif method == 'spearman':
raise ValueError('not implemented: {}'.format(method))
return
# cc = spearmanr_pt(x, y)[:d, d:]
else:
raise ValueError('not a valid method: {}'.format(method))
return
def get_mcs_np(x, y, method='cos'):
"""
Get absolute MCC/MCS COLUMN-wise.
method (str): Cosine similarity ('cos') or correlation ('pearson').
"""
d = x.shape[1] # d is the number of columns, which is the number of sources
all_perm = list(permutations(np.arange(d)))
if method == 'cos':
# proceed only if the matrices have the same dimensions
if x.shape == y.shape:
sbest = 0
for p in all_perm:
s = 0
for i in range(d):
s = s + np.abs(1 - np_cos(x[:,i], y[:,p[i]]))
s = s / d
if s > sbest:
sbest = s
return sbest
elif method == 'pearson':
raise ValueError('not implemented: {}'.format(method))
return
elif method == 'spearman':
raise ValueError('not implemented: {}'.format(method))
return
else:
raise ValueError('not a valid method: {}'.format(method))
return
return cc
def max_perm_mcs_col(A, true_A, method='cos'):
"""
MCC or MCS by taking the maximum of all column permutations (without linear assignment).
A (np.ndarray or torch.Tendor, 2-dimensional): estimated mixing matrix.
true_A (np.ndarray or torch.Tendor, 2-dimensional): true mixing matrix.
method (str): Cosine similarity ('cos') or correlation ('pearson' or 'spearman').
"""
if type(A) != type(true_A):
raise ValueError('inputs are of different types: ({}, {})'.format(type(x), type(y)))
if isinstance(A, np.ndarray):
mean_mcc = get_mcs_np(A, true_A, method)
elif isinstance(A, torch.Tensor):
mean_mcc = get_mcs_pt(A, true_A, method)
else:
raise ValueError('not a supported input type: {}'.format(type(x)))
return mean_mcc