-
Notifications
You must be signed in to change notification settings - Fork 2
/
commonfunc.stan
6115 lines (5495 loc) · 224 KB
/
commonfunc.stan
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
// DO NOT EDIT THIS FILE DIRECTLY. It is created by make_commonfunc_stan.py.
// ========================================================================
// Common functions
// ========================================================================
/*
Reminders -- Stan's flavour of C++:
-----------------------------------------------------------------------
- Disappointingly, you can't modify arguments to Stan user-defined
functions. (No pass-by-reference.)
- You can't have templating of user-defined functions, i.e. not this:
template<T> T somefunc(T x);
- Two functions with the same name can't even have different
signatures. So not this:
real somefunc(real x);
vector somefunc(vector x);
- No default values for function parameters. So not this:
real somefunc(x, y = 0);
- We can't use a leading "_" prefix on function names (gives a Stan
syntax error).
- The addition-assignment (+=) operator generally doesn't work (it
appears to be reserved for the one variable "target += ...").
Similarly for all others you might expect.
- Aha! By Stan 2.19, this has changed. Can use "x += 1"
(p19 of Stan 2.19 Reference Manual).
- The ternary (conditional, ?:) operator *is* supported, e.g.:
x = a ? b : c;
- Simpler Stan statements (e.g. with the ternary operator) translate
to fewer C++ statements and faster code (particularly as Stan inserts
debugging code around the translated C++ statements).
Reminders -- Stan, other:
-----------------------------------------------------------------------
- Array/vector indexing is 1-based.
- OUTDATED: previously, size() didn't work on a plain "vector" and one
should have used num_elements(). This is fixed as of Stan ~2.24: see
https://discourse.mc-stan.org/t/option-to-keep-constant-terms-in-log-probability-via-standard-sampling-syntax/20278/2.
But remember that size() is "top-level" size (e.g. the first
dimension of an array), whereas num_elements() counts all elements.
- Can't define constants in a functions{} block.
*/
// ------------------------------------------------------------------------
// Softmax
// ------------------------------------------------------------------------
real softmaxNth(vector softmax_inputs, int index)
{
/*
Returns the nth value (at "index") of the softmax of the inputs.
Assumes an inverse temperature of 1.
FOR AN EXPLICIT INVERSE TEMPERATURE, see softmaxNthInvTemp().
FOR A LOGIT (LOG ODDS) VERSION, see logitSoftmaxNth().
NOTES:
A softmax function takes several inputs and normalizes them so
that:
- the outputs are in the same relative order as the inputs
- the outputs sum to 1.
For softmax: see my miscstat.R; the important points for
optimization are (1) that softmax is invariant to the addition/
subtraction of a constant, and subtracting the mean makes the
numbers less likely to fall over computationally; (2) we often only
need the final part of the computation for a single number
(preference for one option), so here we don't waste time
vector-calculating the preference for the left as well [that is:
we don't have to calculate s_exp_products / sum(s_exp_products)].
The constant can be the mean, or the max; Stan uses the max, which
is probably a little more efficient.
Since Stan 2.0.0, the alternative is to use softmax(); see
https://github.com/stan-dev/math/blob/develop/stan/math/prim/mat/fun/softmax.hpp
The exact syntactic equivalence is:
real result = softmaxNth(inputs, index); // this
real result = softmax(inputs)[index]; // Stan
This "homebrew" version is faster than using Stan's built-in
softmax() (our speed comparison is in
rlib/tests/profile_stan_softmax/profile_softmax.stan), presumably
because Stan calculates the result for all elements of the input,
and we only bother with the element we care about.
*/
int length = num_elements(softmax_inputs);
real constant = max(softmax_inputs);
vector[length] s_exp_products = exp(softmax_inputs - constant);
return s_exp_products[index] / sum(s_exp_products);
}
real softmaxNthInvTemp(vector softmax_inputs, real inverse_temp, int index)
{
/*
Version of softmaxNth allowing you to specify the inverse temp.
These are equivalent:
real result = softmaxNthInvTemp(inputs, invtemp, index);
real result = softmax(inputs * invtemp)[index]; // Stan
See softmaxNth() above for speed comparisons.
*/
return softmaxNth(softmax_inputs * inverse_temp, index);
// return softmax(softmax_inputs * inverse_temp)[index];
}
real logitSoftmaxNth(vector inputs, int index)
{
/*
Returns
logit(softmax(inputs))[index];
that is, the log odds for a probability from a softmax function.
Recall that:
- odds = p / (1 - p)
- x = logit(p) = log(odds) = log(p) - log(1 - p) = -log((1/p) - 1)
- p = logistic(x) = 1 / (1 + exp(-x)) = exp(x) / (exp(x) + 1)
- softmax(v, i) = exp(v[i]) / sum(exp(v))
- log_softmax(v, i) = v[i] - log(sum(exp(v))
- Stan provides log_sum_exp(), log_softmax(), log1m_exp().
A fully vectorized version in R:
library(matrixStats) # for logSumExp
logitSoftmax <- function(x, debug = FALSE) {
log_sum_exp_x <- logSumExp(x)
log_p <- x - log_sum_exp_x # = log(softmax(x))
log_1mp = log(1 - exp(log_p))
logit <- log_p - log_1mp
if (debug) {
cat("log_sum_exp_x:\n"); print(log_sum_exp_x)
cat("log_p:\n"); print(log_p)
p <- exp(log_p)
cat("p:\n"); print(p)
stopifnot(isTRUE(all.equal(sum(p), 1))) # check with tolerance
cat("log_1mp:\n"); print(log_1mp)
cat("logit:\n"); print(logit)
}
return(logit)
}
logitSoftmax(c(1, 2, 3), debug = TRUE) # demonstration
*/
// METHOD 1 (fewer calculations involved and empirically faster):
real log_p = inputs[index] - log_sum_exp(inputs);
// METHOD 2 (empirically slower):
// real log_p = log_softmax(inputs)[index];
// EITHER WAY:
// Conceptually:
// (a) log_1mp = log(1 - p)
// = log(1 - exp(log_p))
// = log1m_exp(log_p)
// (b) logit = log(p) - log(1 - p)
// = log_p - log_1mp
// It is very slightly faster (from profiling) to do this in a single
// step:
return log_p - log1m_exp(log_p);
}
// ------------------------------------------------------------------------
// Logistic function
// ------------------------------------------------------------------------
// - For the logit function, use Stan's built-in logit().
// - For the standard logistic (with x0 = 0, k = 1, L = 1), use Stan's
// inv_logit().
real logistic(real x, real x0, real k, real L)
{
/*
Returns x transformed through a logistic function, yielding a
result in the range (0, L).
Notation as per https://en.wikipedia.org/wiki/Logistic_function:
- x0: centre
- k: steepness
- L: maximum (usually 1)
The standard logistic function, the inverse of the logit function,
p = logistic(x) = sigmoid(x) = expit(x) = 1 / (1 + exp(-x))
where x is a logit (log odds) and p is the resulting probability,
is a special case where L = 1, k = 1, x0 = 0. However, for that
you should use Stan's inv_logit().
Therefore, if you were to transform x so as to be a logit giving
the same result via the standard logistic function, 1 / (1 +
exp(-x)), for L = 1, you want this logit:
x' = k * (x - x0)
*/
return L / (1 + exp(-k * (x - x0)));
}
// ------------------------------------------------------------------------
// Boundaries (min, max)
// ------------------------------------------------------------------------
real bound(real x, real min_value, real max_value)
{
// Returns x with minimum/maximum boundaries applied.
// We would simply do this:
// return max(min_value, min(x, max_value));
// ... but Stan doesn't have max(real, real) or min(real, real)
// functions.
return x < min_value ? min_value : (x > max_value ? max_value : x);
}
real boundLower(real x, real min_value)
{
// a.k.a. max()
return x < min_value ? min_value : x;
}
real boundUpper(real x, real max_value)
{
// a.k.a. min()
return x > max_value ? max_value : x;
}
// ------------------------------------------------------------------------
// Basic data manipulation
// ------------------------------------------------------------------------
vector vector_from_real_array_row(array[,] real x, int row)
{
// Given an array
// array[nrows, ncols] real x;
// you can slice the array with
// array[ncols] real a = x[row];
// but not with
// vector[ncols] y = x[row];
// so this function does that.
int ncols = dims(x)[2];
vector[ncols] v;
for (i in 1:ncols) {
v[i] = x[row, i];
}
return v;
}
vector vector_from_int_array_row(array[,] int x, int row)
{
// As above, but for an int array.
int ncols = dims(x)[2];
vector[ncols] v;
for (i in 1:ncols) {
v[i] = x[row, i];
}
return v;
}
vector except_V_V(vector v, int except)
{
// Returns a vector that is the original without the element at index
// "except".
int n = num_elements(v);
vector[n - 1] result;
int r = 1; // indexes result
for (i in 1:n) {
if (i == except) {
continue;
}
result[r] = v[i];
r += 1;
}
return result;
}
int except_I_I(int x, int except)
{
// The argument is an index to a vector v; the result is the equivalent
// index to the vector returned by except_V_V(v, except).
if (x < 1) {
reject("Argument x is a Stan index so must be >= 1");
}
if (except == x) {
reject("Cannot remove 'except' where except == x");
}
if (except < 1 || except > x) {
return x;
}
return x - 1;
}
// ------------------------------------------------------------------------
// Simple functions: matrix calculations
// ------------------------------------------------------------------------
// Note that Stan only provides the following versions of dot_product():
// dot_product(vector, vector)
// dot_product(row vector, row vector)
// dot_product(vector, row vector)
// dot_product(row vector, vector)
// dot_product(array[] real, array[] real)
vector dot_product_MV_V(matrix x, vector y)
{
// Dot product between a matrix (2 dimensions) and a vector (1
// dimension):
//
// (p, q) matrix ⋅ (q, 1) vector = (p, 1) vector
//
// For example:
//
// [a, b] [g] [ag + bh]
// x ⋅ y = [c, d] ⋅ [h] = [cg + dh]
// [e, f] [eg + fh]
//
// (3, 2) ⋅ (2, 1) = (3, 1)
array[2] int x_dimensions = dims(x);
int p = x_dimensions[1];
int q = x_dimensions[2];
vector[p] z;
real cell;
if (q != num_elements(y)) {
reject("Incompatible arguments");
}
for (i in 1:p) { // rows of x
cell = 0.0;
for (j in 1:q) { // columns of x
cell += x[i, j] * y[j];
}
z[i] = cell;
}
return z;
}
vector dot_product_2A_V(array[,] real x, array[] real y)
{
// As dot_product_MV_V, but for array inputs.
array[2] int x_dimensions = dims(x);
int p = x_dimensions[1];
int q = x_dimensions[2];
vector[p] z;
real cell;
if (q != num_elements(y)) {
reject("Incompatible arguments");
}
for (i in 1:p) { // rows of x
cell = 0.0;
for (j in 1:q) { // columns of x
cell += x[i, j] * y[j];
}
z[i] = cell;
}
return z;
}
vector dot_product_VM_V(vector x, matrix y)
{
// Dot product between a vector (1 dimension) and a matrix (2
// dimensions):
//
// (1, p) vector ⋅ (p, q) matrix = (1, q) vector
//
// For example:
//
// [a, c, e]
// x ⋅ y = [g, h] ⋅ [b, d, f] = [ag + bh, cg + dh, eg + fh]
// = y' ⋅ x'
//
// (1, 2) ⋅ (2, 3) = (1, 3)
array[2] int y_dimensions = dims(y);
int p = y_dimensions[1];
int q = y_dimensions[2];
vector[q] z;
real cell;
if (p != num_elements(x)) {
reject("Incompatible arguments");
}
for (j in 1:q) { // columns of y
cell = 0.0;
for (i in 1:p) { // rows of y
cell += x[j] * y[i, j];
}
z[j] = cell;
}
return z;
}
vector dot_product_A2_V(array[] real x, array[,] real y)
{
// As dot_product_VM_V(), but for array inputs.
array[2] int y_dimensions = dims(y);
int p = y_dimensions[1];
int q = y_dimensions[2];
vector[q] z;
real cell;
if (p != num_elements(x)) {
reject("Incompatible arguments");
}
for (j in 1:q) { // columns of y
cell = 0.0;
for (i in 1:p) { // rows of y
cell += x[j] * y[i, j];
}
z[j] = cell;
}
return z;
}
real dot_product_AA_R(array[] real x, array[] real y)
{
// Dot product of two arrays.
int n = num_elements(x);
real z = 0.0;
if (n != num_elements(y)) {
reject("Incompatible arguments");
}
for (i in 1:n) {
z += x[i] * y[i];
}
return z;
}
real dot_product_iAV_R(array[] int x, vector y)
{
int n = num_elements(x);
real z = 0.0;
if (n != num_elements(y)) {
reject("Incompatible arguments");
}
for (i in 1:n) {
z += x[i] * y[i];
}
return z;
}
matrix tensordot_A3_M(array[] real x, array[,,] real y)
{
// Equivalent to Numpy's tensordot(x, y, axes=1), for:
//
// (1, p) ⋅ (p, q, r) = (q, r)
//
// For example:
//
// [a, b] ⋅ [ [c, d, e, f] = [ac + bc', ad + bd', ...]
// [g, h, i, j] [ag + bg', ag + bg', ...]
// [k, l, m, n], [ak + bk', ak + bk', ...]
//
// [c', d', e', f']
// [g', h', i', j']
// [k', l', m', n'] ]
//
// (1, 2) ⋅ (2, 3, 4) = (3, 4)
array[3] int dimensions = dims(y);
int p = dimensions[1];
int q = dimensions[2];
int r = dimensions[3];
matrix[q, r] z;
real cell;
if (p != num_elements(x)) {
reject("Incompatible arguments");
}
for (j in 1:q) {
for (k in 1:r) {
cell = 0.0;
for (i in 1:p) {
cell += x[i] * y[i, j, k];
}
z[j, k] = cell;
}
}
return z;
}
array[,] real tensordot_A3_2(array[] real x, array[,,] real y)
{
// As for tensordot_A3_M(), but returning an array.
array[3] int dimensions = dims(y);
int p = dimensions[1];
int q = dimensions[2];
int r = dimensions[3];
array[q, r] real z;
real cell;
if (p != num_elements(x)) {
reject("Incompatible arguments");
}
for (j in 1:q) {
for (k in 1:r) {
cell = 0.0;
for (i in 1:p) {
cell += x[i] * y[i, j, k];
}
z[j, k] = cell;
}
}
return z;
}
// ------------------------------------------------------------------------
// Pairwise differences in matrix format
// ------------------------------------------------------------------------
// Two functions with different signatures can't have the same name...
matrix pairwiseDifferencesSpecifyDiagonal(vector x, vector y,
real diagonal_value)
{
// - Given two vectors of equal length N, returns a matrix[N, N] result
// where each element result[i, j] == x[i] - y[j].
// - Diagonal values, for which i == j, are populated with
// diagonal_value. By default this is zero, but if this is to be a
// result from e.g. a generated quantities block, Stan will complain
// (that the largest value of Rhat is NaN) if diagonal values is unvaryingly
// zero. Under those circumstances, you should pass in a small (e.g.
// iteration-specific) random number, e.g. like this:
// real tiny_random_number = uniform_rng(-1e-16, 1e-16);
// group_diffs = pairwiseDifferences(x, y, tiny_random_number);
int n = num_elements(x);
matrix[n, n] result;
real diff_x_minus_y; // working variable to save a lookup
if (n != num_elements(y)) {
reject("Incompatible arguments");
}
for (j in 1:n) { // access matrices in column-major order
for (i in 1:n) {
if (i == j) {
result[i, j] = diagonal_value;
} else if (i > j) {
// We populate the bottom-left corner [i, j], where i > j,
// and simultaneously cross-populate the corresponding cell
// in the top-right corner [j, i].
diff_x_minus_y = x[i] - y[j];
result[i, j] = diff_x_minus_y;
result[j, i] = -diff_x_minus_y;
}
}
}
return result;
}
matrix pairwiseDifferences(vector x, vector y)
{
// A version of pairwiseDifferences() with diagonal_value = 0.
return pairwiseDifferencesSpecifyDiagonal(x, y, 0);
}
matrix pairwiseDifferencesSelfSpecifyDiagonal(vector x, real diagonal_value)
{
// A version of pairwiseDifferences() to compare a vector to itself
// pairwise.
return pairwiseDifferencesSpecifyDiagonal(x, x, diagonal_value);
}
matrix pairwiseDifferencesSelf(vector x)
{
// A version of pairwiseDifferences() to compare a vector to itself
// pairwise with diagonal_value = 0.
return pairwiseDifferencesSpecifyDiagonal(x, x, 0);
}
// ------------------------------------------------------------------------
// Pairwise comparisons in vector format
// ------------------------------------------------------------------------
int factorial(int x); // necessary for self-recursion
int factorial(int x)
{
// We could use tgamma(x + 1). But then we run into the unwillingness
// of Stan to provide functions that round real numbers to integer, and
// the need for complex workarounds:
// https://discourse.mc-stan.org/t/real-to-integer-conversion/5622/9 So
// we could just implement a factorial algorithm; see
// http://www.luschny.de/math/factorial/FastFactorialFunctions.htm We
// will just use the simplest version:
if (x < 0) {
reject("Factorial undefined for negative numbers. Called for: ", x);
}
if (x == 0 || x == 1) {
return 1; // 0! = 1, and 1! = 1
}
return x * factorial(x - 1);
}
int nCombinations(int n, int k)
{
// Returns the number of combinations of size k amongst n items.
//
// The two-stage approach is entirely because of a wrong warning
// message from Stan. If you use
// return factorial(n) / (factorial(k) * factorial(n - k));
// then the integer division warning in Stan will print
// factorial(n) / factorial(k) * factorial(n - k);
// ... the removal of the brackets in the warning message may make the
// reader think the code is wrong.
int denominator;
if (n < 1 || k < 1 || n - k < 0) {
return 0;
}
denominator = factorial(k) * factorial(n - k);
return factorial(n) %/% denominator;
}
vector pairwiseDifferencesVec(vector x)
{
// Given a vector x of length n (where n > 1), returns a vector of
// length C(n, 2) of every pairwise comparison.
//
// The first pairwise comparisons is x[1] - x[2], then x[1] - x[3],
// etc., up to x[1] - x[n]. Then it moves to x[2] - x[3], x[2] - x[4],
// etc. And so on; the last element is x[n - 1] - x[n].
//
// The inverse comparisons, e.g. x[2] - x[1], are not performed.
int n_items = num_elements(x);
int n_pairs = nCombinations(n_items, 2);
int pair = 1;
vector[n_pairs] differences;
if (n_pairs < 1) {
return differences; // empty vector
}
for (i in 1:(n_items - 1)) {
for (j in (i + 1):n_items) {
differences[pair] = x[i] - x[j];
pair += 1;
}
}
return differences;
}
vector pairwiseDifferencesVecNPairsKnown(vector x, int n_pairs)
{
// As for pairwiseDifferencesVec, but with n_pairs precalculated
// for speed. (The caller will need to have precalculated this to
// define the size of the return vector...)
int n_items = num_elements(x);
int pair = 1;
vector[n_pairs] differences;
if (n_pairs < 1) {
return differences; // empty vector
}
for (i in 1:(n_items - 1)) {
for (j in (i + 1):n_items) {
differences[pair] = x[i] - x[j];
pair += 1;
}
}
return differences;
}
// ------------------------------------------------------------------------
// AUROC (area under the receiver operating characteristic curve)
// ------------------------------------------------------------------------
/*
Calculates AUROC for a binary dependent variable "outcome" from the
predictor "probability", which is continuous.
For example, you could use a calculated probability as a predictor,
or log odds.
CONCEPT
See:
- https://stats.stackexchange.com/questions/145566/how-to-calculate-area-under-the-curve-auc-or-the-c-statistic-by-hand
- https://www.r-bloggers.com/2016/11/calculating-auc-the-area-under-a-roc-curve/
- https://blog.revolutionanalytics.com/2016/11/calculating-auc.html
We will use the following method in principle:
- For every unique pair of actual values (one is 0, the other is 1):
- If p_for_outcome_one > p_for_outcome_zero, that's a win (score 1);
if p_for_outcome_one < p_for_outcome_zero, that's a loss (score 0);
if p_for_outcome_one = p_for_outcome_zero, that's a tie (score 0.5).
- Take the mean of those scores; that is the AUROC.
This follows Hanley & McNeil (1982, PMID 7063747), section III.
If the outcome doesn't have both ones and zeros, we fail, as in R:
library(pROC)
roc(response = c(1, 1, 1, 1), predictor = c(0.1, 0.2, 0.3, 0.4))
General speedup techniques:
https://mc-stan.org/docs/2_27/stan-users-guide/vectorization.html
However, see this algorithm:
- https://stephanosterburg.gitbook.io/scrapbook/data-science/ds-cheatsheets/machine-learning/fast-computation-of-auc-roc-score
ALGORITHM
After:
- https://stephanosterburg.gitbook.io/scrapbook/data-science/ds-cheatsheets/machine-learning/fast-computation-of-auc-roc-score
- https://github.com/jfpuget/metrics/blob/master/auc.ipynb
"Let's first define some entities.
- pos is the set of examples with target 1. These are the positive
examples.
- neg is the set of examples with target 0. These are the negative
examples.
- p(i) is the prediction for example i. p(i) is a number between 0
and 1.
- A pair of examples (i, j) is labelled the right way if i is a
positive example, j is a negative example, and the prediction for
i is higher than the prediction for j.
- | s | is the number of elements in set s.
Then AUC-ROC is the count of pairs labelled the right way divided
by the number of pairs:
AUC-ROC = | {(i,j), i in pos, j in neg, p(i) > p(j)} | / (| pos | * | neg |)
A naive code to compute this would be to consider each possible
pair and count those labelled the right way. A much better way is
to sort the predictions first, then visit the examples in
increasing order of predictions. Each time we see a positive
example we add the number of negative examples we've seen so far."
~~~
RNC: Accuracy verified against R's pROC::roc(); see
rlib/tests/auroc/test_auroc_algorithm.R.
*/
real aurocAV(array[] int binary_outcome, vector predictor)
{
int n = num_elements(binary_outcome);
// Sort the binary outcome by ascending predictor:
array[n] int y = binary_outcome[sort_indices_asc(predictor)];
int n_false = 0;
int current_y;
real total = 0.0;
for (i in 1:n) {
current_y = y[i];
n_false += 1 - current_y; // add 1 if false; unchanged if true
total += current_y * n_false;
// ... if we are seeing a positive example, add the number of
// negative examples so far.
}
return total / (n_false * (n - n_false));
}
real aurocAA(array[] int binary_outcome, array[] real predictor)
{
// For comments, see aurocAV.
int n = num_elements(binary_outcome);
array[n] int y = binary_outcome[sort_indices_asc(predictor)];
int n_false = 0;
int current_y;
real total = 0.0;
for (i in 1:n) {
current_y = y[i];
n_false += 1 - current_y;
total += current_y * n_false;
}
return total / (n_false * (n - n_false));
}
// ========================================================================
// Probability distribution functions not provided by Stan
// ========================================================================
// See extra_distribution_functions.stan, which also implements tests.
/*
NOTE STAN VERSION/SYNTAX PROBLEMS:
- "real a, b;" is disallowed by RStan 2.26.1 but permitted by stanc
2.31.1. The error from the earlier version is:
";" or plain assignment expected after variable declaration.
- gamma_cdf(x, a, b) is warned about in Stan 2.31.1 with a plan to
remove in Stan 2.32.0. It wants gamma_lcdf(x | a, b). Likewise for
beta_cdf(). HOWEVER, Stan 2.26.1 prohibits this, with the error:
Only functions with names ending in _lpdf, _lupdf, _lpmf, _lupmf,
_lcdf, _lccdf can make use of conditional notation.
Currently (2023-02-05), we use comma notation, because the latest
version of RStan is only 2.26.1. This will need changing, though.
*/
// ------------------------------------------------------------------------
// qbeta()
// ------------------------------------------------------------------------
real qbeta(real p, real alpha, real beta)
{
// Quantile, or inverse cumulative distribution function (inverse CDF),
// for the beta distribution. Equivalent to qbeta() in R, or at least a
// less capable version of it. Implements the missing Stan function
// beta_qf().
//
// - The first parameter is a cumulative probability.
// - Distribution parameter shape1 (R) = alpha (Stan).
// - Distribution parameter shape2 (R) = beta (Stan).
// - The result is a value from the beta distribution.
//
// From
// https://github.com/SurajGupta/r-source/blob/master/src/nmath/qnbeta.c,
// modified as per qbeta_notes.txt. We are just implementing the
// version with lower_tail = false and log_p = false.
real DBL_EPSILON_X = machine_precision();
real ONE_M_DBL_EPSILON = 1 - DBL_EPSILON_X; // precalculate
real DBL_MIN_ = 1e-323;
real accu = 1e-15;
real Eps = 1e-14; // must be > accu
real ux; // Stan 2.26.1 dislikes "real ux, lx, nx, pp;"
real lx;
real nx;
real pp;
if (p < 0.0 || p > 1.0) {
reject("qbeta: bad parameter: p < 0 or p > 1");
}
if (alpha <= 0.0 || beta <= 0.0) {
reject("qbeta: bad parameter: alpha <= 0 or beta <= 0");
}
// p = R_DT_qIv(p);
// ... reduces to p for log_p = false and lower_tail = false.
// Invert pnbeta(.):
// 1. finding an upper and lower bound
if (p > ONE_M_DBL_EPSILON) {
return 1.0;
}
// pp = fmin2(ONE_M_DBL_EPSILON, p * (1 + Eps));
pp = fmin(ONE_M_DBL_EPSILON, p * (1 + Eps));
// Start ux at 0.5 and work it up (in big steps) while it's too low.
ux = 0.5;
while (ux < ONE_M_DBL_EPSILON && beta_cdf(ux, alpha, beta) < pp) {
ux = 0.5 * (1 + ux);
}
// ux is now 0.5 or higher
pp = p * (1 - Eps);
// Start lx at 0.5 and work it down (in big steps) while it's too high.
lx = 0.5;
while (lx > DBL_MIN_ && beta_cdf(lx, alpha, beta) > pp) {
lx *= 0.5;
}
// lx is now 0.5 or lower
// 2. interval (lx,ux) halving:
// Narrow down the gap to find the answer.
while (1) {
nx = 0.5 * (lx + ux); // nx is the mean of lx and ux
if (beta_cdf(nx, alpha, beta) > p) {
ux = nx; // nx too high; move down (shift the upper boundary down)
} else {
lx = nx; // nx too low; move up (shift the lower boundary up)
}
if ((ux - lx) / nx <= accu) {
// Sufficiently accurate!
break;
}
}
return 0.5 * (ux + lx);
}
// ------------------------------------------------------------------------
// qcauchy()
// ------------------------------------------------------------------------
real tanpi(real x)
{
// Computes tan(pi * x).
// R's nmath/nmath.h defines __STDC_WANT_IEC_60559_FUNCS_EXT__ to
// ensure that tanpi() is defined. There is a declaration in
// https://github.com/SurajGupta/r-source/blob/master/src/include/Rmath.h0.in
// Stan has a change request to add tanpi() as of Apr 2021 at
// https://github.com/stan-dev/math/issues/2376
//
// Even Boost's Cauchy distribution uses a simple implementation:
// https://www.boost.org/doc/libs/1_81_0/boost/random/cauchy_distribution.hpp
return tan(pi() * x);
}
real qcauchy(real p, real location, real scale)
{
// location (R) = mu (Stan)
// scale (R) = sigma (Stan)
//
// Implements "lower.tail = TRUE, log.p = FALSE" version.
// See https://github.com/SurajGupta/r-source/blob/master/src/nmath/qcauchy.c
int lower_tail = 1; // no "bool" data type
real p_working = p; // can't rewrite argument
if (p < 0.0 || p > 1.0) {
reject("qcauchy: bad parameter: p < 0 or p > 1");
}
if (scale <= 0) {
if (scale == 0) {
// [RNC] Point mass.
return location;
}
reject("qcauchy: bad parameter: sigma (scale) < 0");
}
if (p > 0.5) {
if (p == 1.0) {
return location
+ (lower_tail ? scale : -scale) * positive_infinity();
// RNC: curious! Was the my_INF macro.
}
p_working = 1 - p;
lower_tail = !lower_tail;
}
// Use p_working, not p, below here.
// Stan doesn't let us rewrite our argument.
if (p_working == 0.5) {
return location; // avoid 1/Inf below
}
if (p_working == 0.0) {
return location
+ (lower_tail ? scale : -scale) * negative_infinity();
// p = 1 is handled above
}
return location + (lower_tail ? -scale : scale) / tanpi(p_working);
// -1/tan(pi * p) = -cot(pi * p) = tan(pi * (p - 1/2))
}
// ------------------------------------------------------------------------
// qgamma(), and its support functions
// ------------------------------------------------------------------------
real logcf(real x, real i, real d, real eps)
{
// eps: relative tolerance
// See https://github.com/SurajGupta/r-source/blob/master/src/nmath/pgamma.c
real c1 = 2 * d;
real c2 = i + d;
real c4 = c2 + d;
real a1 = c2;
real b1 = i * (c2 - i * x);
real b2 = d * d * x;
real a2 = c4 * c2 - b2;
real scalefactor = pow(2.0, 256.0);
// = ((4294967296.0^2)^2)^2 = (2^32)^8 = 2^256 = 1.157921e+77