]> gitweb.factorcode.org Git - factor.git/blob - basis/math/statistics/statistics.factor
math.statistics: Add discounted cumulative gain and normalized dcg.
[factor.git] / basis / math / statistics / statistics.factor
1 ! Copyright (C) 2008 Doug Coleman, Michael Judge, Loryn Jenkins.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays assocs combinators fry generalizations grouping
4 kernel locals math math.functions math.order math.vectors
5 sequences sequences.private sorting ;
6 FROM: math.ranges => [a,b] ;
7 IN: math.statistics
8
9 : power-mean ( seq p -- x )
10     [ '[ _ ^ ] map-sum ] [ [ length / ] [ recip ^ ] bi* ] 2bi ; inline
11
12 ! Delta in degrees-of-freedom
13 : mean-ddof ( seq ddof -- x )
14     [ [ sum ] [ length ] bi ] dip -
15     [ drop 0 ] [ / ] if-zero ; inline
16
17 : mean ( seq -- x )
18     0 mean-ddof ; inline
19
20 : sum-of-squares ( seq -- x )
21     [ sq ] map-sum ; inline
22
23 : sum-of-squared-errors ( seq -- x )
24     [ mean ] keep [ - sq ] with map-sum ; inline
25
26 : sum-of-absolute-errors ( seq -- x )
27     [ mean ] keep [ - ] with map-sum ; inline
28
29 : quadratic-mean ( seq -- x ) ! root-mean-square
30     [ sum-of-squares ] [ length ] bi / sqrt ; inline
31
32 : geometric-mean ( seq -- x )
33     [ [ log ] map-sum ] [ length ] bi /f e^ ; inline
34
35 : harmonic-mean ( seq -- x )
36     [ [ recip ] map-sum ] [ length swap / ] bi ; inline
37
38 : contraharmonic-mean ( seq -- x )
39     [ sum-of-squares ] [ sum ] bi / ; inline
40
41 <PRIVATE
42
43 : trim-points ( p seq -- from to seq  )
44     [ length [ * >integer ] keep over - ] keep ;
45
46 PRIVATE>
47
48 : trimmed-mean ( seq p -- x )
49     swap natural-sort trim-points <slice> mean ;
50
51 : winsorized-mean ( seq p -- x )
52     swap natural-sort trim-points
53     [ <slice> ]
54     [ nip dupd nth <array> ]
55     [ [ 1 - ] dip nth <array> ] 3tri
56     surround mean ;
57
58 <PRIVATE
59
60 :: kth-object-impl ( seq k nth-quot exchange-quot quot: ( x y -- ? ) -- elt )
61     ! Wirth's method, Algorithm's + Data structues = Programs p. 84
62     k seq bounds-check 2drop
63     0 :> i!
64     0 :> j!
65     0 :> l!
66     0 :> x!
67     seq length 1 - :> m!
68     [ l m < ]
69     [
70         k seq nth-unsafe x!
71         l i!
72         m j!
73         [ i j <= ]
74         [
75             [ i seq nth-quot call x quot call ] [ i 1 + i! ] while
76             [ x j seq nth-quot call quot call ] [ j 1 - j! ] while
77             i j <= [
78                 i j seq exchange-quot call
79                 i 1 + i!
80                 j 1 - j!
81             ] when
82         ] do while
83
84         j k < [ i l! ] when
85         k i < [ j m! ] when
86     ] while
87     k seq nth-unsafe ; inline
88
89 : (kth-object) ( seq k nth-quot exchange-quot quot: ( x y -- ? ) -- elt )
90     ! The algorithm modifiers seq, so we clone it
91     [ >array ] 4dip kth-object-impl ; inline
92
93 : kth-object-unsafe ( seq k quot: ( x y -- ? ) -- elt )
94     [ [ nth-unsafe ] [ exchange-unsafe ] ] dip (kth-object) ; inline
95
96 : kth-objects-unsafe ( seq kths quot: ( x y -- ? ) -- elts )
97     '[ _ kth-object-unsafe ] with map ; inline
98
99 PRIVATE>
100
101 : kth-object ( seq k quot: ( x y -- ? ) -- elt )
102     [ [ nth ] [ exchange ] ] dip (kth-object) ; inline
103
104 : kth-objects ( seq kths quot: ( x y -- ? ) -- elts )
105     '[ _ kth-object ] with map ; inline
106
107 : kth-smallests ( seq kths -- elts ) [ < ] kth-objects-unsafe ;
108
109 : kth-smallest ( seq k -- elt ) [ < ] kth-object-unsafe ;
110
111 : kth-largests ( seq kths -- elts ) [ > ] kth-objects-unsafe ;
112
113 : kth-largest ( seq k -- elt ) [ > ] kth-object-unsafe ;
114
115 : count-relative ( seq k -- lt eq gt )
116     [ 0 0 0 ] 2dip '[
117         _ <=> {
118             { +lt+ [ [ 1 + ] 2dip ] }
119             { +gt+ [ 1 + ] }
120             { +eq+ [ [ 1 + ] dip ] }
121         } case
122     ] each ;
123
124 : minmax-relative ( seq k -- lt eq gt lt-max gt-min )
125     [ 0 0 0 -1/0. 1/0. ] 2dip '[
126         dup _ <=> {
127             { +lt+ [ [ 1 + ] 5 ndip '[ _ max ] dip ] }
128             { +gt+ [ [ 1 + ] 3dip min ] }
129             { +eq+ [ [ 1 + ] 4dip drop ] }
130         } case
131     ] each ;
132
133 : lower-median-index ( seq -- n )
134     [ midpoint@ ]
135     [ length odd? [ 1 - ] unless ] bi ;
136
137 : lower-median ( seq -- elt )
138     [ ] [ lower-median-index ] bi kth-smallest ;
139
140 : upper-median ( seq -- elt )
141     dup midpoint@ kth-smallest ;
142
143 : medians ( seq -- lower upper )
144     [ ]
145     [ [ lower-median-index ] [ midpoint@ ] bi 2array ]
146     bi kth-smallests first2 ;
147
148 : median ( seq -- x )
149     dup length odd? [ lower-median ] [ medians + 2 / ] if ;
150
151 ! quantile can be any n-tile. quartile is n = 4, percentile is n = 100
152 ! a,b,c,d parameters, N - number of samples, q is quantile (1/2 for median, 1/4 for 1st quartile)
153 ! http://mathworld.wolfram.com/Quantile.html
154 ! a + (N + b) q - 1
155 ! could subtract 1 from a
156
157 : quantile-x ( a b N q -- x )
158     [ + ] dip * + 1 - ; inline
159
160 ! 2+1/4 frac is 1/4
161 : frac ( x -- x' )
162     >fraction [ /mod nip ] keep / ; inline
163
164 :: quantile-indices ( seq qs a b -- seq )
165     qs [ [ a b seq length ] dip quantile-x ] map ;
166
167 :: qabcd ( y-floor y-ceiling x c d -- qabcd )
168     y-floor y-ceiling y-floor - c d x frac * + * + ;
169
170 :: quantile-abcd ( seq qs a b c d -- quantile )
171     seq qs a b quantile-indices :> indices
172     indices [ [ floor 0 max ] [ ceiling seq length 1 - min ] bi 2array ] map
173     concat :> index-pairs
174
175     seq index-pairs kth-smallests
176     2 group indices [ [ first2 ] dip c d qabcd ] 2map ;
177
178 : quantile1 ( seq qs -- seq' )
179     0 0 1 0 quantile-abcd ;
180
181 : quantile3 ( seq qs -- seq' )
182     1/2 0 0 0 quantile-abcd ;
183
184 : quantile4 ( seq qs -- seq' )
185     0 0 0 1 quantile-abcd ;
186
187 : quantile5 ( seq qs -- seq' )
188     1/2 0 0 1 quantile-abcd ;
189
190 : quantile6 ( seq qs -- seq' )
191     0 1 0 1 quantile-abcd ;
192
193 : quantile7 ( seq qs -- seq' )
194     1 -1 0 1 quantile-abcd ;
195
196 : quantile8 ( seq qs -- seq' )
197     1/3 1/3 0 1 quantile-abcd ;
198
199 : quantile9 ( seq qs -- seq' )
200     3/8 1/4 0 1 quantile-abcd ;
201
202 : quartile ( seq -- seq' )
203     { 1/4 1/2 3/4 } quantile5 ;
204
205 : interquartile ( seq -- q1 q3 )
206     quartile [ first ] [ last ] bi ;
207
208 : interquartile-range ( seq -- n )
209     interquartile - ;
210
211 : midhinge ( seq -- n )
212     interquartile + 2 / ;
213
214 : trimean ( seq -- x )
215     quartile first3 [ 2 * ] dip + + 4 / ;
216
217 : histogram! ( hashtable seq -- hashtable )
218     over '[ _ inc-at ] each ;
219
220 : histogram-by ( seq quot: ( x -- bin ) -- hashtable )
221     H{ } clone [ '[ @ _ inc-at ] each ] keep ; inline
222
223 : histogram ( seq -- hashtable )
224     [ ] histogram-by ;
225
226 : sorted-histogram ( seq -- alist )
227     histogram sort-values ;
228
229 : normalized-histogram ( seq -- alist )
230     [ histogram ] [ length ] bi '[ _ / ] assoc-map ;
231
232 : equal-probabilities ( n -- array )
233     dup recip <array> ; inline
234
235 : mode ( seq -- x )
236     histogram >alist [ second ] supremum-by first ;
237
238 : minmax ( seq -- min max )
239     [ first dup ] keep [ [ min ] [ max ] bi-curry bi* ] 1 each-from ;
240
241 : range ( seq -- x )
242     minmax swap - ;
243
244 : fivenum ( seq -- seq' )
245     [ quartile ] [ minmax ] bi [ prefix ] [ suffix ] bi* ;
246
247 : var-ddof ( seq n -- x )
248     2dup [ length ] dip - 0 <= [
249         2drop 0
250     ] [
251         [ [ sum-of-squared-errors ] [ length ] bi ] dip - /
252     ] if ; inline
253
254 : population-var ( seq -- x ) 0 var-ddof ; inline
255
256 : sample-var ( seq -- x ) 1 var-ddof ; inline
257
258 : std-ddof ( seq n -- x ) var-ddof sqrt ; inline
259
260 : population-std ( seq -- x ) 0 std-ddof ; inline
261
262 : sample-std ( seq -- x ) 1 std-ddof ; inline
263
264 ALIAS: std sample-std
265
266 : signal-to-noise ( seq -- x ) [ mean ] [ population-std ] bi / ;
267
268 : demean ( seq -- seq' ) dup mean v-n ;
269
270 : mean-dev ( seq -- x ) demean vabs mean ;
271
272 : demedian ( seq -- seq' ) dup median v-n ;
273
274 : median-dev ( seq -- x ) demedian vabs mean ;
275
276 : ste-ddof ( seq n -- x ) '[ _ std-ddof ] [ length ] bi sqrt / ;
277
278 : population-ste ( seq -- x ) 0 ste-ddof ;
279
280 : sample-ste ( seq -- x ) 1 ste-ddof ;
281
282 <PRIVATE
283 : r-sum-diffs ( x-mean y-mean x-seq y-seq -- (r) )
284     ! finds sigma((xi-mean(x))(yi-mean(y))
285     0 [ [ reach - ] bi@ * + ] 2reduce 2nip ;
286
287 : (r) ( x-mean y-mean x-seq y-seq x-std y-std -- r )
288     * recip [ [ r-sum-diffs ] keep length 1 - / ] dip * ;
289
290 : r-stats ( xy-pairs -- x-mean y-mean x-seq y-seq x-std y-std )
291     first2 [ [ [ mean ] bi@ ] 2keep ] 2keep [ population-std ] bi@ ;
292 PRIVATE>
293
294 : pearson-r ( xy-pairs -- r ) r-stats (r) ;
295
296 : least-squares ( xy-pairs -- alpha beta )
297     r-stats [ 2dup ] 4dip
298     ! stack is x-mean y-mean x-mean y-mean x-seq y-seq x-std y-std
299     [ (r) ] 2keep ! stack is mean(x) mean(y) r sx sy
300     swap / * ! stack is mean(x) mean(y) beta
301     [ swapd * - ] keep ;
302
303 : cov-ddof ( x-seq y-seq ddof -- cov )
304     [ [ demean ] bi@ v* ] dip mean-ddof ;
305
306 : population-cov ( x-seq y-seq -- cov ) 0 cov-ddof ; inline
307
308 : sample-cov ( x-seq y-seq -- cov ) 1 cov-ddof ; inline
309
310 : corr-ddof ( x-seq y-seq n -- corr )
311     [ [ population-cov ] ] dip
312     '[ [ _ var-ddof ] bi@ * sqrt ] 2bi / ;
313
314 : population-corr ( x-seq y-seq -- corr ) 0 corr-ddof ; inline
315
316 : sample-corr ( x-seq y-seq -- corr ) 1 corr-ddof ; inline
317
318 : cum-sum ( seq -- seq' )
319     0 [ + ] accumulate* ;
320
321 : cum-sum0 ( seq -- seq' )
322     0 [ + ] accumulate nip ;
323
324 : cum-product ( seq -- seq' )
325     1 [ * ] accumulate* ;
326
327 : cum-product1 ( seq -- seq' )
328     1 [ * ] accumulate nip ;
329
330 : cum-mean ( seq -- seq' )
331     0 swap [ [ + dup ] dip 1 + / ] map-index nip ;
332
333 : cum-count ( seq quot: ( elt -- ? ) -- seq' )
334     [ 0 ] dip '[ @ [ 1 + ] when ] accumulate* ; inline
335
336 : cum-min ( seq -- seq' )
337     dup ?first [ min ] accumulate* ;
338
339 : cum-max ( seq -- seq' )
340     dup ?first [ max ] accumulate* ;
341
342 : entropy ( probabilities -- n )
343     dup sum '[ _ / dup log * ] map-sum neg ;
344
345 : maximum-entropy ( probabilities -- n )
346     length log ;
347
348 : normalized-entropy ( probabilities -- n )
349     [ entropy ] [ maximum-entropy ] bi / ;
350
351 : binary-entropy ( p -- h )
352     [ dup log * ] [ 1 swap - dup log * ] bi + neg 2 log / ;
353
354 : standardize ( u -- v )
355     [ demean ] [ sample-std ] bi [ v/n ] unless-zero ;
356
357 : standardize-2d ( u -- v )
358     flip [ standardize ] map flip ;
359
360 : differences ( u -- v )
361     [ rest-slice ] keep v- ;
362
363 : rescale ( u -- v )
364     dup minmax over - [ v-n ] [ v/n ] bi* ;
365
366 : rankings ( histogram -- assoc )
367     sort-keys 0 swap [ rot [ + ] keep swapd ] H{ } assoc-map-as nip ;
368
369 : rank-values ( seq -- seq' )
370     dup histogram rankings '[ _ at ] map ;
371
372 : z-score ( seq -- n )
373     [ demean ] [ sample-std ] bi v/n ;
374
375 : dcg ( scores -- dcg )
376     dup length 1 + 2 swap [a,b] [ log 2 log /f ] map v/ sum ;
377
378 : ndcg ( scores -- ndcg )
379     [ 0 ] [
380         [ dcg ] [ natural-sort <reversed> dcg ] bi /f
381     ] if-empty ;