stats
cov_to_cor(covariance_matrix)
¶
Convert a covariance matrix to a correlation matrix.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
covariance_matrix |
ndarray
|
A square matrix of covariance values. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: A corresponding square matrix of correlation coefficients. |
Examples:
>>> from spotpython.utils.stats import cov_to_cor
>>> import numpy as np
>>> cov_matrix = np.array([[1, 0.8], [0.8, 1]])
>>> cov_to_cor(cov_matrix)
array([[1. , 0.8],
[0.8, 1. ]])
Source code in spotpython/utils/stats.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
fit_all_lm(basic, xlist, data, remove_na=True)
¶
Fit a linear regression model for all possible combinations of independent variables.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
basic |
str
|
The basic model formula. |
required |
xlist |
list
|
A list of independent variables. |
required |
data |
DataFrame
|
The data frame containing the variables. |
required |
remove_na |
bool
|
Whether to remove missing values from the data frame. |
True
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict
|
A dictionary containing the estimated coefficients, confidence intervals, p-values, AIC values, sample size, and the basic model formula. |
Examples:
>>> from spotpython.utils.stats import fit_all_lm
>>> import pandas as pd
>>> data = pd.DataFrame({
>>> 'y': [1, 2, 3],
>>> 'x1': [4, 5, 6],
>>> 'x2': [7, 8, 9]
>>> })
>>> fit_all_lm("y ~ x1", ["x2"], data)
{'estimate': variables estimate conf_low conf_high p aic n
0 basic 1.000000 1.000000 1.000000 0.0 0.000000 3
1 x2 1.000000 1.000000 1.000000 0.0 0.000000 3}
Source code in spotpython/utils/stats.py
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 |
|
get_all_vars_from_formula(formula)
¶
Utility function to extract variables from a formula.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
formula |
str
|
A formula. |
required |
Returns:
Name | Type | Description |
---|---|---|
list |
list
|
A list of variables. |
Examples:
>>> from spotpython.utils.stats import get_all_vars_from_formula
get_all_vars_from_formula("y ~ x1 + x2")
['y', 'x1', 'x2']
get_all_vars_from_formula("y ~ ")
['y']
Source code in spotpython/utils/stats.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
|
partial_correlation(x, method='pearson')
¶
Calculate the partial correlation matrix for a given data set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
DataFrame or ndarray
|
The data matrix with variables as columns. |
required |
method |
str
|
Correlation method, one of ‘pearson’, ‘kendall’, or ‘spearman’. |
'pearson'
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict
|
A dictionary containing the partial correlation estimates, p-values, statistics, sample size (n), number of given parameters (gp), and method used. |
Raises:
Type | Description |
---|---|
ValueError
|
If input is not a matrix-like structure or not numeric. |
References
- Kim, S. ppcor: An R package for a fast calculation to semi-partial correlation coefficients. Commun Stat Appl Methods 22, 6 (Nov 2015), 665–674.
Examples:
>>> from spotpython.utils.stats import partial_correlation
>>> import numpy as np
>>> import pandas as pd
>>> data = pd.DataFrame({
>>> 'A': [1, 2, 3],
>>> 'B': [4, 5, 6],
>>> 'C': [7, 8, 9]
>>> })
>>> partial_correlation(data, method='pearson')
{'estimate': array([[ 1. , -1. , 1. ],
[-1. , 1. , -1. ],
[ 1. , -1. , 1. ]]),
'p_value': array([[0. , 0. , 0. ],
[0. , 0. , 0. ],
[0. , 0. , 0. ]]), ...
}
Source code in spotpython/utils/stats.py
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 |
|
partial_correlation_test(x, y, z, method='pearson')
¶
The partial correlation coefficient between x and y given z. x and y should be arrays (vectors) of the same length, and z should be a data frame (matrix).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
array - like
|
The first variable as a 1-dimensional array or list. |
required |
y |
array - like
|
The second variable as a 1-dimensional array or list. |
required |
z |
DataFrame
|
A data frame containing other conditional variables. |
required |
method |
str
|
Correlation method, one of ‘pearson’, ‘kendall’, or ‘spearman’. |
'pearson'
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict
|
A dictionary with the partial correlation estimate, p-value, statistic, sample size (n), number of given parameters (gp), and method used. |
References
- Kim, S. ppcor: An R package for a fast calculation to semi-partial correlation coefficients. Commun Stat Appl Methods 22, 6 (Nov 2015), 665–674.
Examples:
>>> from spotpython.utils.stats import pairwise_partial_correlation
>>> import pandas as pd
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> z = pd.DataFrame({'C': [7, 8, 9]})
>>> pairwise_partial_correlation(x, y, z)
{'estimate': -1.0, 'p_value': 0.0, 'statistic': -inf, 'n': 3, 'gp': 1, 'method': 'pearson'}
Source code in spotpython/utils/stats.py
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 |
|
plot_coeff_vs_pvals(data, xlabels=None, xlim=(0, 1), xlab='p-value', ylim=None, ylab=None, xscale_log=True, yscale_log=False, title=None, show=True)
¶
Plot the coefficient estimates from fit_all_lm against the corresponding p-values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
dict
|
A dictionary containing the estimated coefficients, p-values, and other information. Generated by the fit_all_lm function. |
required |
xlabels |
list
|
A list of x-axis labels. |
None
|
xlim |
tuple
|
A tuple of the x-axis limits. |
(0, 1)
|
xlab |
str
|
The x-axis label. |
'p-value'
|
ylim |
tuple
|
A tuple of the y-axis limits. |
None
|
ylab |
str
|
The y-axis label. |
None
|
xscale_log |
bool
|
Whether to use a log scale on the x-axis. |
True
|
yscale_log |
bool
|
Whether to use a log scale on the y-axis. |
False
|
title |
str
|
The plot title. |
None
|
show |
bool
|
Whether to display the plot. |
True
|
Returns:
Type | Description |
---|---|
None
|
None |
Notes
- Based on the R package ‘allestimates’ by Zhiqiang Wang, see https://cran.r-project.org/package=allestimates
References
Wang, Z. (2007). Two Postestimation Commands for Assessing Confounding Effects in Epidemiological Studies. The Stata Journal, 7(2), 183-196. https://doi.org/10.1177/1536867X0700700203
Examples:
>>> from spotpython.utils.stats import plot_coeff_vs_pvals, fit_all_lm
>>> import pandas as pd
>>> data = pd.DataFrame({
>>> 'y': [1, 2, 3],
>>> 'x1': [4, 5, 6],
>>> 'x2': [7, 8, 9]
>>> })
>>> estimates = fit_all_lm("y ~ x1", ["x2"], data)
>>> plot_coeff_vs_pvals(estimates)
Source code in spotpython/utils/stats.py
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 |
|
plot_coeff_vs_pvals_by_included(data, xlabels=None, xlim=(0, 1), xlab='P value', ylim=None, ylab=None, yscale_log=False, title=None, grid=True, ncol=2, show=True)
¶
Generates a panel of scatter plots with effect estimates of all possible models against p-values. Uses a dictionry generated by the fit_all_lm function. Each plot includes effect estimates from all models including a specific variable.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
dict
|
A dictionary, generated by the fit_all_lm function, containing the following keys: - estimate (pd.DataFrame): A DataFrame containing the estimates. - xlist (list): A list of variables. - fun (str): The function name. - family (str): The family of the model. |
required |
xlabels |
list
|
A list of x-axis labels. |
None
|
xlim |
tuple
|
The x-axis limits. |
(0, 1)
|
xlab |
str
|
The x-axis label. |
'P value'
|
ylim |
tuple
|
The y-axis limits. |
None
|
ylab |
str
|
The y-axis label. |
None
|
yscale_log |
bool
|
Whether to scale y-axis to log10. Default is False. |
False
|
title |
str
|
The title of the plot. |
None
|
grid |
bool
|
Whether to display gridlines. Default is True. |
True
|
ncol |
int
|
Number of columns in the plot grid. Default is 2. |
2
|
Returns:
Type | Description |
---|---|
None
|
None |
Notes
- Based on the R package ‘allestimates’ by Zhiqiang Wang, see https://cran.r-project.org/package=allestimates
References
Wang, Z. (2007). Two Postestimation Commands for Assessing Confounding Effects in Epidemiological Studies. The Stata Journal, 7(2), 183-196. https://doi.org/10.1177/1536867X0700700203
Examples:
data = { “estimate”: pd.DataFrame({ “variables”: [“Crude”, “AL”, “AM”, “AN”, “AO”], “estimate”: [0.5, 0.6, 0.7, 0.8, 0.9], “conf_low”: [0.1, 0.2, 0.3, 0.4, 0.5], “conf_high”: [0.9, 1.0, 1.1, 1.2, 1.3], “p”: [0.01, 0.02, 0.03, 0.04, 0.05], “aic”: [100, 200, 300, 400, 500], “n”: [10, 20, 30, 40, 50] }), “xlist”: [“AL”, “AM”, “AN”, “AO”], “fun”: “all_lm” } plot_coeff_vs_pvals_by_included(data)
Source code in spotpython/utils/stats.py
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 |
|