python-stats 1.0.0__py3-none-any.whl → 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- py_stats/__init__.py +183 -181
- py_stats/multivariate.py +925 -689
- py_stats/univariate.py +1377 -1212
- {python_stats-1.0.0.dist-info → python_stats-2.0.0.dist-info}/METADATA +594 -391
- python_stats-2.0.0.dist-info/RECORD +8 -0
- {python_stats-1.0.0.dist-info → python_stats-2.0.0.dist-info}/WHEEL +1 -1
- {python_stats-1.0.0.dist-info → python_stats-2.0.0.dist-info}/licenses/LICENSE +20 -20
- python_stats-1.0.0.dist-info/RECORD +0 -8
- {python_stats-1.0.0.dist-info → python_stats-2.0.0.dist-info}/top_level.txt +0 -0
py_stats/multivariate.py
CHANGED
|
@@ -1,690 +1,926 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Multivariate statistics functions for py-stats package.
|
|
3
|
-
|
|
4
|
-
This module provides comprehensive multivariate statistical analysis functions
|
|
5
|
-
including correlation coefficients, covariance, regression analysis, and
|
|
6
|
-
association measures.
|
|
7
|
-
"""
|
|
8
|
-
|
|
9
|
-
import math
|
|
10
|
-
|
|
11
|
-
import
|
|
12
|
-
|
|
13
|
-
from .univariate import _validate_data, arithmetic_mean
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
def pearson_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
17
|
-
"""
|
|
18
|
-
Calculate Pearson's correlation coefficient.
|
|
19
|
-
|
|
20
|
-
Args:
|
|
21
|
-
x: First variable data
|
|
22
|
-
y: Second variable data
|
|
23
|
-
|
|
24
|
-
Returns:
|
|
25
|
-
Pearson correlation coefficient (-1 to 1)
|
|
26
|
-
|
|
27
|
-
Example:
|
|
28
|
-
>>> pearson_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
29
|
-
0.7745966692414834
|
|
30
|
-
"""
|
|
31
|
-
x = _validate_data(x)
|
|
32
|
-
y = _validate_data(y)
|
|
33
|
-
|
|
34
|
-
if len(x) != len(y):
|
|
35
|
-
raise ValueError("Variables must have the same length")
|
|
36
|
-
|
|
37
|
-
if len(x) < 2:
|
|
38
|
-
raise ValueError("At least 2 data points required")
|
|
39
|
-
|
|
40
|
-
n = len(x)
|
|
41
|
-
sum_x = sum(x)
|
|
42
|
-
sum_y = sum(y)
|
|
43
|
-
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
|
|
44
|
-
sum_x2 = sum(xi ** 2 for xi in x)
|
|
45
|
-
sum_y2 = sum(yi ** 2 for yi in y)
|
|
46
|
-
|
|
47
|
-
numerator = n * sum_xy - sum_x * sum_y
|
|
48
|
-
denominator = math.sqrt((n * sum_x2 - sum_x ** 2) * (n * sum_y2 - sum_y ** 2))
|
|
49
|
-
|
|
50
|
-
if denominator == 0:
|
|
51
|
-
return 0.0
|
|
52
|
-
|
|
53
|
-
return numerator / denominator
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def
|
|
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
|
-
Returns:
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
Example:
|
|
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
|
-
if
|
|
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
|
-
|
|
1
|
+
"""
|
|
2
|
+
Multivariate statistics functions for py-stats package.
|
|
3
|
+
|
|
4
|
+
This module provides comprehensive multivariate statistical analysis functions
|
|
5
|
+
including correlation coefficients, covariance, regression analysis, and
|
|
6
|
+
association measures.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import numbers
|
|
11
|
+
from typing import List, Union, Tuple, Optional
|
|
12
|
+
|
|
13
|
+
from .univariate import _validate_data, arithmetic_mean
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def pearson_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
17
|
+
"""
|
|
18
|
+
Calculate Pearson's correlation coefficient.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
x: First variable data
|
|
22
|
+
y: Second variable data
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Pearson correlation coefficient (-1 to 1)
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
>>> pearson_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
29
|
+
0.7745966692414834
|
|
30
|
+
"""
|
|
31
|
+
x = _validate_data(x)
|
|
32
|
+
y = _validate_data(y)
|
|
33
|
+
|
|
34
|
+
if len(x) != len(y):
|
|
35
|
+
raise ValueError("Variables must have the same length")
|
|
36
|
+
|
|
37
|
+
if len(x) < 2:
|
|
38
|
+
raise ValueError("At least 2 data points required")
|
|
39
|
+
|
|
40
|
+
n = len(x)
|
|
41
|
+
sum_x = sum(x)
|
|
42
|
+
sum_y = sum(y)
|
|
43
|
+
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
|
|
44
|
+
sum_x2 = sum(xi ** 2 for xi in x)
|
|
45
|
+
sum_y2 = sum(yi ** 2 for yi in y)
|
|
46
|
+
|
|
47
|
+
numerator = n * sum_xy - sum_x * sum_y
|
|
48
|
+
denominator = math.sqrt((n * sum_x2 - sum_x ** 2) * (n * sum_y2 - sum_y ** 2))
|
|
49
|
+
|
|
50
|
+
if denominator == 0:
|
|
51
|
+
return 0.0
|
|
52
|
+
|
|
53
|
+
return numerator / denominator
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def product_concentration_ratio(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
57
|
+
"""
|
|
58
|
+
Ratio of the geometric to the arithmetic mean of the paired products x*y.
|
|
59
|
+
|
|
60
|
+
This measures how EVEN the products are, not whether x and y are related.
|
|
61
|
+
It is 1 when every product is identical and falls towards 0 as they spread
|
|
62
|
+
apart, so it is a concentration (inequality) index rather than a
|
|
63
|
+
correlation. It cannot express direction and never goes negative.
|
|
64
|
+
|
|
65
|
+
This function was called q_correlation up to version 1.0.1, which was
|
|
66
|
+
misleading: anti-correlated data scores higher than perfectly correlated
|
|
67
|
+
data under it. q_correlation now implements Yule's Q. For the strength and
|
|
68
|
+
direction of a relationship use pearson_correlation, spearman_correlation
|
|
69
|
+
or kendall_tau.
|
|
70
|
+
|
|
71
|
+
Requires every x*y product to be strictly positive, since the geometric
|
|
72
|
+
mean of a negative number is undefined.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
x: First variable data
|
|
76
|
+
y: Second variable data
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Ratio in (0, 1]
|
|
80
|
+
|
|
81
|
+
Example:
|
|
82
|
+
>>> product_concentration_ratio([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
83
|
+
0.7514157873352774
|
|
84
|
+
>>> product_concentration_ratio([1, 2, 4], [4, 2, 1]) # products all 4
|
|
85
|
+
1.0
|
|
86
|
+
"""
|
|
87
|
+
x = _validate_data(x)
|
|
88
|
+
y = _validate_data(y)
|
|
89
|
+
|
|
90
|
+
if len(x) != len(y):
|
|
91
|
+
raise ValueError("Variables must have the same length")
|
|
92
|
+
|
|
93
|
+
if len(x) < 2:
|
|
94
|
+
raise ValueError("At least 2 data points required")
|
|
95
|
+
|
|
96
|
+
products = [xi * yi for xi, yi in zip(x, y)]
|
|
97
|
+
|
|
98
|
+
# The geometric mean is only defined for positive values. A single negative
|
|
99
|
+
# product used to surface as "math domain error" from inside math.pow.
|
|
100
|
+
if any(pr <= 0 for pr in products):
|
|
101
|
+
raise ValueError(
|
|
102
|
+
"This index requires every x*y product to be positive; "
|
|
103
|
+
"it is undefined for data with differing signs or zeros"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# Sum of logs rather than prod-then-root, which overflows for large inputs.
|
|
107
|
+
geometric_mean = math.exp(
|
|
108
|
+
math.fsum(math.log(pr) for pr in products) / len(products)
|
|
109
|
+
)
|
|
110
|
+
arithmetic_mean_products = arithmetic_mean(products)
|
|
111
|
+
|
|
112
|
+
if arithmetic_mean_products == 0:
|
|
113
|
+
return 0.0
|
|
114
|
+
|
|
115
|
+
return geometric_mean / arithmetic_mean_products
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def q_correlation(x: List[Union[int, float, bool]], y: List[Union[int, float, bool]]) -> float:
|
|
119
|
+
"""
|
|
120
|
+
Calculate Yule's Q, the association between two binary variables.
|
|
121
|
+
|
|
122
|
+
Yule's Q is the standard coefficient named Q. It is built from the 2x2
|
|
123
|
+
table of counts
|
|
124
|
+
|
|
125
|
+
a = both 1 b = x is 1, y is 0
|
|
126
|
+
c = x is 0, y is 1 d = both 0
|
|
127
|
+
|
|
128
|
+
as (ad - bc) / (ad + bc), which is equivalent to (OR - 1) / (OR + 1) for
|
|
129
|
+
the odds ratio OR = ad / bc. It runs from -1 (perfect negative
|
|
130
|
+
association) through 0 (none) to +1 (perfect positive association), and
|
|
131
|
+
reaches +-1 as soon as any one cell is empty.
|
|
132
|
+
|
|
133
|
+
Both variables must be binary: booleans, or the numbers 0 and 1. For two
|
|
134
|
+
continuous variables use pearson_correlation or spearman_correlation.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
x: First binary variable
|
|
138
|
+
y: Second binary variable
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
Yule's Q, between -1 and 1
|
|
142
|
+
|
|
143
|
+
Raises:
|
|
144
|
+
ValueError: If the inputs are not binary, differ in length, or leave
|
|
145
|
+
a margin of the table empty, which makes Q undefined.
|
|
146
|
+
|
|
147
|
+
Example:
|
|
148
|
+
>>> q_correlation([1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0])
|
|
149
|
+
1.0
|
|
150
|
+
>>> q_correlation([1, 1, 0, 0], [1, 0, 1, 0])
|
|
151
|
+
0.0
|
|
152
|
+
"""
|
|
153
|
+
if len(x) != len(y):
|
|
154
|
+
raise ValueError("Variables must have the same length")
|
|
155
|
+
|
|
156
|
+
if len(x) < 2:
|
|
157
|
+
raise ValueError("At least 2 data points required")
|
|
158
|
+
|
|
159
|
+
def as_binary(values, name):
|
|
160
|
+
out = []
|
|
161
|
+
for v in values:
|
|
162
|
+
if isinstance(v, bool):
|
|
163
|
+
out.append(1 if v else 0)
|
|
164
|
+
elif isinstance(v, numbers.Real) and float(v) in (0.0, 1.0):
|
|
165
|
+
out.append(int(v))
|
|
166
|
+
else:
|
|
167
|
+
raise ValueError(
|
|
168
|
+
f"{name} must contain only booleans or 0/1 values"
|
|
169
|
+
)
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
xb = as_binary(x, "x")
|
|
173
|
+
yb = as_binary(y, "y")
|
|
174
|
+
|
|
175
|
+
a = sum(1 for xi, yi in zip(xb, yb) if xi == 1 and yi == 1)
|
|
176
|
+
b = sum(1 for xi, yi in zip(xb, yb) if xi == 1 and yi == 0)
|
|
177
|
+
c = sum(1 for xi, yi in zip(xb, yb) if xi == 0 and yi == 1)
|
|
178
|
+
d = sum(1 for xi, yi in zip(xb, yb) if xi == 0 and yi == 0)
|
|
179
|
+
|
|
180
|
+
# An empty row or column means one variable never varies, so there is no
|
|
181
|
+
# association to measure and both ad and bc are zero.
|
|
182
|
+
if (a + b) == 0 or (c + d) == 0 or (a + c) == 0 or (b + d) == 0:
|
|
183
|
+
raise ValueError(
|
|
184
|
+
"Yule's Q is undefined when either variable is constant"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
return (a * d - b * c) / (a * d + b * c)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def covariance(x: List[Union[int, float]], y: List[Union[int, float]], population: bool = False) -> float:
|
|
191
|
+
"""
|
|
192
|
+
Calculate covariance between two variables.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
x: First variable data
|
|
196
|
+
y: Second variable data
|
|
197
|
+
population: If True, calculate population covariance (n denominator)
|
|
198
|
+
If False, calculate sample covariance (n-1 denominator)
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
Covariance
|
|
202
|
+
|
|
203
|
+
Example:
|
|
204
|
+
>>> covariance([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
205
|
+
1.5
|
|
206
|
+
"""
|
|
207
|
+
x = _validate_data(x)
|
|
208
|
+
y = _validate_data(y)
|
|
209
|
+
|
|
210
|
+
if len(x) != len(y):
|
|
211
|
+
raise ValueError("Variables must have the same length")
|
|
212
|
+
|
|
213
|
+
if len(x) < 2:
|
|
214
|
+
raise ValueError("At least 2 data points required")
|
|
215
|
+
|
|
216
|
+
mean_x = arithmetic_mean(x)
|
|
217
|
+
mean_y = arithmetic_mean(y)
|
|
218
|
+
|
|
219
|
+
sum_xy = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
|
|
220
|
+
|
|
221
|
+
denominator = len(x) if population else len(x) - 1
|
|
222
|
+
return sum_xy / denominator
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def linear_regression(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[float, float, float]:
|
|
226
|
+
"""
|
|
227
|
+
Perform simple linear regression.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
x: Independent variable data
|
|
231
|
+
y: Dependent variable data
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
Tuple of (slope, intercept, r_squared)
|
|
235
|
+
|
|
236
|
+
Example:
|
|
237
|
+
>>> slope, intercept, r_squared = linear_regression([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
238
|
+
>>> print(f"y = {slope:.2f}x + {intercept:.2f}, R-squared = {r_squared:.3f}")
|
|
239
|
+
y = 0.60x + 2.20, R-squared = 0.600
|
|
240
|
+
"""
|
|
241
|
+
x = _validate_data(x)
|
|
242
|
+
y = _validate_data(y)
|
|
243
|
+
|
|
244
|
+
if len(x) != len(y):
|
|
245
|
+
raise ValueError("Variables must have the same length")
|
|
246
|
+
|
|
247
|
+
if len(x) < 2:
|
|
248
|
+
raise ValueError("At least 2 data points required")
|
|
249
|
+
|
|
250
|
+
n = len(x)
|
|
251
|
+
sum_x = sum(x)
|
|
252
|
+
sum_y = sum(y)
|
|
253
|
+
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
|
|
254
|
+
sum_x2 = sum(xi ** 2 for xi in x)
|
|
255
|
+
|
|
256
|
+
# Calculate slope and intercept
|
|
257
|
+
# A constant x has no spread to regress against; without this the division
|
|
258
|
+
# surfaced as a bare ZeroDivisionError.
|
|
259
|
+
denominator = n * sum_x2 - sum_x ** 2
|
|
260
|
+
if denominator == 0:
|
|
261
|
+
raise ValueError(
|
|
262
|
+
"Cannot fit a line when x has no variation (all x values are equal)"
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
slope = (n * sum_xy - sum_x * sum_y) / denominator
|
|
266
|
+
intercept = (sum_y - slope * sum_x) / n
|
|
267
|
+
|
|
268
|
+
# Calculate R-squared
|
|
269
|
+
mean_y = arithmetic_mean(y)
|
|
270
|
+
ss_tot = sum((yi - mean_y) ** 2 for yi in y)
|
|
271
|
+
ss_res = sum((yi - (slope * xi + intercept)) ** 2 for xi, yi in zip(x, y))
|
|
272
|
+
|
|
273
|
+
# R-squared has no meaning when y is constant: there is no variance to
|
|
274
|
+
# explain. Reported as 0.0 (a float, so the return type does not change
|
|
275
|
+
# with the data) rather than 1.0, which would claim a perfect fit.
|
|
276
|
+
r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0.0
|
|
277
|
+
|
|
278
|
+
return slope, intercept, r_squared
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def sum_xx(x: List[Union[int, float]]) -> float:
|
|
282
|
+
"""
|
|
283
|
+
Calculate sum of squared deviations from mean (Sxx).
|
|
284
|
+
|
|
285
|
+
Args:
|
|
286
|
+
x: Variable data
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
Sum of squared deviations
|
|
290
|
+
|
|
291
|
+
Example:
|
|
292
|
+
>>> sum_xx([1, 2, 3, 4, 5])
|
|
293
|
+
10.0
|
|
294
|
+
"""
|
|
295
|
+
x = _validate_data(x)
|
|
296
|
+
mean_x = arithmetic_mean(x)
|
|
297
|
+
return sum((xi - mean_x) ** 2 for xi in x)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def sum_yy(y: List[Union[int, float]]) -> float:
|
|
301
|
+
"""
|
|
302
|
+
Calculate sum of squared deviations from mean (Syy).
|
|
303
|
+
|
|
304
|
+
Args:
|
|
305
|
+
y: Variable data
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
Sum of squared deviations
|
|
309
|
+
|
|
310
|
+
Example:
|
|
311
|
+
>>> sum_yy([2, 4, 5, 4, 5])
|
|
312
|
+
6.0
|
|
313
|
+
"""
|
|
314
|
+
y = _validate_data(y)
|
|
315
|
+
mean_y = arithmetic_mean(y)
|
|
316
|
+
return sum((yi - mean_y) ** 2 for yi in y)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def sum_xy(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
320
|
+
"""
|
|
321
|
+
Calculate sum of cross-products of deviations (Sxy).
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
x: First variable data
|
|
325
|
+
y: Second variable data
|
|
326
|
+
|
|
327
|
+
Returns:
|
|
328
|
+
Sum of cross-products
|
|
329
|
+
|
|
330
|
+
Example:
|
|
331
|
+
>>> sum_xy([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
332
|
+
6.0
|
|
333
|
+
"""
|
|
334
|
+
x = _validate_data(x)
|
|
335
|
+
y = _validate_data(y)
|
|
336
|
+
|
|
337
|
+
if len(x) != len(y):
|
|
338
|
+
raise ValueError("Variables must have the same length")
|
|
339
|
+
|
|
340
|
+
mean_x = arithmetic_mean(x)
|
|
341
|
+
mean_y = arithmetic_mean(y)
|
|
342
|
+
|
|
343
|
+
return sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# Additional correlation functions
|
|
347
|
+
|
|
348
|
+
def spearman_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
349
|
+
"""
|
|
350
|
+
Calculate Spearman's rank correlation coefficient.
|
|
351
|
+
|
|
352
|
+
Spearman correlation measures the strength of monotonic relationship.
|
|
353
|
+
|
|
354
|
+
Args:
|
|
355
|
+
x: First variable data
|
|
356
|
+
y: Second variable data
|
|
357
|
+
|
|
358
|
+
Returns:
|
|
359
|
+
Spearman correlation coefficient (-1 to 1)
|
|
360
|
+
|
|
361
|
+
Example:
|
|
362
|
+
>>> spearman_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
363
|
+
0.7378647873726218
|
|
364
|
+
"""
|
|
365
|
+
x = _validate_data(x)
|
|
366
|
+
y = _validate_data(y)
|
|
367
|
+
|
|
368
|
+
if len(x) != len(y):
|
|
369
|
+
raise ValueError("Variables must have the same length")
|
|
370
|
+
|
|
371
|
+
if len(x) < 2:
|
|
372
|
+
raise ValueError("At least 2 data points required")
|
|
373
|
+
|
|
374
|
+
# Create rank mappings
|
|
375
|
+
def get_ranks(data):
|
|
376
|
+
"""Rank with ties averaged (the midrank), as Spearman requires.
|
|
377
|
+
|
|
378
|
+
Assigning tied values distinct index-ordered ranks made the measure
|
|
379
|
+
depend on input order and reported a perfect 1.0 for data that was
|
|
380
|
+
merely non-decreasing.
|
|
381
|
+
"""
|
|
382
|
+
order = sorted(range(len(data)), key=lambda i: data[i])
|
|
383
|
+
ranks = [0.0] * len(data)
|
|
384
|
+
i = 0
|
|
385
|
+
while i < len(order):
|
|
386
|
+
j = i
|
|
387
|
+
while j + 1 < len(order) and data[order[j + 1]] == data[order[i]]:
|
|
388
|
+
j += 1
|
|
389
|
+
midrank = (i + j) / 2.0 + 1.0
|
|
390
|
+
for k in range(i, j + 1):
|
|
391
|
+
ranks[order[k]] = midrank
|
|
392
|
+
i = j + 1
|
|
393
|
+
return ranks
|
|
394
|
+
|
|
395
|
+
rank_x = get_ranks(x)
|
|
396
|
+
rank_y = get_ranks(y)
|
|
397
|
+
|
|
398
|
+
# Calculate correlation using Pearson's formula on ranks
|
|
399
|
+
n = len(rank_x)
|
|
400
|
+
sum_rank_x = sum(rank_x)
|
|
401
|
+
sum_rank_y = sum(rank_y)
|
|
402
|
+
sum_rank_xy = sum(rx * ry for rx, ry in zip(rank_x, rank_y))
|
|
403
|
+
sum_rank_x2 = sum(rx ** 2 for rx in rank_x)
|
|
404
|
+
sum_rank_y2 = sum(ry ** 2 for ry in rank_y)
|
|
405
|
+
|
|
406
|
+
numerator = n * sum_rank_xy - sum_rank_x * sum_rank_y
|
|
407
|
+
denominator = math.sqrt((n * sum_rank_x2 - sum_rank_x ** 2) * (n * sum_rank_y2 - sum_rank_y ** 2))
|
|
408
|
+
|
|
409
|
+
# A constant variable has no ranking to correlate with. Returning 0.0 here
|
|
410
|
+
# would assert independence we cannot know; the old code reached this only
|
|
411
|
+
# by accident and returned 1.0 for a constant y.
|
|
412
|
+
if denominator == 0:
|
|
413
|
+
raise ValueError(
|
|
414
|
+
"Spearman correlation is undefined when a variable is constant"
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
return numerator / denominator
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def kendall_tau(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
421
|
+
"""
|
|
422
|
+
Calculate Kendall's tau correlation coefficient.
|
|
423
|
+
|
|
424
|
+
Kendall's tau measures ordinal association between variables.
|
|
425
|
+
|
|
426
|
+
Args:
|
|
427
|
+
x: First variable data
|
|
428
|
+
y: Second variable data
|
|
429
|
+
|
|
430
|
+
Returns:
|
|
431
|
+
Kendall's tau coefficient (-1 to 1)
|
|
432
|
+
|
|
433
|
+
Example:
|
|
434
|
+
>>> kendall_tau([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
435
|
+
0.6708203932499369
|
|
436
|
+
"""
|
|
437
|
+
x = _validate_data(x)
|
|
438
|
+
y = _validate_data(y)
|
|
439
|
+
|
|
440
|
+
if len(x) != len(y):
|
|
441
|
+
raise ValueError("Variables must have the same length")
|
|
442
|
+
|
|
443
|
+
if len(x) < 2:
|
|
444
|
+
raise ValueError("At least 2 data points required")
|
|
445
|
+
|
|
446
|
+
n = len(x)
|
|
447
|
+
concordant = 0
|
|
448
|
+
discordant = 0
|
|
449
|
+
ties_x = 0
|
|
450
|
+
ties_y = 0
|
|
451
|
+
|
|
452
|
+
for i in range(n):
|
|
453
|
+
for j in range(i + 1, n):
|
|
454
|
+
# Classify on the signs of the two differences, never on their
|
|
455
|
+
# product. A product underflows to 0.0 when both differences are
|
|
456
|
+
# tiny -- (1e-300 - 0.0) ** 2 is exactly 0.0 -- and the pair then
|
|
457
|
+
# looked tied on neither variable, so it fell out of the numerator
|
|
458
|
+
# while staying in the denominator. [1e-310, 2e-310, 3e-310,
|
|
459
|
+
# 4e-310] against itself reported tau = 0.0 instead of 1.0.
|
|
460
|
+
x_sign = (x[i] > x[j]) - (x[i] < x[j])
|
|
461
|
+
y_sign = (y[i] > y[j]) - (y[i] < y[j])
|
|
462
|
+
|
|
463
|
+
if x_sign == 0 or y_sign == 0:
|
|
464
|
+
# Tied on at least one variable. These were previously left in
|
|
465
|
+
# the denominator untouched (tau-a), which silently reported a
|
|
466
|
+
# different statistic than the tau-b every other tool returns.
|
|
467
|
+
if x_sign == 0:
|
|
468
|
+
ties_x += 1
|
|
469
|
+
if y_sign == 0:
|
|
470
|
+
ties_y += 1
|
|
471
|
+
elif x_sign == y_sign:
|
|
472
|
+
concordant += 1
|
|
473
|
+
else:
|
|
474
|
+
discordant += 1
|
|
475
|
+
|
|
476
|
+
total_pairs = n * (n - 1) / 2
|
|
477
|
+
|
|
478
|
+
# tau-b normalises by the pairs that were actually comparable on each
|
|
479
|
+
# variable, so ties do not drag the coefficient towards zero.
|
|
480
|
+
denominator = math.sqrt((total_pairs - ties_x) * (total_pairs - ties_y))
|
|
481
|
+
|
|
482
|
+
if denominator == 0:
|
|
483
|
+
raise ValueError(
|
|
484
|
+
"Kendall's tau is undefined when every pair is tied on a variable"
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
return (concordant - discordant) / denominator
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def point_biserial_correlation(x: List[Union[int, float]], y: List[bool]) -> float:
|
|
491
|
+
"""
|
|
492
|
+
Calculate point-biserial correlation coefficient.
|
|
493
|
+
|
|
494
|
+
Point-biserial correlation measures the relationship between a continuous
|
|
495
|
+
variable and a binary variable.
|
|
496
|
+
|
|
497
|
+
Args:
|
|
498
|
+
x: Continuous variable data
|
|
499
|
+
y: Binary variable data (True/False or 1/0)
|
|
500
|
+
|
|
501
|
+
Returns:
|
|
502
|
+
Point-biserial correlation coefficient (-1 to 1)
|
|
503
|
+
|
|
504
|
+
Example:
|
|
505
|
+
>>> point_biserial_correlation([1, 2, 3, 4, 5], [False, False, True, True, True])
|
|
506
|
+
0.8660254037844385
|
|
507
|
+
"""
|
|
508
|
+
x = _validate_data(x)
|
|
509
|
+
|
|
510
|
+
if len(x) != len(y):
|
|
511
|
+
raise ValueError("Variables must have the same length")
|
|
512
|
+
|
|
513
|
+
if len(x) < 2:
|
|
514
|
+
raise ValueError("At least 2 data points required")
|
|
515
|
+
|
|
516
|
+
# Convert boolean to numeric. "1 if yi else 0" accepted any truthy object,
|
|
517
|
+
# so a stray string like "maybe" was silently counted as the 1 group.
|
|
518
|
+
y_numeric = []
|
|
519
|
+
for yi in y:
|
|
520
|
+
if isinstance(yi, bool):
|
|
521
|
+
y_numeric.append(1 if yi else 0)
|
|
522
|
+
elif isinstance(yi, numbers.Real) and float(yi) in (0.0, 1.0):
|
|
523
|
+
y_numeric.append(int(yi))
|
|
524
|
+
else:
|
|
525
|
+
raise ValueError(
|
|
526
|
+
"Binary variable must contain only booleans or 0/1 values"
|
|
527
|
+
)
|
|
528
|
+
|
|
529
|
+
# Calculate means for each group
|
|
530
|
+
group_1 = [xi for xi, yi in zip(x, y_numeric) if yi == 1]
|
|
531
|
+
group_0 = [xi for xi, yi in zip(x, y_numeric) if yi == 0]
|
|
532
|
+
|
|
533
|
+
if not group_1 or not group_0:
|
|
534
|
+
return 0.0
|
|
535
|
+
|
|
536
|
+
mean_1 = arithmetic_mean(group_1)
|
|
537
|
+
mean_0 = arithmetic_mean(group_0)
|
|
538
|
+
|
|
539
|
+
# Calculate standard deviation
|
|
540
|
+
# Population SD (divide by n). The point-biserial coefficient is defined to
|
|
541
|
+
# equal Pearson's r on the same data; using the sample SD (n-1) made the
|
|
542
|
+
# two disagree, e.g. -0.7746 against Pearson's -0.8660.
|
|
543
|
+
std_x = math.sqrt(sum_xx(x) / len(x))
|
|
544
|
+
|
|
545
|
+
if std_x == 0:
|
|
546
|
+
return 0.0
|
|
547
|
+
|
|
548
|
+
# Calculate proportions
|
|
549
|
+
p = len(group_1) / len(x)
|
|
550
|
+
q = 1 - p
|
|
551
|
+
|
|
552
|
+
# Point-biserial correlation formula
|
|
553
|
+
return (mean_1 - mean_0) / std_x * math.sqrt(p * q)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
# Multiple regression functions
|
|
557
|
+
|
|
558
|
+
def multiple_linear_regression(x_vars: List[List[Union[int, float]]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
|
|
559
|
+
"""
|
|
560
|
+
Perform multiple linear regression.
|
|
561
|
+
|
|
562
|
+
Args:
|
|
563
|
+
x_vars: List of independent variable data (each inner list is one variable)
|
|
564
|
+
y: Dependent variable data
|
|
565
|
+
|
|
566
|
+
Returns:
|
|
567
|
+
Tuple of (coefficients, intercept, r_squared)
|
|
568
|
+
|
|
569
|
+
Example:
|
|
570
|
+
>>> x1 = [1, 2, 3, 4, 5]
|
|
571
|
+
>>> x2 = [1, 1, 2, 3, 5]
|
|
572
|
+
>>> y = [1 + 2 * a + 3 * b for a, b in zip(x1, x2)]
|
|
573
|
+
>>> coeffs, intercept, r_sq = multiple_linear_regression([x1, x2], y)
|
|
574
|
+
>>> [round(c, 6) for c in coeffs], round(intercept, 6)
|
|
575
|
+
([2.0, 3.0], 1.0)
|
|
576
|
+
"""
|
|
577
|
+
if not x_vars:
|
|
578
|
+
raise ValueError("At least one independent variable required")
|
|
579
|
+
|
|
580
|
+
# Validate all variables have same length
|
|
581
|
+
lengths = [len(x) for x in x_vars] + [len(y)]
|
|
582
|
+
if len(set(lengths)) != 1:
|
|
583
|
+
raise ValueError("All variables must have the same length")
|
|
584
|
+
|
|
585
|
+
# Validate data
|
|
586
|
+
x_vars = [_validate_data(x) for x in x_vars]
|
|
587
|
+
y = _validate_data(y)
|
|
588
|
+
|
|
589
|
+
n = len(y)
|
|
590
|
+
k = len(x_vars)
|
|
591
|
+
|
|
592
|
+
if n <= k:
|
|
593
|
+
raise ValueError("Number of observations must be greater than number of variables")
|
|
594
|
+
|
|
595
|
+
# Solve the normal equations (X'X) b = X'y by Gaussian elimination with
|
|
596
|
+
# partial pivoting. The previous implementation special-cased k == 1 and
|
|
597
|
+
# returned [0.0] * k for anything larger, so every fit with two or more
|
|
598
|
+
# predictors silently reported zero coefficients.
|
|
599
|
+
X = []
|
|
600
|
+
for i in range(n):
|
|
601
|
+
row = [1.0] # intercept term
|
|
602
|
+
for j in range(k):
|
|
603
|
+
row.append(float(x_vars[j][i]))
|
|
604
|
+
X.append(row)
|
|
605
|
+
|
|
606
|
+
size = k + 1
|
|
607
|
+
# Augmented matrix [X'X | X'y]
|
|
608
|
+
aug = []
|
|
609
|
+
for i in range(size):
|
|
610
|
+
row = [sum(X[r][i] * X[r][j] for r in range(n)) for j in range(size)]
|
|
611
|
+
row.append(sum(X[r][i] * y[r] for r in range(n)))
|
|
612
|
+
aug.append(row)
|
|
613
|
+
|
|
614
|
+
# Scale the singularity threshold to the matrix, so the test means the same
|
|
615
|
+
# thing whether the data is in millimetres or kilometres.
|
|
616
|
+
scale = max(abs(v) for row in aug for v in row[:size]) or 1.0
|
|
617
|
+
|
|
618
|
+
for col in range(size):
|
|
619
|
+
pivot_row = max(range(col, size), key=lambda r: abs(aug[r][col]))
|
|
620
|
+
if abs(aug[pivot_row][col]) <= 1e-12 * scale:
|
|
621
|
+
raise ValueError(
|
|
622
|
+
"Singular matrix - variables may be collinear"
|
|
623
|
+
)
|
|
624
|
+
aug[col], aug[pivot_row] = aug[pivot_row], aug[col]
|
|
625
|
+
|
|
626
|
+
pivot = aug[col][col]
|
|
627
|
+
for r in range(size):
|
|
628
|
+
if r == col:
|
|
629
|
+
continue
|
|
630
|
+
factor = aug[r][col] / pivot
|
|
631
|
+
if factor:
|
|
632
|
+
for c in range(col, size + 1):
|
|
633
|
+
aug[r][c] -= factor * aug[col][c]
|
|
634
|
+
|
|
635
|
+
solution = [aug[i][size] / aug[i][i] for i in range(size)]
|
|
636
|
+
intercept = solution[0]
|
|
637
|
+
coefficients = solution[1:]
|
|
638
|
+
|
|
639
|
+
# Calculate R-squared
|
|
640
|
+
y_pred = [intercept + sum(coeff * x_vars[j][i] for j, coeff in enumerate(coefficients)) for i in range(n)]
|
|
641
|
+
ss_tot = sum((yi - arithmetic_mean(y)) ** 2 for yi in y)
|
|
642
|
+
ss_res = sum((yi - y_pred[i]) ** 2 for i, yi in enumerate(y))
|
|
643
|
+
|
|
644
|
+
r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0
|
|
645
|
+
|
|
646
|
+
return coefficients, intercept, r_squared
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def polynomial_regression(x: List[Union[int, float]], y: List[Union[int, float]], degree: int = 2) -> Tuple[List[float], float]:
|
|
650
|
+
"""
|
|
651
|
+
Perform polynomial regression.
|
|
652
|
+
|
|
653
|
+
Args:
|
|
654
|
+
x: Independent variable data
|
|
655
|
+
y: Dependent variable data
|
|
656
|
+
degree: Degree of polynomial (1=linear, 2=quadratic, etc.)
|
|
657
|
+
|
|
658
|
+
Returns:
|
|
659
|
+
Tuple of (coefficients, r_squared). Coefficients are ordered highest
|
|
660
|
+
degree first, as numpy.polyfit returns them: for degree=2 the list is
|
|
661
|
+
[a, b, c] for a*x**2 + b*x + c.
|
|
662
|
+
|
|
663
|
+
Example:
|
|
664
|
+
>>> x = [1, 2, 3, 4, 5]
|
|
665
|
+
>>> y = [1, 4, 9, 16, 25]
|
|
666
|
+
>>> coeffs, r_sq = polynomial_regression(x, y, degree=2)
|
|
667
|
+
"""
|
|
668
|
+
x = _validate_data(x)
|
|
669
|
+
y = _validate_data(y)
|
|
670
|
+
|
|
671
|
+
if len(x) != len(y):
|
|
672
|
+
raise ValueError("Variables must have the same length")
|
|
673
|
+
|
|
674
|
+
if degree < 1:
|
|
675
|
+
raise ValueError("Degree must be at least 1")
|
|
676
|
+
|
|
677
|
+
if len(x) <= degree:
|
|
678
|
+
raise ValueError("Number of observations must be greater than degree")
|
|
679
|
+
|
|
680
|
+
# Create polynomial features
|
|
681
|
+
x_vars = []
|
|
682
|
+
for d in range(1, degree + 1):
|
|
683
|
+
x_vars.append([xi ** d for xi in x])
|
|
684
|
+
|
|
685
|
+
# Use multiple regression
|
|
686
|
+
coefficients, intercept, r_squared = multiple_linear_regression(x_vars, y)
|
|
687
|
+
|
|
688
|
+
# Highest degree first, matching numpy.polyfit, so coefficients[0] is the
|
|
689
|
+
# leading term. The order was previously undocumented and ran the other
|
|
690
|
+
# way, which made the returned list easy to misread.
|
|
691
|
+
all_coefficients = list(reversed(coefficients)) + [intercept]
|
|
692
|
+
|
|
693
|
+
return all_coefficients, r_squared
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def residual_analysis(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
|
|
697
|
+
"""
|
|
698
|
+
Perform residual analysis for linear regression.
|
|
699
|
+
|
|
700
|
+
Args:
|
|
701
|
+
x: Independent variable data
|
|
702
|
+
y: Dependent variable data
|
|
703
|
+
|
|
704
|
+
Returns:
|
|
705
|
+
Tuple of (residuals, r_squared, adjusted_r_squared)
|
|
706
|
+
|
|
707
|
+
Example:
|
|
708
|
+
>>> x = [1, 2, 3, 4, 5]
|
|
709
|
+
>>> y = [2, 4, 5, 4, 5]
|
|
710
|
+
>>> residuals, r_sq, adj_r_sq = residual_analysis(x, y)
|
|
711
|
+
"""
|
|
712
|
+
x = _validate_data(x)
|
|
713
|
+
y = _validate_data(y)
|
|
714
|
+
|
|
715
|
+
if len(x) != len(y):
|
|
716
|
+
raise ValueError("Variables must have the same length")
|
|
717
|
+
|
|
718
|
+
if len(x) < 3:
|
|
719
|
+
raise ValueError("At least 3 data points required")
|
|
720
|
+
|
|
721
|
+
# Perform regression
|
|
722
|
+
slope, intercept, r_squared = linear_regression(x, y)
|
|
723
|
+
|
|
724
|
+
# Calculate residuals
|
|
725
|
+
residuals = [yi - (slope * xi + intercept) for xi, yi in zip(x, y)]
|
|
726
|
+
|
|
727
|
+
# Calculate adjusted R-squared
|
|
728
|
+
n = len(x)
|
|
729
|
+
k = 1 # Number of independent variables
|
|
730
|
+
adjusted_r_squared = 1 - ((1 - r_squared) * (n - 1) / (n - k - 1))
|
|
731
|
+
|
|
732
|
+
return residuals, r_squared, adjusted_r_squared
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
# Association measures for categorical data
|
|
736
|
+
|
|
737
|
+
def _upper_regularized_gamma(s_param: float, x: float) -> float:
|
|
738
|
+
"""Regularized upper incomplete gamma Q(s, x) = 1 - P(s, x).
|
|
739
|
+
|
|
740
|
+
Returns the UPPER function directly rather than 1 - lower. In the far tail
|
|
741
|
+
the lower function is indistinguishable from 1.0 in double precision, so
|
|
742
|
+
subtracting it collapses the answer to exactly 0.0 -- at df=1, chi2=120
|
|
743
|
+
that turned 6.3e-28 into nothing. The continued fraction below computes Q
|
|
744
|
+
without that cancellation.
|
|
745
|
+
|
|
746
|
+
Series expansion for x < s+1, continued fraction otherwise, which is where
|
|
747
|
+
each converges quickly. Pure Python so the package keeps no dependencies.
|
|
748
|
+
"""
|
|
749
|
+
if x <= 0:
|
|
750
|
+
return 1.0
|
|
751
|
+
|
|
752
|
+
log_gamma_s = math.lgamma(s_param)
|
|
753
|
+
|
|
754
|
+
if x < s_param + 1.0:
|
|
755
|
+
# Series for the lower function; Q is not small in this region, so
|
|
756
|
+
# taking 1 - P here costs no meaningful precision.
|
|
757
|
+
term = 1.0 / s_param
|
|
758
|
+
total = term
|
|
759
|
+
for n in range(1, 1000):
|
|
760
|
+
term *= x / (s_param + n)
|
|
761
|
+
total += term
|
|
762
|
+
if abs(term) < abs(total) * 1e-16:
|
|
763
|
+
break
|
|
764
|
+
lower = total * math.exp(-x + s_param * math.log(x) - log_gamma_s)
|
|
765
|
+
return 1.0 - lower
|
|
766
|
+
|
|
767
|
+
# Lentz's continued fraction for Q(s, x), accurate deep into the tail.
|
|
768
|
+
tiny = 1e-300
|
|
769
|
+
b = x + 1.0 - s_param
|
|
770
|
+
c = 1.0 / tiny
|
|
771
|
+
d = 1.0 / b
|
|
772
|
+
h = d
|
|
773
|
+
for i in range(1, 1000):
|
|
774
|
+
an = -i * (i - s_param)
|
|
775
|
+
b += 2.0
|
|
776
|
+
d = an * d + b
|
|
777
|
+
if abs(d) < tiny:
|
|
778
|
+
d = tiny
|
|
779
|
+
c = b + an / c
|
|
780
|
+
if abs(c) < tiny:
|
|
781
|
+
c = tiny
|
|
782
|
+
d = 1.0 / d
|
|
783
|
+
delta = d * c
|
|
784
|
+
h *= delta
|
|
785
|
+
if abs(delta - 1.0) < 1e-16:
|
|
786
|
+
break
|
|
787
|
+
return math.exp(-x + s_param * math.log(x) - log_gamma_s) * h
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
def _chi_square_sf(chi_square: float, df: int) -> float:
|
|
791
|
+
"""Upper tail probability of the chi-square distribution.
|
|
792
|
+
|
|
793
|
+
This replaces two approximations that were wrong in different ways: the
|
|
794
|
+
df == 1 branch halved the z-score, and the df > 1 branch used
|
|
795
|
+
1 - chi/(df+chi), which is not a distribution function at all. Both could
|
|
796
|
+
reverse a significance decision.
|
|
797
|
+
"""
|
|
798
|
+
if df <= 0:
|
|
799
|
+
raise ValueError("Degrees of freedom must be positive")
|
|
800
|
+
if chi_square <= 0:
|
|
801
|
+
return 1.0
|
|
802
|
+
return max(0.0, min(1.0, _upper_regularized_gamma(df / 2.0, chi_square / 2.0)))
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def chi_square_test(observed: List[List[int]]) -> Tuple[float, float, int]:
|
|
806
|
+
"""
|
|
807
|
+
Perform chi-square test of independence.
|
|
808
|
+
|
|
809
|
+
Args:
|
|
810
|
+
observed: Observed frequency table (2D list)
|
|
811
|
+
|
|
812
|
+
Returns:
|
|
813
|
+
Tuple of (chi_square_statistic, p_value, degrees_of_freedom)
|
|
814
|
+
|
|
815
|
+
Example:
|
|
816
|
+
>>> observed = [[10, 20], [15, 25]]
|
|
817
|
+
>>> chi_sq, p_val, df = chi_square_test(observed)
|
|
818
|
+
"""
|
|
819
|
+
if not observed or not observed[0]:
|
|
820
|
+
raise ValueError("Invalid observed frequency table")
|
|
821
|
+
|
|
822
|
+
rows = len(observed)
|
|
823
|
+
cols = len(observed[0])
|
|
824
|
+
|
|
825
|
+
if rows < 2 or cols < 2:
|
|
826
|
+
raise ValueError("Table must be at least 2x2")
|
|
827
|
+
|
|
828
|
+
# A ragged table used to fall through and raise IndexError from deep inside
|
|
829
|
+
# the expected-frequency loop.
|
|
830
|
+
if any(len(row) != cols for row in observed):
|
|
831
|
+
raise ValueError("All rows of the table must have the same length")
|
|
832
|
+
if any(value < 0 for row in observed for value in row):
|
|
833
|
+
raise ValueError("Frequencies cannot be negative")
|
|
834
|
+
|
|
835
|
+
# Calculate row and column totals
|
|
836
|
+
row_totals = [sum(row) for row in observed]
|
|
837
|
+
col_totals = [sum(observed[i][j] for i in range(rows)) for j in range(cols)]
|
|
838
|
+
total = sum(row_totals)
|
|
839
|
+
|
|
840
|
+
if total == 0:
|
|
841
|
+
raise ValueError("Total frequency cannot be zero")
|
|
842
|
+
|
|
843
|
+
# Calculate expected frequencies
|
|
844
|
+
expected = []
|
|
845
|
+
for i in range(rows):
|
|
846
|
+
expected_row = []
|
|
847
|
+
for j in range(cols):
|
|
848
|
+
expected_freq = (row_totals[i] * col_totals[j]) / total
|
|
849
|
+
expected_row.append(expected_freq)
|
|
850
|
+
expected.append(expected_row)
|
|
851
|
+
|
|
852
|
+
# Calculate chi-square statistic
|
|
853
|
+
chi_square = 0
|
|
854
|
+
for i in range(rows):
|
|
855
|
+
for j in range(cols):
|
|
856
|
+
if expected[i][j] != 0:
|
|
857
|
+
chi_square += ((observed[i][j] - expected[i][j]) ** 2) / expected[i][j]
|
|
858
|
+
|
|
859
|
+
# Calculate degrees of freedom
|
|
860
|
+
df = (rows - 1) * (cols - 1)
|
|
861
|
+
|
|
862
|
+
p_value = _chi_square_sf(chi_square, df)
|
|
863
|
+
|
|
864
|
+
return chi_square, p_value, df
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def cramers_v(observed: List[List[int]]) -> float:
|
|
868
|
+
"""
|
|
869
|
+
Calculate Cramer's V association measure.
|
|
870
|
+
|
|
871
|
+
Cramer's V measures the strength of association between categorical variables.
|
|
872
|
+
|
|
873
|
+
Args:
|
|
874
|
+
observed: Observed frequency table (2D list)
|
|
875
|
+
|
|
876
|
+
Returns:
|
|
877
|
+
Cramer's V (0 to 1)
|
|
878
|
+
|
|
879
|
+
Example:
|
|
880
|
+
>>> observed = [[10, 20], [15, 25]]
|
|
881
|
+
>>> v = cramers_v(observed)
|
|
882
|
+
"""
|
|
883
|
+
chi_square, _, df = chi_square_test(observed)
|
|
884
|
+
|
|
885
|
+
rows = len(observed)
|
|
886
|
+
cols = len(observed[0])
|
|
887
|
+
total = sum(sum(row) for row in observed)
|
|
888
|
+
|
|
889
|
+
# Calculate minimum of rows-1 and cols-1
|
|
890
|
+
min_dim = min(rows - 1, cols - 1)
|
|
891
|
+
|
|
892
|
+
if min_dim == 0 or total == 0:
|
|
893
|
+
return 0.0
|
|
894
|
+
|
|
895
|
+
# Cramer's V formula
|
|
896
|
+
v = math.sqrt(chi_square / (total * min_dim))
|
|
897
|
+
|
|
898
|
+
return min(v, 1.0) # Ensure V doesn't exceed 1
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def contingency_coefficient(observed: List[List[int]]) -> float:
|
|
902
|
+
"""
|
|
903
|
+
Calculate contingency coefficient.
|
|
904
|
+
|
|
905
|
+
Contingency coefficient measures association between categorical variables.
|
|
906
|
+
|
|
907
|
+
Args:
|
|
908
|
+
observed: Observed frequency table (2D list)
|
|
909
|
+
|
|
910
|
+
Returns:
|
|
911
|
+
Contingency coefficient (0 to less than 1)
|
|
912
|
+
|
|
913
|
+
Example:
|
|
914
|
+
>>> observed = [[10, 20], [15, 25]]
|
|
915
|
+
>>> c = contingency_coefficient(observed)
|
|
916
|
+
"""
|
|
917
|
+
chi_square, _, _ = chi_square_test(observed)
|
|
918
|
+
total = sum(sum(row) for row in observed)
|
|
919
|
+
|
|
920
|
+
if total == 0:
|
|
921
|
+
return 0.0
|
|
922
|
+
|
|
923
|
+
# Contingency coefficient formula
|
|
924
|
+
c = math.sqrt(chi_square / (chi_square + total))
|
|
925
|
+
|
|
690
926
|
return c
|