forked from gonum/gonum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstat.go
1400 lines (1297 loc) · 36.9 KB
/
stat.go
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright ©2014 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package stat
import (
"math"
"sort"
"gonum.org/v1/gonum/floats"
)
// CumulantKind specifies the behavior for calculating the empirical CDF or Quantile
type CumulantKind int
// List of supported CumulantKind values for the Quantile function.
// Constant values should match the R nomenclature. See
// https://en.wikipedia.org/wiki/Quantile#Estimating_the_quantiles_of_a_population
const (
// Empirical treats the distribution as the actual empirical distribution.
Empirical CumulantKind = 1
// LinInterp linearly interpolates the empirical distribution between sample values, with a flat extrapolation.
LinInterp CumulantKind = 4
)
// bhattacharyyaCoeff computes the Bhattacharyya Coefficient for probability distributions given by:
//
// \sum_i \sqrt{p_i q_i}
//
// It is assumed that p and q have equal length.
func bhattacharyyaCoeff(p, q []float64) float64 {
var bc float64
for i, a := range p {
bc += math.Sqrt(a * q[i])
}
return bc
}
// Bhattacharyya computes the distance between the probability distributions p and q given by:
//
// -\ln ( \sum_i \sqrt{p_i q_i} )
//
// The lengths of p and q must be equal. It is assumed that p and q sum to 1.
func Bhattacharyya(p, q []float64) float64 {
if len(p) != len(q) {
panic("stat: slice length mismatch")
}
bc := bhattacharyyaCoeff(p, q)
return -math.Log(bc)
}
// CDF returns the empirical cumulative distribution function value of x, that is
// the fraction of the samples less than or equal to q. The
// exact behavior is determined by the CumulantKind. CDF is theoretically
// the inverse of the Quantile function, though it may not be the actual inverse
// for all values q and CumulantKinds.
//
// The x data must be sorted in increasing order. If weights is nil then all
// of the weights are 1. If weights is not nil, then len(x) must equal len(weights).
// CDF will panic if the length of x is zero.
//
// CumulantKind behaviors:
// - Empirical: Returns the lowest fraction for which q is greater than or equal
// to that fraction of samples
func CDF(q float64, c CumulantKind, x, weights []float64) float64 {
if weights != nil && len(x) != len(weights) {
panic("stat: slice length mismatch")
}
if floats.HasNaN(x) {
return math.NaN()
}
if len(x) == 0 {
panic("stat: zero length slice")
}
if !sort.Float64sAreSorted(x) {
panic("x data are not sorted")
}
if q < x[0] {
return 0
}
if q >= x[len(x)-1] {
return 1
}
var sumWeights float64
if weights == nil {
sumWeights = float64(len(x))
} else {
sumWeights = floats.Sum(weights)
}
// Calculate the index
switch c {
case Empirical:
// Find the smallest value that is greater than that percent of the samples
var w float64
for i, v := range x {
if v > q {
return w / sumWeights
}
if weights == nil {
w++
} else {
w += weights[i]
}
}
panic("impossible")
default:
panic("stat: bad cumulant kind")
}
}
// ChiSquare computes the chi-square distance between the observed frequencies 'obs' and
// expected frequencies 'exp' given by:
//
// \sum_i (obs_i-exp_i)^2 / exp_i
//
// The lengths of obs and exp must be equal.
func ChiSquare(obs, exp []float64) float64 {
if len(obs) != len(exp) {
panic("stat: slice length mismatch")
}
var result float64
for i, a := range obs {
b := exp[i]
if a == 0 && b == 0 {
continue
}
result += (a - b) * (a - b) / b
}
return result
}
// CircularMean returns the circular mean of the dataset.
//
// atan2(\sum_i w_i * sin(alpha_i), \sum_i w_i * cos(alpha_i))
//
// If weights is nil then all of the weights are 1. If weights is not nil, then
// len(x) must equal len(weights).
func CircularMean(x, weights []float64) float64 {
if weights != nil && len(x) != len(weights) {
panic("stat: slice length mismatch")
}
var aX, aY float64
if weights != nil {
for i, v := range x {
aX += weights[i] * math.Cos(v)
aY += weights[i] * math.Sin(v)
}
} else {
for _, v := range x {
aX += math.Cos(v)
aY += math.Sin(v)
}
}
return math.Atan2(aY, aX)
}
// Correlation returns the weighted correlation between the samples of x and y
// with the given means.
//
// sum_i {w_i (x_i - meanX) * (y_i - meanY)} / (stdX * stdY)
//
// The lengths of x and y must be equal. If weights is nil then all of the
// weights are 1. If weights is not nil, then len(x) must equal len(weights).
func Correlation(x, y, weights []float64) float64 {
// This is a two-pass corrected implementation. It is an adaptation of the
// algorithm used in the MeanVariance function, which applies a correction
// to the typical two pass approach.
if len(x) != len(y) {
panic("stat: slice length mismatch")
}
xu := Mean(x, weights)
yu := Mean(y, weights)
var (
sxx float64
syy float64
sxy float64
xcompensation float64
ycompensation float64
)
if weights == nil {
for i, xv := range x {
yv := y[i]
xd := xv - xu
yd := yv - yu
sxx += xd * xd
syy += yd * yd
sxy += xd * yd
xcompensation += xd
ycompensation += yd
}
// xcompensation and ycompensation are from Chan, et. al.
// referenced in the MeanVariance function. They are analogous
// to the second term in (1.7) in that paper.
sxx -= xcompensation * xcompensation / float64(len(x))
syy -= ycompensation * ycompensation / float64(len(x))
return (sxy - xcompensation*ycompensation/float64(len(x))) / math.Sqrt(sxx*syy)
}
var sumWeights float64
for i, xv := range x {
w := weights[i]
yv := y[i]
xd := xv - xu
wxd := w * xd
yd := yv - yu
wyd := w * yd
sxx += wxd * xd
syy += wyd * yd
sxy += wxd * yd
xcompensation += wxd
ycompensation += wyd
sumWeights += w
}
// xcompensation and ycompensation are from Chan, et. al.
// referenced in the MeanVariance function. They are analogous
// to the second term in (1.7) in that paper, except they use
// the sumWeights instead of the sample count.
sxx -= xcompensation * xcompensation / sumWeights
syy -= ycompensation * ycompensation / sumWeights
return (sxy - xcompensation*ycompensation/sumWeights) / math.Sqrt(sxx*syy)
}
// Kendall returns the weighted Tau-a Kendall correlation between the
// samples of x and y. The Kendall correlation measures the quantity of
// concordant and discordant pairs of numbers. If weights are specified then
// each pair is weighted by weights[i] * weights[j] and the final sum is
// normalized to stay between -1 and 1.
// The lengths of x and y must be equal. If weights is nil then all of the
// weights are 1. If weights is not nil, then len(x) must equal len(weights).
func Kendall(x, y, weights []float64) float64 {
if len(x) != len(y) {
panic("stat: slice length mismatch")
}
var (
cc float64 // number of concordant pairs
dc float64 // number of discordant pairs
n = len(x)
)
if weights == nil {
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
if i == j {
continue
}
if math.Signbit(x[j]-x[i]) == math.Signbit(y[j]-y[i]) {
cc++
} else {
dc++
}
}
}
return (cc - dc) / float64(n*(n-1)/2)
}
var sumWeights float64
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
if i == j {
continue
}
weight := weights[i] * weights[j]
if math.Signbit(x[j]-x[i]) == math.Signbit(y[j]-y[i]) {
cc += weight
} else {
dc += weight
}
sumWeights += weight
}
}
return float64(cc-dc) / sumWeights
}
// Covariance returns the weighted covariance between the samples of x and y.
//
// sum_i {w_i (x_i - meanX) * (y_i - meanY)} / (sum_j {w_j} - 1)
//
// The lengths of x and y must be equal. If weights is nil then all of the
// weights are 1. If weights is not nil, then len(x) must equal len(weights).
func Covariance(x, y, weights []float64) float64 {
// This is a two-pass corrected implementation. It is an adaptation of the
// algorithm used in the MeanVariance function, which applies a correction
// to the typical two pass approach.
if len(x) != len(y) {
panic("stat: slice length mismatch")
}
xu := Mean(x, weights)
yu := Mean(y, weights)
return covarianceMeans(x, y, weights, xu, yu)
}
// covarianceMeans returns the weighted covariance between x and y with the mean
// of x and y already specified. See the documentation of Covariance for more
// information.
func covarianceMeans(x, y, weights []float64, xu, yu float64) float64 {
var (
ss float64
xcompensation float64
ycompensation float64
)
if weights == nil {
for i, xv := range x {
yv := y[i]
xd := xv - xu
yd := yv - yu
ss += xd * yd
xcompensation += xd
ycompensation += yd
}
// xcompensation and ycompensation are from Chan, et. al.
// referenced in the MeanVariance function. They are analogous
// to the second term in (1.7) in that paper.
return (ss - xcompensation*ycompensation/float64(len(x))) / float64(len(x)-1)
}
var sumWeights float64
for i, xv := range x {
w := weights[i]
yv := y[i]
wxd := w * (xv - xu)
yd := (yv - yu)
ss += wxd * yd
xcompensation += wxd
ycompensation += w * yd
sumWeights += w
}
// xcompensation and ycompensation are from Chan, et. al.
// referenced in the MeanVariance function. They are analogous
// to the second term in (1.7) in that paper, except they use
// the sumWeights instead of the sample count.
return (ss - xcompensation*ycompensation/sumWeights) / (sumWeights - 1)
}
// CrossEntropy computes the cross-entropy between the two distributions specified
// in p and q.
func CrossEntropy(p, q []float64) float64 {
if len(p) != len(q) {
panic("stat: slice length mismatch")
}
var ce float64
for i, v := range p {
if v != 0 {
ce -= v * math.Log(q[i])
}
}
return ce
}
// Entropy computes the Shannon entropy of a distribution or the distance between
// two distributions. The natural logarithm is used.
// - sum_i (p_i * log_e(p_i))
func Entropy(p []float64) float64 {
var e float64
for _, v := range p {
if v != 0 { // Entropy needs 0 * log(0) == 0.
e -= v * math.Log(v)
}
}
return e
}
// ExKurtosis returns the population excess kurtosis of the sample.
// The kurtosis is defined by the 4th moment of the mean divided by the squared
// variance. The excess kurtosis subtracts 3.0 so that the excess kurtosis of
// the normal distribution is zero.
// If weights is nil then all of the weights are 1. If weights is not nil, then
// len(x) must equal len(weights).
func ExKurtosis(x, weights []float64) float64 {
mean, std := MeanStdDev(x, weights)
if weights == nil {
var e float64
for _, v := range x {
z := (v - mean) / std
e += z * z * z * z
}
mul, offset := kurtosisCorrection(float64(len(x)))
return e*mul - offset
}
var (
e float64
sumWeights float64
)
for i, v := range x {
z := (v - mean) / std
e += weights[i] * z * z * z * z
sumWeights += weights[i]
}
mul, offset := kurtosisCorrection(sumWeights)
return e*mul - offset
}
// n is the number of samples
// see https://en.wikipedia.org/wiki/Kurtosis
func kurtosisCorrection(n float64) (mul, offset float64) {
return ((n + 1) / (n - 1)) * (n / (n - 2)) * (1 / (n - 3)), 3 * ((n - 1) / (n - 2)) * ((n - 1) / (n - 3))
}
// GeometricMean returns the weighted geometric mean of the dataset
//
// \prod_i {x_i ^ w_i}
//
// This only applies with positive x and positive weights. If weights is nil
// then all of the weights are 1. If weights is not nil, then len(x) must equal
// len(weights).
func GeometricMean(x, weights []float64) float64 {
if weights == nil {
var s float64
for _, v := range x {
s += math.Log(v)
}
s /= float64(len(x))
return math.Exp(s)
}
if len(x) != len(weights) {
panic("stat: slice length mismatch")
}
var (
s float64
sumWeights float64
)
for i, v := range x {
s += weights[i] * math.Log(v)
sumWeights += weights[i]
}
s /= sumWeights
return math.Exp(s)
}
// HarmonicMean returns the weighted harmonic mean of the dataset
//
// \sum_i {w_i} / ( sum_i {w_i / x_i} )
//
// This only applies with positive x and positive weights.
// If weights is nil then all of the weights are 1. If weights is not nil, then
// len(x) must equal len(weights).
func HarmonicMean(x, weights []float64) float64 {
if weights != nil && len(x) != len(weights) {
panic("stat: slice length mismatch")
}
// TODO(btracey): Fix this to make it more efficient and avoid allocation.
// This can be numerically unstable (for example if x is very small).
// W = \sum_i {w_i}
// hm = exp(log(W) - log(\sum_i w_i / x_i))
logs := make([]float64, len(x))
var W float64
for i := range x {
if weights == nil {
logs[i] = -math.Log(x[i])
W++
continue
}
logs[i] = math.Log(weights[i]) - math.Log(x[i])
W += weights[i]
}
// Sum all of the logs
v := floats.LogSumExp(logs) // This computes log(\sum_i { w_i / x_i}).
return math.Exp(math.Log(W) - v)
}
// Hellinger computes the distance between the probability distributions p and q given by:
//
// \sqrt{ 1 - \sum_i \sqrt{p_i q_i} }
//
// The lengths of p and q must be equal. It is assumed that p and q sum to 1.
func Hellinger(p, q []float64) float64 {
if len(p) != len(q) {
panic("stat: slice length mismatch")
}
bc := bhattacharyyaCoeff(p, q)
return math.Sqrt(1 - bc)
}
// Histogram sums up the weighted number of data points in each bin.
// The weight of data point x[i] will be placed into count[j] if
// dividers[j] <= x < dividers[j+1]. The "span" function in the floats package can assist
// with bin creation.
//
// The following conditions on the inputs apply:
// - The count variable must either be nil or have length of one less than dividers.
// - The values in dividers must be sorted (use the sort package).
// - The x values must be sorted.
// - If weights is nil then all of the weights are 1.
// - If weights is not nil, then len(x) must equal len(weights).
func Histogram(count, dividers, x, weights []float64) []float64 {
if weights != nil && len(x) != len(weights) {
panic("stat: slice length mismatch")
}
if count == nil {
count = make([]float64, len(dividers)-1)
}
if len(dividers) < 2 {
panic("histogram: fewer than two dividers")
}
if len(count) != len(dividers)-1 {
panic("histogram: bin count mismatch")
}
if !sort.Float64sAreSorted(dividers) {
panic("histogram: dividers are not sorted")
}
if !sort.Float64sAreSorted(x) {
panic("histogram: x data are not sorted")
}
for i := range count {
count[i] = 0
}
if len(x) == 0 {
return count
}
if x[0] < dividers[0] {
panic("histogram: minimum x value is less than lowest divider")
}
if dividers[len(dividers)-1] <= x[len(x)-1] {
panic("histogram: maximum x value is greater than or equal to highest divider")
}
idx := 0
comp := dividers[idx+1]
if weights == nil {
for _, v := range x {
if v < comp {
// Still in the current bucket.
count[idx]++
continue
}
// Find the next divider where v is less than the divider.
for j := idx + 1; j < len(dividers); j++ {
if v < dividers[j+1] {
idx = j
comp = dividers[j+1]
break
}
}
count[idx]++
}
return count
}
for i, v := range x {
if v < comp {
// Still in the current bucket.
count[idx] += weights[i]
continue
}
// Need to find the next divider where v is less than the divider.
for j := idx + 1; j < len(count); j++ {
if v < dividers[j+1] {
idx = j
comp = dividers[j+1]
break
}
}
count[idx] += weights[i]
}
return count
}
// JensenShannon computes the JensenShannon divergence between the distributions
// p and q. The Jensen-Shannon divergence is defined as
//
// m = 0.5 * (p + q)
// JS(p, q) = 0.5 ( KL(p, m) + KL(q, m) )
//
// Unlike Kullback-Leibler, the Jensen-Shannon distance is symmetric. The value
// is between 0 and ln(2).
func JensenShannon(p, q []float64) float64 {
if len(p) != len(q) {
panic("stat: slice length mismatch")
}
var js float64
for i, v := range p {
qi := q[i]
m := 0.5 * (v + qi)
if v != 0 {
// add kl from p to m
js += 0.5 * v * (math.Log(v) - math.Log(m))
}
if qi != 0 {
// add kl from q to m
js += 0.5 * qi * (math.Log(qi) - math.Log(m))
}
}
return js
}
// KolmogorovSmirnov computes the largest distance between two empirical CDFs.
// Each dataset x and y consists of sample locations and counts, xWeights and
// yWeights, respectively.
//
// x and y may have different lengths, though len(x) must equal len(xWeights), and
// len(y) must equal len(yWeights). Both x and y must be sorted.
//
// Special cases are:
//
// = 0 if len(x) == len(y) == 0
// = 1 if len(x) == 0, len(y) != 0 or len(x) != 0 and len(y) == 0
func KolmogorovSmirnov(x, xWeights, y, yWeights []float64) float64 {
if xWeights != nil && len(x) != len(xWeights) {
panic("stat: slice length mismatch")
}
if yWeights != nil && len(y) != len(yWeights) {
panic("stat: slice length mismatch")
}
if len(x) == 0 || len(y) == 0 {
if len(x) == 0 && len(y) == 0 {
return 0
}
return 1
}
if floats.HasNaN(x) {
return math.NaN()
}
if floats.HasNaN(y) {
return math.NaN()
}
if !sort.Float64sAreSorted(x) {
panic("x data are not sorted")
}
if !sort.Float64sAreSorted(y) {
panic("y data are not sorted")
}
xWeightsNil := xWeights == nil
yWeightsNil := yWeights == nil
var (
maxDist float64
xSum, ySum float64
xCdf, yCdf float64
xIdx, yIdx int
)
if xWeightsNil {
xSum = float64(len(x))
} else {
xSum = floats.Sum(xWeights)
}
if yWeightsNil {
ySum = float64(len(y))
} else {
ySum = floats.Sum(yWeights)
}
xVal := x[0]
yVal := y[0]
// Algorithm description:
// The goal is to find the maximum difference in the empirical CDFs for the
// two datasets. The CDFs are piecewise-constant, and thus the distance
// between the CDFs will only change at the values themselves.
//
// To find the maximum distance, step through the data in ascending order
// of value between the two datasets. At each step, compute the empirical CDF
// and compare the local distance with the maximum distance.
// Due to some corner cases, equal data entries must be tallied simultaneously.
for {
switch {
case xVal < yVal:
xVal, xCdf, xIdx = updateKS(xIdx, xCdf, xSum, x, xWeights, xWeightsNil)
case yVal < xVal:
yVal, yCdf, yIdx = updateKS(yIdx, yCdf, ySum, y, yWeights, yWeightsNil)
case xVal == yVal:
newX := x[xIdx]
newY := y[yIdx]
if newX < newY {
xVal, xCdf, xIdx = updateKS(xIdx, xCdf, xSum, x, xWeights, xWeightsNil)
} else if newY < newX {
yVal, yCdf, yIdx = updateKS(yIdx, yCdf, ySum, y, yWeights, yWeightsNil)
} else {
// Update them both, they'll be equal next time and the right
// thing will happen.
xVal, xCdf, xIdx = updateKS(xIdx, xCdf, xSum, x, xWeights, xWeightsNil)
yVal, yCdf, yIdx = updateKS(yIdx, yCdf, ySum, y, yWeights, yWeightsNil)
}
default:
panic("unreachable")
}
dist := math.Abs(xCdf - yCdf)
if dist > maxDist {
maxDist = dist
}
// Both xCdf and yCdf will equal 1 at the end, so if we have reached the
// end of either sample list, the distance is as large as it can be.
if xIdx == len(x) || yIdx == len(y) {
return maxDist
}
}
}
// updateKS gets the next data point from one of the set. In doing so, it combines
// the weight of all the data points of equal value. Upon return, val is the new
// value of the data set, newCdf is the total combined CDF up until this point,
// and newIdx is the index of the next location in that sample to examine.
func updateKS(idx int, cdf, sum float64, values, weights []float64, isNil bool) (val, newCdf float64, newIdx int) {
// Sum up all the weights of consecutive values that are equal.
if isNil {
newCdf = cdf + 1/sum
} else {
newCdf = cdf + weights[idx]/sum
}
newIdx = idx + 1
for {
if newIdx == len(values) {
return values[newIdx-1], newCdf, newIdx
}
if values[newIdx-1] != values[newIdx] {
return values[newIdx], newCdf, newIdx
}
if isNil {
newCdf += 1 / sum
} else {
newCdf += weights[newIdx] / sum
}
newIdx++
}
}
// KullbackLeibler computes the Kullback-Leibler distance between the
// distributions p and q. The natural logarithm is used.
//
// sum_i(p_i * log(p_i / q_i))
//
// Note that the Kullback-Leibler distance is not symmetric;
// KullbackLeibler(p,q) != KullbackLeibler(q,p)
func KullbackLeibler(p, q []float64) float64 {
if len(p) != len(q) {
panic("stat: slice length mismatch")
}
var kl float64
for i, v := range p {
if v != 0 { // Entropy needs 0 * log(0) == 0.
kl += v * (math.Log(v) - math.Log(q[i]))
}
}
return kl
}
// LinearRegression computes the best-fit line
//
// y = alpha + beta*x
//
// to the data in x and y with the given weights. If origin is true, the
// regression is forced to pass through the origin.
//
// Specifically, LinearRegression computes the values of alpha and
// beta such that the total residual
//
// \sum_i w[i]*(y[i] - alpha - beta*x[i])^2
//
// is minimized. If origin is true, then alpha is forced to be zero.
//
// The lengths of x and y must be equal. If weights is nil then all of the
// weights are 1. If weights is not nil, then len(x) must equal len(weights).
func LinearRegression(x, y, weights []float64, origin bool) (alpha, beta float64) {
if len(x) != len(y) {
panic("stat: slice length mismatch")
}
if weights != nil && len(weights) != len(x) {
panic("stat: slice length mismatch")
}
w := 1.0
if origin {
var x2Sum, xySum float64
for i, xi := range x {
if weights != nil {
w = weights[i]
}
yi := y[i]
xySum += w * xi * yi
x2Sum += w * xi * xi
}
beta = xySum / x2Sum
return 0, beta
}
xu, xv := MeanVariance(x, weights)
yu := Mean(y, weights)
cov := covarianceMeans(x, y, weights, xu, yu)
beta = cov / xv
alpha = yu - beta*xu
return alpha, beta
}
// RSquared returns the coefficient of determination defined as
//
// R^2 = 1 - \sum_i w[i]*(y[i] - alpha - beta*x[i])^2 / \sum_i w[i]*(y[i] - mean(y))^2
//
// for the line
//
// y = alpha + beta*x
//
// and the data in x and y with the given weights.
//
// The lengths of x and y must be equal. If weights is nil then all of the
// weights are 1. If weights is not nil, then len(x) must equal len(weights).
func RSquared(x, y, weights []float64, alpha, beta float64) float64 {
if len(x) != len(y) {
panic("stat: slice length mismatch")
}
if weights != nil && len(weights) != len(x) {
panic("stat: slice length mismatch")
}
w := 1.0
yMean := Mean(y, weights)
var res, tot, d float64
for i, xi := range x {
if weights != nil {
w = weights[i]
}
yi := y[i]
fi := alpha + beta*xi
d = yi - fi
res += w * d * d
d = yi - yMean
tot += w * d * d
}
return 1 - res/tot
}
// RSquaredFrom returns the coefficient of determination defined as
//
// R^2 = 1 - \sum_i w[i]*(estimate[i] - value[i])^2 / \sum_i w[i]*(value[i] - mean(values))^2
//
// and the data in estimates and values with the given weights.
//
// The lengths of estimates and values must be equal. If weights is nil then
// all of the weights are 1. If weights is not nil, then len(values) must
// equal len(weights).
func RSquaredFrom(estimates, values, weights []float64) float64 {
if len(estimates) != len(values) {
panic("stat: slice length mismatch")
}
if weights != nil && len(weights) != len(values) {
panic("stat: slice length mismatch")
}
w := 1.0
mean := Mean(values, weights)
var res, tot, d float64
for i, val := range values {
if weights != nil {
w = weights[i]
}
d = val - estimates[i]
res += w * d * d
d = val - mean
tot += w * d * d
}
return 1 - res/tot
}
// RNoughtSquared returns the coefficient of determination defined as
//
// R₀^2 = \sum_i w[i]*(beta*x[i])^2 / \sum_i w[i]*y[i]^2
//
// for the line
//
// y = beta*x
//
// and the data in x and y with the given weights. RNoughtSquared should
// only be used for best-fit lines regressed through the origin.
//
// The lengths of x and y must be equal. If weights is nil then all of the
// weights are 1. If weights is not nil, then len(x) must equal len(weights).
func RNoughtSquared(x, y, weights []float64, beta float64) float64 {
if len(x) != len(y) {
panic("stat: slice length mismatch")
}
if weights != nil && len(weights) != len(x) {
panic("stat: slice length mismatch")
}
w := 1.0
var ssr, tot float64
for i, xi := range x {
if weights != nil {
w = weights[i]
}
fi := beta * xi
ssr += w * fi * fi
yi := y[i]
tot += w * yi * yi
}
return ssr / tot
}
// Mean computes the weighted mean of the data set.
//
// sum_i {w_i * x_i} / sum_i {w_i}
//
// If weights is nil then all of the weights are 1. If weights is not nil, then
// len(x) must equal len(weights).
func Mean(x, weights []float64) float64 {
if weights == nil {
return floats.Sum(x) / float64(len(x))
}
if len(x) != len(weights) {
panic("stat: slice length mismatch")
}
var (
sumValues float64
sumWeights float64
)
for i, w := range weights {
sumValues += w * x[i]
sumWeights += w
}
return sumValues / sumWeights
}
// Mode returns the most common value in the dataset specified by x and the
// given weights. Strict float64 equality is used when comparing values, so users
// should take caution. If several values are the mode, any of them may be returned.
func Mode(x, weights []float64) (val float64, count float64) {
if weights != nil && len(x) != len(weights) {
panic("stat: slice length mismatch")
}
if len(x) == 0 {
return 0, 0
}
m := make(map[float64]float64)
if weights == nil {
for _, v := range x {
m[v]++
}
} else {
for i, v := range x {
m[v] += weights[i]
}
}
var (
maxCount float64
max float64
)
for val, count := range m {
if count > maxCount {
maxCount = count
max = val
}
}
return max, maxCount
}
// BivariateMoment computes the weighted mixed moment between the samples x and y.
//
// E[(x - μ_x)^r*(y - μ_y)^s]
//
// No degrees of freedom correction is done.
// The lengths of x and y must be equal. If weights is nil then all of the
// weights are 1. If weights is not nil, then len(x) must equal len(weights).
func BivariateMoment(r, s float64, x, y, weights []float64) float64 {
meanX := Mean(x, weights)
meanY := Mean(y, weights)
if len(x) != len(y) {
panic("stat: slice length mismatch")
}
if weights == nil {
var m float64
for i, vx := range x {
vy := y[i]
m += math.Pow(vx-meanX, r) * math.Pow(vy-meanY, s)
}
return m / float64(len(x))
}
if len(weights) != len(x) {
panic("stat: slice length mismatch")
}
var (
m float64
sumWeights float64
)
for i, vx := range x {
vy := y[i]
w := weights[i]
m += w * math.Pow(vx-meanX, r) * math.Pow(vy-meanY, s)