/
Distance.php
473 lines (440 loc) · 15.1 KB
/
Distance.php
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
<?php
namespace MathPHP\Statistics;
use MathPHP\Functions\Map;
use MathPHP\LinearAlgebra\NumericMatrix;
use MathPHP\Exception;
use MathPHP\LinearAlgebra\Vector;
/**
* Functions dealing with statistical distance.
* Related to probability and information theory and entropy.
*
* - Distances
* - Bhattacharyya
* - Hellinger
* - Mahalanobis
* - Jensen-Shannon
* - Minkowski
* - Euclidean
* - Manhattan
* - Cosine
* - Cosine similarity
* - Bray Curtis
* - Canberra
*
* In statistics, probability theory, and information theory, a statistical distance quantifies the distance between
* two statistical objects, which can be two random variables, or two probability distributions or samples, or the
* distance can be between an individual sample point and a population or a wider sample of points.
*
* https://en.wikipedia.org/wiki/Statistical_distance
*/
class Distance
{
private const ONE_TOLERANCE = 0.010001;
/**
* Bhattacharyya distance
* Measures the similarity of two discrete or continuous probability distributions.
* https://en.wikipedia.org/wiki/Bhattacharyya_distance
*
* For probability distributions p and q over the same domain X,
* the Bhattacharyya distance is defined as:
*
* DB(p,q) = -ln(BC(p,q))
*
* where BC is the Bhattacharyya coefficient:
*
* BC(p,q) = ∑ √(p(x) q(x))
* x∈X
*
* @param array $p distribution p
* @param array $q distribution q
*
* @return float distance between distributions
*
* @throws Exception\BadDataException if p and q do not have the same number of elements
* @throws Exception\BadDataException if p and q are not probability distributions that add up to 1
*/
public static function bhattacharyya(array $p, array $q): float
{
// Arrays must have the same number of elements
if (\count($p) !== \count($q)) {
throw new Exception\BadDataException('p and q must have the same number of elements');
}
// Probability distributions must add up to 1.0
if ((\abs(\array_sum($p) - 1) > self::ONE_TOLERANCE) || (\abs(\array_sum($q) - 1) > self::ONE_TOLERANCE)) {
throw new Exception\BadDataException('Distributions p and q must add up to 1');
}
// ∑ √(p(x) q(x))
$BC⟮p、q⟯ = \array_sum(Map\Single::sqrt(Map\Multi::multiply($p, $q)));
return -\log($BC⟮p、q⟯);
}
/**
* Hellinger distance
* Used to quantify the similarity between two probability distributions. It is a type of f-divergence.
* https://en.wikipedia.org/wiki/Hellinger_distance
*
* 1 _______________
* H(P,Q) = -- √ ∑ (√pᵢ - √qᵢ)²
* √2
*
* @param array $p distribution p
* @param array $q distribution q
*
* @return float difference between distributions
*
* @throws Exception\BadDataException if p and q do not have the same number of elements
* @throws Exception\BadDataException if p and q are not probability distributions that add up to 1
*/
public static function hellinger(array $p, array $q): float
{
// Arrays must have the same number of elements
if (\count($p) !== \count($q)) {
throw new Exception\BadDataException('p and q must have the same number of elements');
}
// Probability distributions must add up to 1.0
if ((\abs(\array_sum($p) - 1) > self::ONE_TOLERANCE) || (\abs(\array_sum($q) - 1) > self::ONE_TOLERANCE)) {
throw new Exception\BadDataException('Distributions p and q must add up to 1');
}
// Defensive measures against taking the log of 0 which would be -∞ or dividing by 0
$p = \array_map(
function ($pᵢ) {
return $pᵢ == 0 ? 1e-15 : $pᵢ;
},
$p
);
$q = \array_map(
function ($qᵢ) {
return $qᵢ == 0 ? 1e-15 : $qᵢ;
},
$q
);
// √ ∑ (√pᵢ - √qᵢ)²
$√∑⟮√pᵢ − √qᵢ⟯² = \sqrt(\array_sum(\array_map(
function ($pᵢ, $qᵢ) {
return (\sqrt($pᵢ) - \sqrt($qᵢ)) ** 2;
},
$p,
$q
)));
return (1 / \sqrt(2)) * $√∑⟮√pᵢ − √qᵢ⟯²;
}
/**
* Jensen-Shannon distance
* Square root of the Jensen-Shannon divergence
* https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence
*
* _____________________
* / 1 1
* \ / - D(P‖M) + - D(Q‖M)
* \/ 2 2
*
* 1
* where M = - (P + Q)
* 2
*
* D(P‖Q) = Kullback-Leibler divergence
*
* @param array $p distribution p
* @param array $q distribution q
*
* @return float
*
* @throws Exception\BadDataException if p and q do not have the same number of elements
* @throws Exception\BadDataException if p and q are not probability distributions that add up to 1
*/
public static function jensenShannon(array $p, array $q): float
{
return \sqrt(Divergence::jensenShannon($p, $q));
}
/**
* Mahalanobis distance
*
* https://en.wikipedia.org/wiki/Mahalanobis_distance
*
* The Mahalanobis distance measures the distance between two points in multidimensional
* space, scaled by the standard deviation of the data in each dimension.
*
* If x and y are vectors of points in space, and S is the covariance matrix of that space,
* the Mahalanobis distance, D, of the point within the space is:
*
* D = √[(x-y)ᵀ S⁻¹ (x-y)]
*
* If y is not provided, the distances will be calculated from x to the centroid of the dataset.
*
* The Mahalanobis distance can also be used to measure the distance between two sets of data.
* If x has more than one column, the combined data covariance matrix is used, and the distance
* will be calculated between the centroids of each data set.
*
* @param NumericMatrix $x a vector in the vector space. ie [[1],[2],[4]] or a matrix of data
* @param NumericMatrix $data an array of data. i.e. [[1,2,3,4],[6,2,8,1],[0,4,8,1]]
* @param NumericMatrix|null $y a vector in the vector space
*
* @return float Mahalanobis Distance
*
* @throws Exception\BadParameterException
* @throws Exception\IncorrectTypeException
* @throws Exception\MatrixException
* @throws Exception\OutOfBoundsException
* @throws Exception\VectorException
*/
public static function mahalanobis(NumericMatrix $x, NumericMatrix $data, NumericMatrix $y = null): float
{
$Centroid = $data->rowMeans()->asColumnMatrix();
$Nx = $x->getN();
if ($Nx > 1) {
// Combined covariance Matrix
$S = $data->augment($x)->covarianceMatrix();
$diff = $x->rowMeans()->asColumnMatrix()->subtract($Centroid);
} else {
$S = $data->covarianceMatrix();
if ($y === null) {
$y = $Centroid;
}
$diff = $x->subtract($y);
}
$S⁻¹ = $S->inverse();
$D = $diff->transpose()->multiply($S⁻¹)->multiply($diff);
return \sqrt($D[0][0]);
}
/**
* Minkowski distance
*
* https://en.wikipedia.org/wiki/Minkowski_distance
*
* (Σ|xᵢ - yᵢ|ᵖ)¹/ᵖ
*
* @param float[] $xs input array
* @param float[] $ys input array
* @param int $p order of the norm of the difference
*
* @return float
*
* @throws Exception\BadDataException if p and q do not have the same number of elements
*/
public static function minkowski(array $xs, array $ys, int $p): float
{
// Arrays must have the same number of elements
$n = \count($xs);
if ($n !== \count($ys)) {
throw new Exception\BadDataException('x and y must have the same number of elements');
}
if ($p < 1) {
throw new Exception\BadDataException("p must be ≥ 1. Given $p");
}
$∑|xᵢ − yᵢ⟯ᵖ = \array_sum(
\array_map(
function ($x, $y) use ($p) {
return \abs($x - $y) ** $p;
},
$xs,
$ys
)
);
return $∑|xᵢ − yᵢ⟯ᵖ ** (1 / $p);
}
/**
* Euclidean distance
*
* https://en.wikipedia.org/wiki/Euclidean_distance
*
* A generalized term for the Euclidean norm is the L² norm or L² distance.
*
* (Σ|xᵢ - yᵢ|²)¹/²
*
* @param float[] $xs input array
* @param float[] $ys input array
*
* @return float
*
* @throws Exception\BadDataException if p and q do not have the same number of elements
*/
public static function euclidean(array $xs, array $ys): float
{
return self::minkowski($xs, $ys, 2);
}
/**
* Manhattan distance (Taxicab geometry)
*
* https://en.wikipedia.org/wiki/Taxicab_geometry
*
* The taxicab metric is also known as rectilinear distance, L₁ distance, L¹ distance , snake distance, city block
* distance, Manhattan distance or Manhattan length, with corresponding variations in the name of the geometry.
*
* Σ|xᵢ - yᵢ|
*
* @param float[] $xs input array
* @param float[] $ys input array
*
* @return float
*
* @throws Exception\BadDataException if p and q do not have the same number of elements
*/
public static function manhattan(array $xs, array $ys): float
{
return self::minkowski($xs, $ys, 1);
}
/**
* Cosine distance
*
* A⋅B
* 1 - ---------
* ‖A‖₂⋅‖B‖₂
*
* where
* A⋅B is the dot product of A and B
* ‖A‖₂ is the L² norm of A
* ‖B‖₂ is the L² norm of B
*
* Similar to Python: scipy.spatial.distance.cosine(u, v, w=None)
*
* @param float[] $A
* @param float[] $B
*
* @return float
*
* @throws Exception\BadDataException if null vector passed in
* @throws Exception\VectorException
*/
public static function cosine(array $A, array $B): float
{
if (\count(\array_unique($A)) === 1 && \end($A) == 0) {
throw new Exception\BadDataException('A is the null vector');
}
if (\count(\array_unique($B)) === 1 && \end($B) == 0) {
throw new Exception\BadDataException('B is the null vector');
}
$A = new Vector($A);
$B = new Vector($B);
$A⋅B = $A->dotProduct($B);
$‖A‖₂⋅‖B‖₂ = $A->l2Norm() * $B->l2Norm();
return 1 - ($A⋅B / $‖A‖₂⋅‖B‖₂);
}
/**
* Cosine similarity
* A measure of similarity between two non-zero vectors of an inner product space.
* Defined to equal the cosine of the angle between them, which is also the same as the inner product of the same
* vectors normalized to both have length 1.
*
* A⋅B
* cos α = ---------
* ‖A‖₂⋅‖B‖₂
*
* where
* A⋅B is the dot product of A and B
* ‖A‖₂ is the L² norm of A
* ‖B‖₂ is the L² norm of B
*
* Similar to Python: 1 - scipy.spatial.distance.cosine(u, v, w=None)
*
* @param float[] $A
* @param float[] $B
*
* @return float
*
* @throws Exception\BadDataException if null vector passed in
* @throws Exception\VectorException
*/
public static function cosineSimilarity(array $A, array $B): float
{
return 1 - self::cosine($A, $B);
}
/**
* Bray Curtis Distance
*
* https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.braycurtis.html#scipy.spatial.distance.braycurtis
*
* ∑|uᵢ − vᵢ|
* -----------
* ∑|uᵢ + vᵢ|
*
* @param array $u
* @param array $v
*
* @return float
*/
public static function brayCurtis(array $u, array $v): float
{
if (\count($u) !== \count($v)) {
throw new Exception\BadDataException('u and v must have the same number of elements');
}
$uZero = \count(\array_unique($u)) === 1 && \end($u) == 0;
$vZero = \count(\array_unique($u)) === 1 && \end($v) == 0;
if ($uZero && $vZero) {
return \NAN;
}
$∑|uᵢ − vᵢ| = \array_sum(\array_map(
function (float $uᵢ, float $vᵢ) {
return \abs($uᵢ - $vᵢ);
},
$u,
$v
));
$∑|uᵢ + vᵢ| = \array_sum(\array_map(
function (float $uᵢ, float $vᵢ) {
return \abs($uᵢ + $vᵢ);
},
$u,
$v
));
if ($∑|uᵢ + vᵢ| == 0) {
return \NAN;
}
return $∑|uᵢ − vᵢ| / $∑|uᵢ + vᵢ|;
}
/**
* Canberra Distance
* A numerical measure of the distance between pairs of points in a vector space
* It is a weighted version of L₁ (Manhattan) distance.
*
* https://en.wikipedia.org/wiki/Canberra_distance
* http://www.code10.info/index.php?option=com_content&view=article&id=49:article_canberra-distance&catid=38:cat_coding_algorithms_data-similarity&Itemid=57
*
* |pᵢ − qᵢ|
* d(p,q) = ∑ --------------
* |pᵢ| + |qᵢ|
*
* @param array $p
* @param array $q
*
* @return float
*/
public static function canberra(array $p, array $q): float
{
if (\count($p) !== \count($q)) {
throw new Exception\BadDataException('p and q must have the same number of elements');
}
$pZero = \count(\array_unique($p)) === 1 && \end($p) == 0;
$qZero = \count(\array_unique($p)) === 1 && \end($q) == 0;
if ($pZero && $qZero) {
return \NAN;
}
// Numerators |pᵢ − qᵢ|
$|p − q| = \array_map(
function (float $pᵢ, float $qᵢ) {
return \abs($pᵢ - $qᵢ);
},
$p,
$q
);
// Denominators |pᵢ| + |qᵢ|
$|p| + |q| = \array_map(
function (float $p, float $q) {
return \abs($p) + \abs($q);
},
$p,
$q
);
// Sum of quotients with non-zero denominators
// |pᵢ − qᵢ|
// ∑ --------------
// |pᵢ| + |qᵢ|
return \array_sum(\array_map(
function (float $|pᵢ − qᵢ|, float $|pᵢ| + |qᵢ|) {
return $|pᵢ| + |qᵢ| == 0
? 0
: $|pᵢ − qᵢ| / $|pᵢ| + |qᵢ|;
},
$|p − q|,
$|p| + |q|
));
}
}