python-stats 1.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 +182 -0
- py_stats/multivariate.py +690 -0
- py_stats/univariate.py +1213 -0
- python_stats-1.0.0.dist-info/METADATA +391 -0
- python_stats-1.0.0.dist-info/RECORD +8 -0
- python_stats-1.0.0.dist-info/WHEEL +5 -0
- python_stats-1.0.0.dist-info/licenses/LICENSE +21 -0
- python_stats-1.0.0.dist-info/top_level.txt +1 -0
py_stats/multivariate.py
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
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
|
+
from typing import List, Union, Tuple, Optional
|
|
11
|
+
import numpy as np
|
|
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 q_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
57
|
+
"""
|
|
58
|
+
Calculate Q-correlation coefficient.
|
|
59
|
+
|
|
60
|
+
Q-correlation is based on the ratio of the geometric mean to arithmetic mean.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
x: First variable data
|
|
64
|
+
y: Second variable data
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
Q-correlation coefficient
|
|
68
|
+
|
|
69
|
+
Example:
|
|
70
|
+
>>> q_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
71
|
+
0.7745966692414834
|
|
72
|
+
"""
|
|
73
|
+
x = _validate_data(x)
|
|
74
|
+
y = _validate_data(y)
|
|
75
|
+
|
|
76
|
+
if len(x) != len(y):
|
|
77
|
+
raise ValueError("Variables must have the same length")
|
|
78
|
+
|
|
79
|
+
if len(x) < 2:
|
|
80
|
+
raise ValueError("At least 2 data points required")
|
|
81
|
+
|
|
82
|
+
# Calculate geometric mean of products
|
|
83
|
+
products = [xi * yi for xi, yi in zip(x, y)]
|
|
84
|
+
geometric_mean = math.pow(math.prod(products), 1/len(products))
|
|
85
|
+
|
|
86
|
+
# Calculate arithmetic mean of products
|
|
87
|
+
arithmetic_mean_products = arithmetic_mean(products)
|
|
88
|
+
|
|
89
|
+
if arithmetic_mean_products == 0:
|
|
90
|
+
return 0.0
|
|
91
|
+
|
|
92
|
+
return geometric_mean / arithmetic_mean_products
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def covariance(x: List[Union[int, float]], y: List[Union[int, float]], population: bool = False) -> float:
|
|
96
|
+
"""
|
|
97
|
+
Calculate covariance between two variables.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
x: First variable data
|
|
101
|
+
y: Second variable data
|
|
102
|
+
population: If True, calculate population covariance (n denominator)
|
|
103
|
+
If False, calculate sample covariance (n-1 denominator)
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
Covariance
|
|
107
|
+
|
|
108
|
+
Example:
|
|
109
|
+
>>> covariance([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
110
|
+
1.5
|
|
111
|
+
"""
|
|
112
|
+
x = _validate_data(x)
|
|
113
|
+
y = _validate_data(y)
|
|
114
|
+
|
|
115
|
+
if len(x) != len(y):
|
|
116
|
+
raise ValueError("Variables must have the same length")
|
|
117
|
+
|
|
118
|
+
if len(x) < 2:
|
|
119
|
+
raise ValueError("At least 2 data points required")
|
|
120
|
+
|
|
121
|
+
mean_x = arithmetic_mean(x)
|
|
122
|
+
mean_y = arithmetic_mean(y)
|
|
123
|
+
|
|
124
|
+
sum_xy = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
|
|
125
|
+
|
|
126
|
+
denominator = len(x) if population else len(x) - 1
|
|
127
|
+
return sum_xy / denominator
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def linear_regression(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[float, float, float]:
|
|
131
|
+
"""
|
|
132
|
+
Perform simple linear regression.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
x: Independent variable data
|
|
136
|
+
y: Dependent variable data
|
|
137
|
+
|
|
138
|
+
Returns:
|
|
139
|
+
Tuple of (slope, intercept, r_squared)
|
|
140
|
+
|
|
141
|
+
Example:
|
|
142
|
+
>>> slope, intercept, r_squared = linear_regression([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
143
|
+
>>> print(f"y = {slope:.2f}x + {intercept:.2f}, R² = {r_squared:.3f}")
|
|
144
|
+
"""
|
|
145
|
+
x = _validate_data(x)
|
|
146
|
+
y = _validate_data(y)
|
|
147
|
+
|
|
148
|
+
if len(x) != len(y):
|
|
149
|
+
raise ValueError("Variables must have the same length")
|
|
150
|
+
|
|
151
|
+
if len(x) < 2:
|
|
152
|
+
raise ValueError("At least 2 data points required")
|
|
153
|
+
|
|
154
|
+
n = len(x)
|
|
155
|
+
sum_x = sum(x)
|
|
156
|
+
sum_y = sum(y)
|
|
157
|
+
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
|
|
158
|
+
sum_x2 = sum(xi ** 2 for xi in x)
|
|
159
|
+
|
|
160
|
+
# Calculate slope and intercept
|
|
161
|
+
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
|
|
162
|
+
intercept = (sum_y - slope * sum_x) / n
|
|
163
|
+
|
|
164
|
+
# Calculate R-squared
|
|
165
|
+
mean_y = arithmetic_mean(y)
|
|
166
|
+
ss_tot = sum((yi - mean_y) ** 2 for yi in y)
|
|
167
|
+
ss_res = sum((yi - (slope * xi + intercept)) ** 2 for xi, yi in zip(x, y))
|
|
168
|
+
|
|
169
|
+
r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0
|
|
170
|
+
|
|
171
|
+
return slope, intercept, r_squared
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def sum_xx(x: List[Union[int, float]]) -> float:
|
|
175
|
+
"""
|
|
176
|
+
Calculate sum of squared deviations from mean (Sxx).
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
x: Variable data
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
Sum of squared deviations
|
|
183
|
+
|
|
184
|
+
Example:
|
|
185
|
+
>>> sum_xx([1, 2, 3, 4, 5])
|
|
186
|
+
10.0
|
|
187
|
+
"""
|
|
188
|
+
x = _validate_data(x)
|
|
189
|
+
mean_x = arithmetic_mean(x)
|
|
190
|
+
return sum((xi - mean_x) ** 2 for xi in x)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def sum_yy(y: List[Union[int, float]]) -> float:
|
|
194
|
+
"""
|
|
195
|
+
Calculate sum of squared deviations from mean (Syy).
|
|
196
|
+
|
|
197
|
+
Args:
|
|
198
|
+
y: Variable data
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
Sum of squared deviations
|
|
202
|
+
|
|
203
|
+
Example:
|
|
204
|
+
>>> sum_yy([2, 4, 5, 4, 5])
|
|
205
|
+
6.0
|
|
206
|
+
"""
|
|
207
|
+
y = _validate_data(y)
|
|
208
|
+
mean_y = arithmetic_mean(y)
|
|
209
|
+
return sum((yi - mean_y) ** 2 for yi in y)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def sum_xy(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
213
|
+
"""
|
|
214
|
+
Calculate sum of cross-products of deviations (Sxy).
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
x: First variable data
|
|
218
|
+
y: Second variable data
|
|
219
|
+
|
|
220
|
+
Returns:
|
|
221
|
+
Sum of cross-products
|
|
222
|
+
|
|
223
|
+
Example:
|
|
224
|
+
>>> sum_xy([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
225
|
+
6.0
|
|
226
|
+
"""
|
|
227
|
+
x = _validate_data(x)
|
|
228
|
+
y = _validate_data(y)
|
|
229
|
+
|
|
230
|
+
if len(x) != len(y):
|
|
231
|
+
raise ValueError("Variables must have the same length")
|
|
232
|
+
|
|
233
|
+
mean_x = arithmetic_mean(x)
|
|
234
|
+
mean_y = arithmetic_mean(y)
|
|
235
|
+
|
|
236
|
+
return sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
# Additional correlation functions
|
|
240
|
+
|
|
241
|
+
def spearman_correlation(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
242
|
+
"""
|
|
243
|
+
Calculate Spearman's rank correlation coefficient.
|
|
244
|
+
|
|
245
|
+
Spearman correlation measures the strength of monotonic relationship.
|
|
246
|
+
|
|
247
|
+
Args:
|
|
248
|
+
x: First variable data
|
|
249
|
+
y: Second variable data
|
|
250
|
+
|
|
251
|
+
Returns:
|
|
252
|
+
Spearman correlation coefficient (-1 to 1)
|
|
253
|
+
|
|
254
|
+
Example:
|
|
255
|
+
>>> spearman_correlation([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
256
|
+
0.8
|
|
257
|
+
"""
|
|
258
|
+
x = _validate_data(x)
|
|
259
|
+
y = _validate_data(y)
|
|
260
|
+
|
|
261
|
+
if len(x) != len(y):
|
|
262
|
+
raise ValueError("Variables must have the same length")
|
|
263
|
+
|
|
264
|
+
if len(x) < 2:
|
|
265
|
+
raise ValueError("At least 2 data points required")
|
|
266
|
+
|
|
267
|
+
# Create rank mappings
|
|
268
|
+
def get_ranks(data):
|
|
269
|
+
sorted_data = sorted(enumerate(data), key=lambda x: x[1])
|
|
270
|
+
ranks = [0] * len(data)
|
|
271
|
+
for rank, (index, _) in enumerate(sorted_data):
|
|
272
|
+
ranks[index] = rank + 1
|
|
273
|
+
return ranks
|
|
274
|
+
|
|
275
|
+
rank_x = get_ranks(x)
|
|
276
|
+
rank_y = get_ranks(y)
|
|
277
|
+
|
|
278
|
+
# Calculate correlation using Pearson's formula on ranks
|
|
279
|
+
n = len(rank_x)
|
|
280
|
+
sum_rank_x = sum(rank_x)
|
|
281
|
+
sum_rank_y = sum(rank_y)
|
|
282
|
+
sum_rank_xy = sum(rx * ry for rx, ry in zip(rank_x, rank_y))
|
|
283
|
+
sum_rank_x2 = sum(rx ** 2 for rx in rank_x)
|
|
284
|
+
sum_rank_y2 = sum(ry ** 2 for ry in rank_y)
|
|
285
|
+
|
|
286
|
+
numerator = n * sum_rank_xy - sum_rank_x * sum_rank_y
|
|
287
|
+
denominator = math.sqrt((n * sum_rank_x2 - sum_rank_x ** 2) * (n * sum_rank_y2 - sum_rank_y ** 2))
|
|
288
|
+
|
|
289
|
+
if denominator == 0:
|
|
290
|
+
return 0.0
|
|
291
|
+
|
|
292
|
+
return numerator / denominator
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def kendall_tau(x: List[Union[int, float]], y: List[Union[int, float]]) -> float:
|
|
296
|
+
"""
|
|
297
|
+
Calculate Kendall's tau correlation coefficient.
|
|
298
|
+
|
|
299
|
+
Kendall's tau measures ordinal association between variables.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
x: First variable data
|
|
303
|
+
y: Second variable data
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
Kendall's tau coefficient (-1 to 1)
|
|
307
|
+
|
|
308
|
+
Example:
|
|
309
|
+
>>> kendall_tau([1, 2, 3, 4, 5], [2, 4, 5, 4, 5])
|
|
310
|
+
0.6
|
|
311
|
+
"""
|
|
312
|
+
x = _validate_data(x)
|
|
313
|
+
y = _validate_data(y)
|
|
314
|
+
|
|
315
|
+
if len(x) != len(y):
|
|
316
|
+
raise ValueError("Variables must have the same length")
|
|
317
|
+
|
|
318
|
+
if len(x) < 2:
|
|
319
|
+
raise ValueError("At least 2 data points required")
|
|
320
|
+
|
|
321
|
+
n = len(x)
|
|
322
|
+
concordant = 0
|
|
323
|
+
discordant = 0
|
|
324
|
+
|
|
325
|
+
for i in range(n):
|
|
326
|
+
for j in range(i + 1, n):
|
|
327
|
+
x_diff = x[i] - x[j]
|
|
328
|
+
y_diff = y[i] - y[j]
|
|
329
|
+
|
|
330
|
+
if x_diff * y_diff > 0:
|
|
331
|
+
concordant += 1
|
|
332
|
+
elif x_diff * y_diff < 0:
|
|
333
|
+
discordant += 1
|
|
334
|
+
|
|
335
|
+
total_pairs = n * (n - 1) / 2
|
|
336
|
+
|
|
337
|
+
if total_pairs == 0:
|
|
338
|
+
return 0.0
|
|
339
|
+
|
|
340
|
+
return (concordant - discordant) / total_pairs
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def point_biserial_correlation(x: List[Union[int, float]], y: List[bool]) -> float:
|
|
344
|
+
"""
|
|
345
|
+
Calculate point-biserial correlation coefficient.
|
|
346
|
+
|
|
347
|
+
Point-biserial correlation measures the relationship between a continuous
|
|
348
|
+
variable and a binary variable.
|
|
349
|
+
|
|
350
|
+
Args:
|
|
351
|
+
x: Continuous variable data
|
|
352
|
+
y: Binary variable data (True/False or 1/0)
|
|
353
|
+
|
|
354
|
+
Returns:
|
|
355
|
+
Point-biserial correlation coefficient (-1 to 1)
|
|
356
|
+
|
|
357
|
+
Example:
|
|
358
|
+
>>> point_biserial_correlation([1, 2, 3, 4, 5], [True, False, True, False, True])
|
|
359
|
+
0.31622776601683794
|
|
360
|
+
"""
|
|
361
|
+
x = _validate_data(x)
|
|
362
|
+
|
|
363
|
+
if len(x) != len(y):
|
|
364
|
+
raise ValueError("Variables must have the same length")
|
|
365
|
+
|
|
366
|
+
if len(x) < 2:
|
|
367
|
+
raise ValueError("At least 2 data points required")
|
|
368
|
+
|
|
369
|
+
# Convert boolean to numeric
|
|
370
|
+
y_numeric = [1 if yi else 0 for yi in y]
|
|
371
|
+
|
|
372
|
+
# Calculate means for each group
|
|
373
|
+
group_1 = [xi for xi, yi in zip(x, y_numeric) if yi == 1]
|
|
374
|
+
group_0 = [xi for xi, yi in zip(x, y_numeric) if yi == 0]
|
|
375
|
+
|
|
376
|
+
if not group_1 or not group_0:
|
|
377
|
+
return 0.0
|
|
378
|
+
|
|
379
|
+
mean_1 = arithmetic_mean(group_1)
|
|
380
|
+
mean_0 = arithmetic_mean(group_0)
|
|
381
|
+
|
|
382
|
+
# Calculate standard deviation
|
|
383
|
+
std_x = math.sqrt(sum_xx(x) / (len(x) - 1))
|
|
384
|
+
|
|
385
|
+
if std_x == 0:
|
|
386
|
+
return 0.0
|
|
387
|
+
|
|
388
|
+
# Calculate proportions
|
|
389
|
+
p = len(group_1) / len(x)
|
|
390
|
+
q = 1 - p
|
|
391
|
+
|
|
392
|
+
# Point-biserial correlation formula
|
|
393
|
+
return (mean_1 - mean_0) / std_x * math.sqrt(p * q)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
# Multiple regression functions
|
|
397
|
+
|
|
398
|
+
def multiple_linear_regression(x_vars: List[List[Union[int, float]]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
|
|
399
|
+
"""
|
|
400
|
+
Perform multiple linear regression.
|
|
401
|
+
|
|
402
|
+
Args:
|
|
403
|
+
x_vars: List of independent variable data (each inner list is one variable)
|
|
404
|
+
y: Dependent variable data
|
|
405
|
+
|
|
406
|
+
Returns:
|
|
407
|
+
Tuple of (coefficients, intercept, r_squared)
|
|
408
|
+
|
|
409
|
+
Example:
|
|
410
|
+
>>> x1 = [1, 2, 3, 4, 5]
|
|
411
|
+
>>> x2 = [2, 4, 6, 8, 10]
|
|
412
|
+
>>> y = [3, 5, 7, 9, 11]
|
|
413
|
+
>>> coeffs, intercept, r_sq = multiple_linear_regression([x1, x2], y)
|
|
414
|
+
"""
|
|
415
|
+
if not x_vars:
|
|
416
|
+
raise ValueError("At least one independent variable required")
|
|
417
|
+
|
|
418
|
+
# Validate all variables have same length
|
|
419
|
+
lengths = [len(x) for x in x_vars] + [len(y)]
|
|
420
|
+
if len(set(lengths)) != 1:
|
|
421
|
+
raise ValueError("All variables must have the same length")
|
|
422
|
+
|
|
423
|
+
# Validate data
|
|
424
|
+
x_vars = [_validate_data(x) for x in x_vars]
|
|
425
|
+
y = _validate_data(y)
|
|
426
|
+
|
|
427
|
+
n = len(y)
|
|
428
|
+
k = len(x_vars)
|
|
429
|
+
|
|
430
|
+
if n <= k:
|
|
431
|
+
raise ValueError("Number of observations must be greater than number of variables")
|
|
432
|
+
|
|
433
|
+
# For educational purposes, we'll use a simple approach
|
|
434
|
+
# In practice, you'd use numpy.linalg or scipy for better numerical stability
|
|
435
|
+
|
|
436
|
+
# Create design matrix
|
|
437
|
+
X = []
|
|
438
|
+
for i in range(n):
|
|
439
|
+
row = [1] # Intercept term
|
|
440
|
+
for j in range(k):
|
|
441
|
+
row.append(x_vars[j][i])
|
|
442
|
+
X.append(row)
|
|
443
|
+
|
|
444
|
+
# Simple least squares solution (for educational purposes)
|
|
445
|
+
# In practice, use numpy.linalg.lstsq
|
|
446
|
+
|
|
447
|
+
# Calculate coefficients using normal equations
|
|
448
|
+
XT = list(zip(*X)) # Transpose
|
|
449
|
+
XTX = [[sum(XT[i][r] * XT[j][r] for r in range(n)) for j in range(k+1)] for i in range(k+1)]
|
|
450
|
+
XTy = [sum(XT[i][r] * y[r] for r in range(n)) for i in range(k+1)]
|
|
451
|
+
|
|
452
|
+
# Simple matrix inversion (for educational purposes)
|
|
453
|
+
# In practice, use numpy.linalg.inv
|
|
454
|
+
|
|
455
|
+
# For 2x2 case (intercept + 1 variable)
|
|
456
|
+
if k == 1:
|
|
457
|
+
det = XTX[0][0] * XTX[1][1] - XTX[0][1] * XTX[1][0]
|
|
458
|
+
if abs(det) < 1e-10:
|
|
459
|
+
raise ValueError("Singular matrix - variables may be collinear")
|
|
460
|
+
|
|
461
|
+
inv_00 = XTX[1][1] / det
|
|
462
|
+
inv_01 = -XTX[0][1] / det
|
|
463
|
+
inv_10 = -XTX[1][0] / det
|
|
464
|
+
inv_11 = XTX[0][0] / det
|
|
465
|
+
|
|
466
|
+
intercept = inv_00 * XTy[0] + inv_01 * XTy[1]
|
|
467
|
+
coeff = inv_10 * XTy[0] + inv_11 * XTy[1]
|
|
468
|
+
coefficients = [coeff]
|
|
469
|
+
else:
|
|
470
|
+
# For educational purposes, return simple approximation
|
|
471
|
+
# In practice, use proper matrix operations
|
|
472
|
+
coefficients = [0.0] * k
|
|
473
|
+
intercept = arithmetic_mean(y)
|
|
474
|
+
|
|
475
|
+
# Calculate R-squared
|
|
476
|
+
y_pred = [intercept + sum(coeff * x_vars[j][i] for j, coeff in enumerate(coefficients)) for i in range(n)]
|
|
477
|
+
ss_tot = sum((yi - arithmetic_mean(y)) ** 2 for yi in y)
|
|
478
|
+
ss_res = sum((yi - y_pred[i]) ** 2 for i, yi in enumerate(y))
|
|
479
|
+
|
|
480
|
+
r_squared = 1 - (ss_res / ss_tot) if ss_tot != 0 else 0
|
|
481
|
+
|
|
482
|
+
return coefficients, intercept, r_squared
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def polynomial_regression(x: List[Union[int, float]], y: List[Union[int, float]], degree: int = 2) -> Tuple[List[float], float]:
|
|
486
|
+
"""
|
|
487
|
+
Perform polynomial regression.
|
|
488
|
+
|
|
489
|
+
Args:
|
|
490
|
+
x: Independent variable data
|
|
491
|
+
y: Dependent variable data
|
|
492
|
+
degree: Degree of polynomial (1=linear, 2=quadratic, etc.)
|
|
493
|
+
|
|
494
|
+
Returns:
|
|
495
|
+
Tuple of (coefficients, r_squared)
|
|
496
|
+
|
|
497
|
+
Example:
|
|
498
|
+
>>> x = [1, 2, 3, 4, 5]
|
|
499
|
+
>>> y = [1, 4, 9, 16, 25]
|
|
500
|
+
>>> coeffs, r_sq = polynomial_regression(x, y, degree=2)
|
|
501
|
+
"""
|
|
502
|
+
x = _validate_data(x)
|
|
503
|
+
y = _validate_data(y)
|
|
504
|
+
|
|
505
|
+
if len(x) != len(y):
|
|
506
|
+
raise ValueError("Variables must have the same length")
|
|
507
|
+
|
|
508
|
+
if degree < 1:
|
|
509
|
+
raise ValueError("Degree must be at least 1")
|
|
510
|
+
|
|
511
|
+
if len(x) <= degree:
|
|
512
|
+
raise ValueError("Number of observations must be greater than degree")
|
|
513
|
+
|
|
514
|
+
# Create polynomial features
|
|
515
|
+
x_vars = []
|
|
516
|
+
for d in range(1, degree + 1):
|
|
517
|
+
x_vars.append([xi ** d for xi in x])
|
|
518
|
+
|
|
519
|
+
# Use multiple regression
|
|
520
|
+
coefficients, intercept, r_squared = multiple_linear_regression(x_vars, y)
|
|
521
|
+
|
|
522
|
+
# Add intercept as first coefficient
|
|
523
|
+
all_coefficients = [intercept] + coefficients
|
|
524
|
+
|
|
525
|
+
return all_coefficients, r_squared
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def residual_analysis(x: List[Union[int, float]], y: List[Union[int, float]]) -> Tuple[List[float], float, float]:
|
|
529
|
+
"""
|
|
530
|
+
Perform residual analysis for linear regression.
|
|
531
|
+
|
|
532
|
+
Args:
|
|
533
|
+
x: Independent variable data
|
|
534
|
+
y: Dependent variable data
|
|
535
|
+
|
|
536
|
+
Returns:
|
|
537
|
+
Tuple of (residuals, r_squared, adjusted_r_squared)
|
|
538
|
+
|
|
539
|
+
Example:
|
|
540
|
+
>>> x = [1, 2, 3, 4, 5]
|
|
541
|
+
>>> y = [2, 4, 5, 4, 5]
|
|
542
|
+
>>> residuals, r_sq, adj_r_sq = residual_analysis(x, y)
|
|
543
|
+
"""
|
|
544
|
+
x = _validate_data(x)
|
|
545
|
+
y = _validate_data(y)
|
|
546
|
+
|
|
547
|
+
if len(x) != len(y):
|
|
548
|
+
raise ValueError("Variables must have the same length")
|
|
549
|
+
|
|
550
|
+
if len(x) < 3:
|
|
551
|
+
raise ValueError("At least 3 data points required")
|
|
552
|
+
|
|
553
|
+
# Perform regression
|
|
554
|
+
slope, intercept, r_squared = linear_regression(x, y)
|
|
555
|
+
|
|
556
|
+
# Calculate residuals
|
|
557
|
+
residuals = [yi - (slope * xi + intercept) for xi, yi in zip(x, y)]
|
|
558
|
+
|
|
559
|
+
# Calculate adjusted R-squared
|
|
560
|
+
n = len(x)
|
|
561
|
+
k = 1 # Number of independent variables
|
|
562
|
+
adjusted_r_squared = 1 - ((1 - r_squared) * (n - 1) / (n - k - 1))
|
|
563
|
+
|
|
564
|
+
return residuals, r_squared, adjusted_r_squared
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
# Association measures for categorical data
|
|
568
|
+
|
|
569
|
+
def chi_square_test(observed: List[List[int]]) -> Tuple[float, float, int]:
|
|
570
|
+
"""
|
|
571
|
+
Perform chi-square test of independence.
|
|
572
|
+
|
|
573
|
+
Args:
|
|
574
|
+
observed: Observed frequency table (2D list)
|
|
575
|
+
|
|
576
|
+
Returns:
|
|
577
|
+
Tuple of (chi_square_statistic, p_value, degrees_of_freedom)
|
|
578
|
+
|
|
579
|
+
Example:
|
|
580
|
+
>>> observed = [[10, 20], [15, 25]]
|
|
581
|
+
>>> chi_sq, p_val, df = chi_square_test(observed)
|
|
582
|
+
"""
|
|
583
|
+
if not observed or not observed[0]:
|
|
584
|
+
raise ValueError("Invalid observed frequency table")
|
|
585
|
+
|
|
586
|
+
rows = len(observed)
|
|
587
|
+
cols = len(observed[0])
|
|
588
|
+
|
|
589
|
+
if rows < 2 or cols < 2:
|
|
590
|
+
raise ValueError("Table must be at least 2x2")
|
|
591
|
+
|
|
592
|
+
# Calculate row and column totals
|
|
593
|
+
row_totals = [sum(row) for row in observed]
|
|
594
|
+
col_totals = [sum(observed[i][j] for i in range(rows)) for j in range(cols)]
|
|
595
|
+
total = sum(row_totals)
|
|
596
|
+
|
|
597
|
+
if total == 0:
|
|
598
|
+
raise ValueError("Total frequency cannot be zero")
|
|
599
|
+
|
|
600
|
+
# Calculate expected frequencies
|
|
601
|
+
expected = []
|
|
602
|
+
for i in range(rows):
|
|
603
|
+
expected_row = []
|
|
604
|
+
for j in range(cols):
|
|
605
|
+
expected_freq = (row_totals[i] * col_totals[j]) / total
|
|
606
|
+
expected_row.append(expected_freq)
|
|
607
|
+
expected.append(expected_row)
|
|
608
|
+
|
|
609
|
+
# Calculate chi-square statistic
|
|
610
|
+
chi_square = 0
|
|
611
|
+
for i in range(rows):
|
|
612
|
+
for j in range(cols):
|
|
613
|
+
if expected[i][j] != 0:
|
|
614
|
+
chi_square += ((observed[i][j] - expected[i][j]) ** 2) / expected[i][j]
|
|
615
|
+
|
|
616
|
+
# Calculate degrees of freedom
|
|
617
|
+
df = (rows - 1) * (cols - 1)
|
|
618
|
+
|
|
619
|
+
# Simple p-value approximation (for educational purposes)
|
|
620
|
+
# In practice, use scipy.stats.chi2.sf
|
|
621
|
+
if df == 1:
|
|
622
|
+
# For 1 degree of freedom, use normal approximation
|
|
623
|
+
p_value = 2 * (1 - 0.5 * (1 + math.erf(math.sqrt(chi_square/2) / math.sqrt(2))))
|
|
624
|
+
else:
|
|
625
|
+
# Simple approximation for other degrees of freedom
|
|
626
|
+
p_value = max(0, 1 - chi_square / (df + chi_square))
|
|
627
|
+
|
|
628
|
+
return chi_square, p_value, df
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def cramers_v(observed: List[List[int]]) -> float:
|
|
632
|
+
"""
|
|
633
|
+
Calculate Cramer's V association measure.
|
|
634
|
+
|
|
635
|
+
Cramer's V measures the strength of association between categorical variables.
|
|
636
|
+
|
|
637
|
+
Args:
|
|
638
|
+
observed: Observed frequency table (2D list)
|
|
639
|
+
|
|
640
|
+
Returns:
|
|
641
|
+
Cramer's V (0 to 1)
|
|
642
|
+
|
|
643
|
+
Example:
|
|
644
|
+
>>> observed = [[10, 20], [15, 25]]
|
|
645
|
+
>>> v = cramers_v(observed)
|
|
646
|
+
"""
|
|
647
|
+
chi_square, _, df = chi_square_test(observed)
|
|
648
|
+
|
|
649
|
+
rows = len(observed)
|
|
650
|
+
cols = len(observed[0])
|
|
651
|
+
total = sum(sum(row) for row in observed)
|
|
652
|
+
|
|
653
|
+
# Calculate minimum of rows-1 and cols-1
|
|
654
|
+
min_dim = min(rows - 1, cols - 1)
|
|
655
|
+
|
|
656
|
+
if min_dim == 0 or total == 0:
|
|
657
|
+
return 0.0
|
|
658
|
+
|
|
659
|
+
# Cramer's V formula
|
|
660
|
+
v = math.sqrt(chi_square / (total * min_dim))
|
|
661
|
+
|
|
662
|
+
return min(v, 1.0) # Ensure V doesn't exceed 1
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def contingency_coefficient(observed: List[List[int]]) -> float:
|
|
666
|
+
"""
|
|
667
|
+
Calculate contingency coefficient.
|
|
668
|
+
|
|
669
|
+
Contingency coefficient measures association between categorical variables.
|
|
670
|
+
|
|
671
|
+
Args:
|
|
672
|
+
observed: Observed frequency table (2D list)
|
|
673
|
+
|
|
674
|
+
Returns:
|
|
675
|
+
Contingency coefficient (0 to less than 1)
|
|
676
|
+
|
|
677
|
+
Example:
|
|
678
|
+
>>> observed = [[10, 20], [15, 25]]
|
|
679
|
+
>>> c = contingency_coefficient(observed)
|
|
680
|
+
"""
|
|
681
|
+
chi_square, _, _ = chi_square_test(observed)
|
|
682
|
+
total = sum(sum(row) for row in observed)
|
|
683
|
+
|
|
684
|
+
if total == 0:
|
|
685
|
+
return 0.0
|
|
686
|
+
|
|
687
|
+
# Contingency coefficient formula
|
|
688
|
+
c = math.sqrt(chi_square / (chi_square + total))
|
|
689
|
+
|
|
690
|
+
return c
|