|
| 1 | +from __future__ import annotations |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +from .mean_var import IncrementalMeanVariance |
| 5 | + |
| 6 | +class IncrementalCovarianceCorrelation: |
| 7 | + """Incrementally computes vectorized covariance and correlation. |
| 8 | +
|
| 9 | + When feeding every row of an MxN matrix A and every row of an MxO matrix B, this code |
| 10 | + updates a co-variance NxO matrix C where every cell C[r,c] is the covariance between |
| 11 | + A[:,r] and B[:,c]. |
| 12 | +
|
| 13 | + This code is useful when the matrixes A and B cannot be not present |
| 14 | + in memory at one given time. |
| 15 | +
|
| 16 | + ``` |
| 17 | + nX = 100 |
| 18 | + nY1 = 30 |
| 19 | + nY2 = 50 |
| 20 | +
|
| 21 | + m1 = np.random.randn(nX, nY1) |
| 22 | + m2 = np.random.randn(nX, nY2) |
| 23 | +
|
| 24 | + ic = IncrementalCovarianceCorrelation(nY1, nY2) |
| 25 | +
|
| 26 | + for row in range(nX): |
| 27 | + ic.update(m1[row,:], m2[row,:]) |
| 28 | +
|
| 29 | + reference_covariance = (1 / (nX - 1)) * np.matmul((m1 - np.mean(m1, axis=0)).T, (m2 - np.mean(m2, axis=0))) |
| 30 | + reference_m1_stddev = np.std(m1, axis=0, ddof=1) |
| 31 | + reference_m2_stddev = np.std(m2, axis=0, ddof=1) |
| 32 | + reference_1_over_m1_stddev = (1 / numpy_m1_stddev).reshape(numpy_m1_stddev.size, 1) |
| 33 | + reference_1_over_m2_stddev = (1 / numpy_m2_stddev).reshape(1,numpy_m2_stddev.size) |
| 34 | + reference_correlation = numpy_covariance * numpy_1_over_m1_stddev * numpy_1_over_m2_stddev |
| 35 | +
|
| 36 | + assert (np.allclose(ic.getCovariance(), reference_covariance)) |
| 37 | + assert (np.allclose(ic.getCorrelation(), reference_correlation)) |
| 38 | +
|
| 39 | + ``` |
| 40 | + """ |
| 41 | + |
| 42 | + def __init__(self, nX, nY): |
| 43 | + """Initialize with the #columns for matrices A and B""" |
| 44 | + self.nX = nX |
| 45 | + self.nY = nY |
| 46 | + self.imX = IncrementalMeanVariance(nX) |
| 47 | + self.imY = IncrementalMeanVariance(nY) |
| 48 | + self.cov = np.zeros((nX, nY), dtype=np.float64) |
| 49 | + self.n = 0 |
| 50 | + |
| 51 | + def update(self, x, y): |
| 52 | + """Updates the covariance matrix with a single row of matrix A and a single row of matrix B""" |
| 53 | + if len(x) != self.nX: |
| 54 | + raise Exception("wrong x length") |
| 55 | + if len(y) != self.nY: |
| 56 | + raise Exception("wrong y length") |
| 57 | + |
| 58 | + self.n += 1 |
| 59 | + f = (self.n - 1) / self.n |
| 60 | + |
| 61 | + mfX = (x - self.imX.mean) * f |
| 62 | + mfY = y - self.imY.mean |
| 63 | + |
| 64 | + self.cov += np.tensordot(mfX, mfY, axes=0) |
| 65 | + |
| 66 | + self.imX.update(x) |
| 67 | + self.imY.update(y) |
| 68 | + |
| 69 | + def add(self, x: IncrementalCovarianceCorrelation): |
| 70 | + """Merges another object of IncrementalCovarianceCorrelation into this co-variance matrix. This is useful in |
| 71 | + parallelized computations, where different nodes compute co-variances over different |
| 72 | + ranges of rows""" |
| 73 | + n = self.n + x.n |
| 74 | + f = (self.n * x.n ** 2 + x.n * self.n ** 2) / (n ** 2) |
| 75 | + |
| 76 | + deltaX = self.imX.mean - x.imX.mean |
| 77 | + deltaX = deltaX.reshape(deltaX.size, 1) * f |
| 78 | + |
| 79 | + deltaY = self.imY.mean - x.imY.mean |
| 80 | + deltaY = deltaY.reshape(1, deltaY.size) |
| 81 | + |
| 82 | + self.cov += x.cov + deltaX * deltaY |
| 83 | + self.n = n |
| 84 | + self.imX.add(x.imX) |
| 85 | + self.imY.add(x.imY) |
| 86 | + |
| 87 | + def getCovariance(self): |
| 88 | + """Returns the scaled co-variance matrix with 1 degree of freedom""" |
| 89 | + return 1 / (self.n - 1) * self.cov |
| 90 | + |
| 91 | + def getCorrelation(self): |
| 92 | + """Returns Pearson's correlation matrix""" |
| 93 | + sX = 1 / np.sqrt(self.imX.getVariance()) |
| 94 | + sX = sX.reshape(sX.size, 1) |
| 95 | + sY = 1 / np.sqrt(self.imY.getVariance()) |
| 96 | + sY = sY.reshape(1, sY.size) |
| 97 | + return 1 / (self.n - 1) * self.cov * sX * sY |
0 commit comments