API Reference
This is the code documentation for the humlpy package, which implements the
methodology from:
Göbler, K., Drton, M., Mukherjee, S. and Miloschewski, A. (2024). High-dimensional undirected graphical models for arbitrary mixed data. Electronic Journal of Statistics, 18(1), 2339–2404. https://doi.org/10.1214/24-EJS2254
Main Classes
Estimate a sample correlation matrix for mixed continuous/ordinal data.
Pairwise correlations are estimated as follows:
- continuous - continuous: Spearman sin-transform
:math:
\hat{\sigma} = 2 \sin(\pi/6 \cdot \hat{\rho}_S). - continuous - ordinal: ad-hoc polyserial correlation via
:class:
~humlpy.correlation.PolyserialCorrelation. - ordinal - ordinal: maximum-likelihood polychoric correlation via
:class:
~humlpy.correlation.PolychoricCorrelation.
After calling :meth:fit, the estimated matrix is available as
:attr:correlation_matrix_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_levels_threshold
|
int
|
Columns with strictly fewer unique values are treated as ordinal. Defaults to 20. |
20
|
Example::
sc = SampleCorrelation().fit(X)
print(sc.correlation_matrix_)
Source code in humlpy/estimation.py
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 | |
__init__(n_levels_threshold=20)
Construct a SampleCorrelation estimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_levels_threshold
|
int
|
Unique-value threshold for ordinal detection. Defaults to 20. |
20
|
Source code in humlpy/estimation.py
fit(x)
Estimate the correlation matrix from x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
DataFrame | NDArray[Any]
|
Data matrix of shape |
required |
Returns:
| Type | Description |
|---|---|
SampleCorrelation
|
self -- enables method chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If x has fewer than 2 columns. |
Source code in humlpy/estimation.py
Sparse Gaussian graphical model for mixed continuous/ordinal data.
Estimates a precision matrix and the associated :class:~humlpy.graphs.UGRAPH
by:
- Computing the sample correlation matrix via :class:
SampleCorrelation. - Projecting to the positive-definite cone if necessary.
- Computing the full graphical lasso regularisation path.
- Selecting the model with the smallest eBIC via :func:
omega_select. - Re-fitting graphical lasso at the selected alpha for a clean final solution.
The overall design mirrors sklearn.covariance.GraphicalLassoCV but
replaces cross-validation with eBIC-based selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_lambdas
|
int
|
Number of regularisation steps in the path. Defaults to 50. |
50
|
ebic_gamma
|
float
|
eBIC hyper-parameter :math: |
0.1
|
n_levels_threshold
|
int
|
Unique-value threshold for declaring a column ordinal. Defaults to 20. |
20
|
Attributes set after :meth:fit:
precision_matrix_ (pd.DataFrame): Partial correlation matrix derived
from the estimated precision (diagonal = 1).
correlation_matrix_ (pd.DataFrame): Sample correlation matrix used as
input to graphical lasso.
graph_ (UGRAPH): Undirected graph whose edges correspond to non-zero
off-diagonal entries in precision_matrix_.
alpha_ (float): Selected regularisation parameter.
ebic_scores_ (np.ndarray): eBIC values for each point on the path.
singular_ (bool): Whether positive-definite projection was needed.
feature_names_ (list[str]): Variable names inferred from the input.
Example::
mgl = MixedGraphicalLasso(ebic_gamma=0.1)
mgl.fit(X)
print(mgl.graph_.edges)
print(mgl.precision_matrix_)
Source code in humlpy/estimation.py
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 | |
n_edges_
property
Number of edges in the estimated graph.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If :meth: |
__init__(n_lambdas=50, ebic_gamma=0.1, n_levels_threshold=20)
Construct a MixedGraphicalLasso estimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_lambdas
|
int
|
Length of the regularisation path. Defaults to 50. |
50
|
ebic_gamma
|
float
|
eBIC dimensionality penalty weight in [0, 1]. Defaults to 0.1. |
0.1
|
n_levels_threshold
|
int
|
Ordinal detection threshold. Defaults to 20. |
20
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If ebic_gamma is not in [0, 1]. |
Source code in humlpy/estimation.py
fit(x)
Fit the model to x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
DataFrame | NDArray[Any]
|
Data matrix of shape |
required |
Returns:
| Type | Description |
|---|---|
MixedGraphicalLasso
|
self -- enables method chaining. |
Source code in humlpy/estimation.py
Model Selection
Select the best precision matrix from a glasso path using eBIC.
The extended BIC criterion is:
.. math::
\mathrm{eBIC}(\Omega) =
-2 \ell(\Omega \mid E)
+ |E| \log n
+ 4 \gamma |E| \log d
where :math:|E| is the number of edges, :math:n the sample size,
:math:d the number of variables, and :math:\gamma \in [0,1] an
additional penalty for high-dimensional settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
precision_path
|
list[NDArray[Any]]
|
List of precision matrices along the regularisation path. |
required |
lambda_path
|
NDArray[Any]
|
Corresponding array of |
required |
n
|
int
|
Sample size. |
required |
s
|
NDArray[Any]
|
Sample correlation/covariance matrix used for estimation. |
required |
gamma
|
float
|
eBIC hyper-parameter. |
0.1
|
Returns:
| Type | Description |
|---|---|
NDArray[Any]
|
Tuple |
float
|
selected_precision is the raw precision matrix for the chosen model, |
NDArray[Any]
|
selected_alpha is the corresponding regularisation value, and |
tuple[NDArray[Any], float, NDArray[Any]]
|
ebic_scores is the full eBIC array along the path. |
References
Foygel, Rina and Drton, Mathias. (2010). Extended Bayesian Information Criteria for Gaussian Graphical Models. Advances in Neural Information Processing Systems, Volume 23, pp. 604-612.
Source code in humlpy/estimation.py
Graph Classes
Bases: GRAPH
Class for dealing with undirected graph i.e. graphs that only contain undirected edges.
Source code in humlpy/graphs.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 | |
adjacency_matrix
property
Returns adjacency matrix.
The i,jth entry being one indicates that there is an undirected edge between i and j. A zero indicates that there is no edge. The matrix is symmetric.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: adjacency matrix |
causal_order
property
Causal order is None.
This is because undirected graphs do not imply a causal order.
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
None |
edges
property
Gives all edges in current UGRAPH.
Returns:
| Type | Description |
|---|---|
list[tuple[str, str]]
|
list[tuple[str,str]]: List of edges. |
nodes
property
Get all nodes in current UGRAPH.
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
list of nodes. |
num_edges
property
Number of edges in current UGRAPH.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of edges |
num_nodes
property
Number of nodes in current UGRAPH.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of nodes |
__init__(nodes=None, edges=None)
UGRAPH constructor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
list[str] | None
|
Nodes. Defaults to None. |
None
|
edges
|
list[tuple[str, str]] | None
|
Edges. Defaults to None. |
None
|
Source code in humlpy/graphs.py
copy()
from_pandas_adjacency(pd_amat)
classmethod
Build UGRAPH from a Pandas adjacency matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pd_amat
|
DataFrame
|
input adjacency matrix. |
required |
Returns:
| Type | Description |
|---|---|
UGRAPH
|
UGRAPH |
Source code in humlpy/graphs.py
is_adjacent(i, j)
Return True if the graph contains an undirected edge between i and j.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
i
|
str
|
node i. |
required |
j
|
str
|
node j. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if i - j |
Source code in humlpy/graphs.py
is_clique(potential_clique)
Check every pair of nodes in potential_clique is adjacent.
neighbors(node)
Gives all neighbors of node node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
str
|
node in current UGRAPH. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
set |
set[str]
|
set of neighbors. |
Source code in humlpy/graphs.py
remove_edge(i, j)
Removes edge in question.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
i
|
str
|
first node |
required |
j
|
str
|
second node |
required |
Raises:
| Type | Description |
|---|---|
AssertionError
|
if edge does not exist |
Source code in humlpy/graphs.py
remove_node(node)
Remove a node from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
str
|
node to remove |
required |
Source code in humlpy/graphs.py
show()
to_networkx()
Convert to networkx graph.
Returns:
| Type | Description |
|---|---|
Graph
|
nx.Graph: Undirected networkx graph. |
Correlation Functions
Bases: CorrelationMeasure
Maximum-likelihood polychoric correlation between two ordinal variables.
Both variables are treated as discretised versions of latent normal variates. The MLE of their latent correlation is found by one of two solvers:
-
"brent"(default) — Direct maximisation of $\ell(\rho) = \sum_{ij} n_{ij}\log\pi_{ij}$ via :func:scipy.optimize.minimize_scalarwith Brent's bounded method. Each function evaluation requires only :func:_pi_rs(no derivatives). Converges super-linearly and is consistently faster once the number of ordinal categories exceeds ~3, because the per-evaluation cost grows as $O(k_x \times k_y)$ CDF calls rather than CDF + PDF calls. -
"newton"— Fisher scoring. Uses the score $S(\rho) = \sum_{ij} n_{ij}\,(\pi_{ij}'/\pi_{ij})$ and the empirical Fisher information $\hat{I}(\rho) = \sum_{ij} n_{ij}\,(\pi_{ij}'/\pi_{ij})^2$ to iterate $\rho \leftarrow \rho + S/\hat{I}$ until convergence. Converges quadratically near the MLE and can be ~2× faster than"brent"for binary variables ($k_x = k_y = 2$), but becomes progressively slower as the category count grows because each iteration requires both :func:_pi_rsand :func:_pi_rs_derivativeper cell. Consider this solver when both variables are binary or ternary.
Solver selection guide (rule of thumb from benchmarks):
+-------------------+------------------+
| Category count | Recommended |
+===================+==================+
| binary (2 × 2) | "newton" |
+-------------------+------------------+
| ternary (3 × 3) | either |
+-------------------+------------------+
| 4+ categories | "brent" |
+-------------------+------------------+
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_cor
|
float
|
Absolute upper bound for the estimated correlation. Defaults to 0.9999. |
0.9999
|
solver
|
Literal['newton', 'brent']
|
Optimisation strategy, |
'brent'
|
max_iter
|
int
|
Maximum Fisher-scoring iterations (ignored for |
100
|
tol
|
float
|
Convergence tolerance on the absolute score value and step size
(ignored for |
1e-10
|
Example::
rho = PolychoricCorrelation().fit(x_ord, y_ord).correlation
rho = PolychoricCorrelation(solver="newton").fit(x_ord, y_ord).correlation
Source code in humlpy/correlation.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | |
__init__(max_cor=0.9999, solver='brent', max_iter=100, tol=1e-10)
Initialise the polychoric correlation estimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_cor
|
float
|
Absolute upper bound for the estimated correlation. Defaults to 0.9999. |
0.9999
|
solver
|
Literal['newton', 'brent']
|
Optimisation strategy. |
'brent'
|
max_iter
|
int
|
Maximum Fisher-scoring iterations; ignored when
|
100
|
tol
|
float
|
Convergence tolerance on the absolute score value and step
size; ignored when |
1e-10
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If solver is not |
Source code in humlpy/correlation.py
fit(x, y)
Fit the polychoric correlation model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
First ordinal variable (integer-valued or small number of distinct float levels). |
required |
y
|
ndarray
|
Second ordinal variable. |
required |
Returns:
| Type | Description |
|---|---|
PolychoricCorrelation
|
self |
Raises:
| Type | Description |
|---|---|
ValueError
|
On invalid or incompatible inputs. |
RuntimeError
|
If the solver cannot converge. |
Source code in humlpy/correlation.py
Bases: CorrelationMeasure
Ad-hoc polyserial correlation between one continuous and one ordinal variable.
The estimator applies the nonparanormal (rank-based) transformation to the continuous variable and uses a closed-form correction factor derived from the ordinal thresholds to approximate the underlying latent correlation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_cor
|
float
|
Absolute upper bound for the estimated correlation. Defaults to 0.9999. |
0.9999
|
n_levels_threshold
|
int
|
Variables with fewer unique values than this threshold are treated as ordinal. Defaults to 20. |
20
|
Example::
rho = PolyserialCorrelation().fit(x_cont, y_ord).correlation
Source code in humlpy/correlation.py
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 | |
__init__(max_cor=0.9999, n_levels_threshold=20)
Inits polyserial correlation class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_cor
|
float
|
Defaults to 0.9999. |
0.9999
|
n_levels_threshold
|
int
|
Until what level set to treat a variable as ordinal. Defaults to 20. |
20
|
Raises:
| Type | Description |
|---|---|
ValueError
|
description |
Source code in humlpy/correlation.py
fit(x, y)
Fit the polyserial correlation model.
The method automatically identifies which argument is the continuous variable and which is the ordinal variable based on the number of unique values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
One variable (continuous or ordinal). |
required |
y
|
ndarray
|
The other variable (ordinal or continuous). |
required |
Returns:
| Type | Description |
|---|---|
PolyserialCorrelation
|
self |
Raises:
| Type | Description |
|---|---|
ValueError
|
On invalid inputs or if both variables appear to be
continuous (use a Spearman/NPP estimator instead) or if both
appear to be ordinal (use :class: |
Source code in humlpy/correlation.py
Spearman's rank correlation coefficient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
First numeric array. |
required |
y
|
ndarray
|
Second numeric array (same length as x). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Spearman's ρ in [−1, 1]. |
Source code in humlpy/correlation.py
Winsorized nonparanormal transformation.
Implements the estimator from Liu, Lafferty & Wasserman (2009): each observation is mapped to its normal score and the result is scaled to unit variance. Extreme ranks are Winsorized to avoid ±∞.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
A 1-D numeric array. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Transformed array of the same length, scaled to unit variance. |
Source code in humlpy/correlation.py
Nonparanormal product-moment correlation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cont
|
ndarray
|
Continuous numeric array. |
required |
disc
|
ndarray
|
Discrete/ordinal array. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Correlation coefficient in [−1, 1]. |
Source code in humlpy/correlation.py
Convenience dispatcher for mixed-type correlation estimation.
Selects the appropriate estimator based on the number of unique values:
- Both continuous → nonparanormal Spearman sin-transformation.
- Both ordinal → :class:
PolychoricCorrelation. - Mixed → :class:
PolyserialCorrelation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
First array (discrete or continuous). |
required |
y
|
ndarray
|
Second array (discrete or continuous). |
required |
max_cor
|
float
|
Maximum allowed absolute correlation; clips to ±max_cor. |
0.9999
|
n_levels_threshold
|
int
|
Unique-value count below which a variable is treated as ordinal. |
20
|
verbose
|
bool
|
Emit an :mod: |
False
|
Returns:
| Type | Description |
|---|---|
float
|
Correlation estimate in [−1, 1]. |
Source code in humlpy/correlation.py
Legacy Functions
Estimate a mixed graphical model (backward-compatible wrapper).
.. deprecated::
Prefer :class:MixedGraphicalLasso directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame | NDArray[Any]
|
Data matrix |
required |
verbose
|
bool
|
Emit logging warnings. |
True
|
n_lambdas
|
int
|
Length of the regularisation path. |
50
|
param
|
float
|
eBIC dimensionality penalty weight (gamma). |
0.1
|
feature_names
|
list[str] | None
|
Override column names. |
None
|
n_levels_threshold
|
int
|
Ordinal detection threshold. |
20
|
Returns:
| Type | Description |
|---|---|
MixedGraphResult
|
class: |
Source code in humlpy/estimation.py
Estimate a mixed graphical model (backward-compatible wrapper).
.. deprecated::
Prefer :class:MixedGraphicalLasso directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame | NDArray[Any]
|
Data matrix |
required |
verbose
|
bool
|
Emit logging warnings. |
True
|
n_lambdas
|
int
|
Length of the regularisation path. |
50
|
param
|
float
|
eBIC dimensionality penalty weight (gamma). |
0.1
|
feature_names
|
list[str] | None
|
Override column names. |
None
|
n_levels_threshold
|
int
|
Ordinal detection threshold. |
20
|
Returns:
| Type | Description |
|---|---|
MixedGraphResult
|
class: |
Source code in humlpy/estimation.py
Legacy result container kept for backward compatibility.
New code should use :class:MixedGraphicalLasso directly and access
results via its attributes.
Attributes:
| Name | Type | Description |
|---|---|---|
precision_matrix |
NDArray[Any]
|
Estimated partial correlation matrix as a numpy array. |
adjacency_matrix |
NDArray[bool_]
|
Boolean adjacency matrix (True = edge present). |
correlation_matrix |
NDArray[Any]
|
Sample correlation matrix fed to graphical lasso. |
n_edges |
int
|
Number of edges in the estimated graph. |
max_degree |
int
|
Largest node degree. |
initial_mat_singular |
bool
|
Whether the correlation matrix needed PD projection. |
feature_names |
list[str] | None
|
Variable names (None if not provided). |
Source code in humlpy/estimation.py
Calculate number of edges given a precision matrix.
Thin wrapper around :func:_edgenumber kept for backward compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
precision
|
NDArray[Any]
|
Square precision or partial-correlation matrix. |
required |
cut
|
float
|
Entries with |value| <= cut are treated as zero. |
0.0
|
Returns:
| Type | Description |
|---|---|
int
|
Number of edges (lower-triangular non-zeros). |