GLM — Generalized Linear Models

Generalized Linear Model fitting routines.

aurora.models.glm.fit_glm(X, y, *, family='gaussian', link=None, weights=None, offset=None, backend=None, device=None, max_iter=25, tol=1e-8, fit_intercept=True)[source]

Fit a Generalized Linear Model using IRLS.

Parameters:
  • X (array-like) – Design matrix of shape (n_samples, n_features).

  • y (array-like) – Target values of shape (n_samples,).

  • family (str or Family) – Distribution family (‘gaussian’, ‘poisson’, ‘binomial’, ‘gamma’).

  • link (str or LinkFunction, optional) – Link function. If None, uses family default.

  • weights (array-like, optional) – Prior weights (R glm convention): each observation contributes wᵢ times its unit deviance/log-likelihood. For grouped binomial data, pass proportions as y and trial counts as weights.

  • offset (array-like, optional) – Offset term.

  • backend (str, optional) – Computational backend: ‘numpy’, ‘torch’, or ‘jax’. If None, infers from input data type.

  • device (str, optional) – Device for computation (for torch backend): ‘cpu’, ‘cuda’, ‘cuda:0’, etc.

  • max_iter (int) – Maximum number of IRLS iterations.

  • tol (float) – Convergence tolerance.

  • fit_intercept (bool) – Whether to fit an intercept term.

Returns:

Fitted model results.

Return type:

GLMResult

aurora.models.glm.predict_glm(model, design_matrix, *, backend=None, type='response')[source]

Generate predictions from a fitted GLM model.

This is a convenience wrapper around the GLMResult.predict() method, providing a functional interface for predictions.

Parameters:
  • model (GLMResult) – A fitted GLM model result from fit_glm().

  • design_matrix (ArrayLike) – Design matrix for prediction. Shape (n_samples, n_features).

  • backend (str, optional) – Backend to use for computation (‘numpy’, ‘torch’, ‘jax’). If None, uses the backend from the fitted model.

  • type ({'response', 'link'}, default='response') – Type of prediction: - ‘response’: Predictions on the response scale (μ = g⁻¹(Xβ)) - ‘link’: Predictions on the linear predictor scale (η = Xβ)

Returns:

predictions – Predicted values. Shape (n_samples,).

Return type:

ArrayLike

Examples

>>> from aurora.models import fit_glm, predict_glm
>>> from aurora import GaussianFamily
>>>
>>> # Fit a linear model
>>> result = fit_glm(X_train, y_train, family=GaussianFamily())
>>>
>>> # Predict on test data
>>> y_pred = predict_glm(result, X_test)
>>>
>>> # Get linear predictor values
>>> eta = predict_glm(result, X_test, type='link')

See also

fit_glm

Fit a Generalized Linear Model

GLMResult.predict

Instance method for predictions

class aurora.models.glm.GLMResult(coef_, intercept_, family, link, mu_, eta_, deviance_, null_deviance_, aic_, bic_, n_iter_, converged_, log_likelihood_=0.0, dispersion_=1.0, rank_=None, condition_number_=None, theta_=None, _coef_cov=None, _std_errors=None, _p_values=None, _X=None, _y=None, _weights=None, _offset=None, _fit_intercept=True, _intercept_std_error=None, _intercept_p_value=None, _diagnostics_cache=None)[source]

Bases: object

Structured container describing the outcome of a GLM fit.

The Attributes

coef_Array

Fitted coefficients (excluding intercept if present).

intercept_float or optional

Fitted intercept. None when fit_intercept=False.

familyFamily

Distribution family instance.

linkLinkFunction

Link function instance.

mu_Array

Fitted mean values.

eta_Array

Fitted linear predictor values.

deviance_float

Model deviance.

null_deviance_float

Null model deviance (intercept-only model).

log_likelihood_float

Log-likelihood of the fitted model.

aic_float

Akaike Information Criterion.

bic_float

Bayesian Information Criterion.

n_iter_int

Number of IRLS iterations.

converged_bool

Whether fitting converged.

dispersion_float

Estimated dispersion parameter φ̂ = deviance / (n − rank) for families with free dispersion (Gaussian, Gamma, InverseGaussian); exactly 1.0 for Poisson/Binomial. Scales the coefficient covariance matrix (R summary.glm convention).

rank_int, optional

Numerically detected rank of the final weighted design matrix. Less than the number of columns indicates aliasing.

condition_number_float, optional

Largest condition number of XᵀWX observed during IRLS.

theta_float, optional

Estimated Negative Binomial dispersion, set only when fitting with NegativeBinomialFamily(theta='estimate') (glm.nb two-step flow).

std_errors_Array

Standard errors for fitted coefficients (computed on demand). Based on the dispersion-scaled covariance; Wald statistics use the normal (z) reference distribution, matching the statsmodels GLM default (use_t=False).

p_values_Array

Wald p-values for fitted coefficients (computed on demand).

coef_cov: Array

Covariance matrix of fitted coefficients (computed on demand).

intercept_std_error_float, optional

Standard error of the intercept (computed on demand).

intercept_p_value_float, optional

Wald p-value for the intercept (computed on demand).

diagnostics_: GLMDiagnosticResult

Residual and influence diagnostics (computed on demand).

coef_: Array
intercept_: float | None
family: Family
link: LinkFunction
mu_: Array
eta_: Array
deviance_: float
null_deviance_: float
aic_: float
bic_: float
n_iter_: int
converged_: bool
log_likelihood_: float = 0.0
dispersion_: float = 1.0
rank_: int | None = None
condition_number_: float | None = None
theta_: float | None = None
property scale_: float

Alias for dispersion_ (statsmodels terminology).

property std_errors_: ndarray | Any

Return standard errors for the fitted coefficients.

property p_values_: ndarray | Any

Return Wald p-values for the fitted coefficients.

property coef_cov_: ndarray | Any

Return the covariance matrix of the fitted coefficients.

property intercept_std_error_: float | None

Standard error of the intercept parameter, if fitted.

property intercept_p_value_: float | None

Wald p-value for the intercept parameter, if fitted.

property diagnostics_: GLMDiagnosticResult

Return (and cache) residual and influence diagnostics for this fit.

predict(X_new, *, type='response', backend=None, interval=None, level=0.95)[source]

Generate predictions for new design matrices.

Returns the mean prediction when interval is None; otherwise a tuple (mean, lower, upper) with Wald confidence bounds.

Parameters:
Return type:

ndarray | Any | tuple[ndarray | Any, ndarray | Any, ndarray | Any]

summary(*, detailed=True)[source]

Generate a formatted summary table of the GLM fit.

Parameters:

detailed (bool, default=True) – If True, includes full coefficient table with statistics. If False, returns a condensed summary with key model metrics only.

Returns:

Multi-line formatted string containing:

  • Model information (family, link, observations, parameters)

  • Convergence status and iterations

  • Coefficient table with estimates, std errors, z-values, p-values

  • Goodness-of-fit statistics (deviance, AIC, BIC, pseudo R²)

Return type:

str

Examples

>>> import numpy as np
>>> from aurora.models.glm import fit_glm
>>> X = np.random.randn(100, 2)
>>> y = np.random.poisson(np.exp(X[:, 0] * 0.5))
>>> result = fit_glm(X, y, family='poisson', link='log')
>>> print(result.summary())
plot_diagnostics(*, figsize=(12, 10))[source]

Generate standard diagnostic plots for the fitted GLM.

Creates a 2x2 grid of diagnostic plots: 1. Residuals vs Fitted: response residuals against fitted values 2. Q-Q Plot: theoretical normal quantiles vs studentized residuals 3. Scale-Location: sqrt(|studentized residuals|) vs fitted values 4. Residuals vs Leverage: studentized residuals vs leverage, with Cook’s distance contours

Parameters:

figsize (tuple of float, default=(12, 10)) – Figure size in inches (width, height).

Returns:

The created figure object containing the 4 diagnostic plots.

Return type:

matplotlib.figure.Figure

Raises:

ImportError – If matplotlib is not installed.

Examples

>>> import numpy as np
>>> from aurora.models.glm import fit_glm
>>> X = np.random.randn(100, 2)
>>> y = np.random.poisson(np.exp(X[:, 0] * 0.5))
>>> result = fit_glm(X, y, family='poisson')
>>> fig = result.plot_diagnostics()
>>> fig.savefig('diagnostics.png')
Parameters:
  • coef_ (Array)

  • intercept_ (float | None)

  • family (Family)

  • link (LinkFunction)

  • mu_ (Array)

  • eta_ (Array)

  • deviance_ (float)

  • null_deviance_ (float)

  • aic_ (float)

  • bic_ (float)

  • n_iter_ (int)

  • converged_ (bool)

  • log_likelihood_ (float)

  • dispersion_ (float)

  • rank_ (int | None)

  • condition_number_ (float | None)

  • theta_ (float | None)

  • _coef_cov (Array | None)

  • _std_errors (Array | None)

  • _p_values (Array | None)

  • _X (Array | None)

  • _y (Array | None)

  • _weights (Array | None)

  • _offset (Array | None)

  • _fit_intercept (bool)

  • _intercept_std_error (float | None)

  • _intercept_p_value (float | None)

  • _diagnostics_cache (GLMDiagnosticResult | None)

Fitting

aurora.models.glm.fitting.fit_glm(X, y, *, family='gaussian', link=None, weights=None, offset=None, backend=None, device=None, max_iter=25, tol=1e-8, fit_intercept=True)[source]

Fit a Generalized Linear Model using IRLS.

Parameters:
  • X (array-like) – Design matrix of shape (n_samples, n_features).

  • y (array-like) – Target values of shape (n_samples,).

  • family (str or Family) – Distribution family (‘gaussian’, ‘poisson’, ‘binomial’, ‘gamma’).

  • link (str or LinkFunction, optional) – Link function. If None, uses family default.

  • weights (array-like, optional) – Prior weights (R glm convention): each observation contributes wᵢ times its unit deviance/log-likelihood. For grouped binomial data, pass proportions as y and trial counts as weights.

  • offset (array-like, optional) – Offset term.

  • backend (str, optional) – Computational backend: ‘numpy’, ‘torch’, or ‘jax’. If None, infers from input data type.

  • device (str, optional) – Device for computation (for torch backend): ‘cpu’, ‘cuda’, ‘cuda:0’, etc.

  • max_iter (int) – Maximum number of IRLS iterations.

  • tol (float) – Convergence tolerance.

  • fit_intercept (bool) – Whether to fit an intercept term.

Returns:

Fitted model results.

Return type:

GLMResult

Prediction

aurora.models.glm.prediction.predict_glm(model, design_matrix, *, backend=None, type='response')[source]

Generate predictions from a fitted GLM model.

This is a convenience wrapper around the GLMResult.predict() method, providing a functional interface for predictions.

Parameters:
  • model (GLMResult) – A fitted GLM model result from fit_glm().

  • design_matrix (ArrayLike) – Design matrix for prediction. Shape (n_samples, n_features).

  • backend (str, optional) – Backend to use for computation (‘numpy’, ‘torch’, ‘jax’). If None, uses the backend from the fitted model.

  • type ({'response', 'link'}, default='response') – Type of prediction: - ‘response’: Predictions on the response scale (μ = g⁻¹(Xβ)) - ‘link’: Predictions on the linear predictor scale (η = Xβ)

Returns:

predictions – Predicted values. Shape (n_samples,).

Return type:

ArrayLike

Examples

>>> from aurora.models import fit_glm, predict_glm
>>> from aurora import GaussianFamily
>>>
>>> # Fit a linear model
>>> result = fit_glm(X_train, y_train, family=GaussianFamily())
>>>
>>> # Predict on test data
>>> y_pred = predict_glm(result, X_test)
>>>
>>> # Get linear predictor values
>>> eta = predict_glm(result, X_test, type='link')

See also

fit_glm

Fit a Generalized Linear Model

GLMResult.predict

Instance method for predictions

Result

class aurora.models.glm.fitting.GLMResult(coef_, intercept_, family, link, mu_, eta_, deviance_, null_deviance_, aic_, bic_, n_iter_, converged_, log_likelihood_=0.0, dispersion_=1.0, rank_=None, condition_number_=None, theta_=None, _coef_cov=None, _std_errors=None, _p_values=None, _X=None, _y=None, _weights=None, _offset=None, _fit_intercept=True, _intercept_std_error=None, _intercept_p_value=None, _diagnostics_cache=None)[source]

Bases: object

Structured container describing the outcome of a GLM fit.

The Attributes

coef_Array

Fitted coefficients (excluding intercept if present).

intercept_float or optional

Fitted intercept. None when fit_intercept=False.

familyFamily

Distribution family instance.

linkLinkFunction

Link function instance.

mu_Array

Fitted mean values.

eta_Array

Fitted linear predictor values.

deviance_float

Model deviance.

null_deviance_float

Null model deviance (intercept-only model).

log_likelihood_float

Log-likelihood of the fitted model.

aic_float

Akaike Information Criterion.

bic_float

Bayesian Information Criterion.

n_iter_int

Number of IRLS iterations.

converged_bool

Whether fitting converged.

dispersion_float

Estimated dispersion parameter φ̂ = deviance / (n − rank) for families with free dispersion (Gaussian, Gamma, InverseGaussian); exactly 1.0 for Poisson/Binomial. Scales the coefficient covariance matrix (R summary.glm convention).

rank_int, optional

Numerically detected rank of the final weighted design matrix. Less than the number of columns indicates aliasing.

condition_number_float, optional

Largest condition number of XᵀWX observed during IRLS.

theta_float, optional

Estimated Negative Binomial dispersion, set only when fitting with NegativeBinomialFamily(theta='estimate') (glm.nb two-step flow).

std_errors_Array

Standard errors for fitted coefficients (computed on demand). Based on the dispersion-scaled covariance; Wald statistics use the normal (z) reference distribution, matching the statsmodels GLM default (use_t=False).

p_values_Array

Wald p-values for fitted coefficients (computed on demand).

coef_cov: Array

Covariance matrix of fitted coefficients (computed on demand).

intercept_std_error_float, optional

Standard error of the intercept (computed on demand).

intercept_p_value_float, optional

Wald p-value for the intercept (computed on demand).

diagnostics_: GLMDiagnosticResult

Residual and influence diagnostics (computed on demand).

coef_: Array
intercept_: float | None
family: Family
mu_: Array
eta_: Array
deviance_: float
null_deviance_: float
aic_: float
bic_: float
n_iter_: int
converged_: bool
log_likelihood_: float = 0.0
dispersion_: float = 1.0
rank_: int | None = None
condition_number_: float | None = None
theta_: float | None = None
property scale_: float

Alias for dispersion_ (statsmodels terminology).

property std_errors_: ndarray | Any

Return standard errors for the fitted coefficients.

property p_values_: ndarray | Any

Return Wald p-values for the fitted coefficients.

property coef_cov_: ndarray | Any

Return the covariance matrix of the fitted coefficients.

property intercept_std_error_: float | None

Standard error of the intercept parameter, if fitted.

property intercept_p_value_: float | None

Wald p-value for the intercept parameter, if fitted.

property diagnostics_: GLMDiagnosticResult

Return (and cache) residual and influence diagnostics for this fit.

predict(X_new, *, type='response', backend=None, interval=None, level=0.95)[source]

Generate predictions for new design matrices.

Returns the mean prediction when interval is None; otherwise a tuple (mean, lower, upper) with Wald confidence bounds.

Parameters:
Return type:

ndarray | Any | tuple[ndarray | Any, ndarray | Any, ndarray | Any]

summary(*, detailed=True)[source]

Generate a formatted summary table of the GLM fit.

Parameters:

detailed (bool, default=True) – If True, includes full coefficient table with statistics. If False, returns a condensed summary with key model metrics only.

Returns:

Multi-line formatted string containing:

  • Model information (family, link, observations, parameters)

  • Convergence status and iterations

  • Coefficient table with estimates, std errors, z-values, p-values

  • Goodness-of-fit statistics (deviance, AIC, BIC, pseudo R²)

Return type:

str

Examples

>>> import numpy as np
>>> from aurora.models.glm import fit_glm
>>> X = np.random.randn(100, 2)
>>> y = np.random.poisson(np.exp(X[:, 0] * 0.5))
>>> result = fit_glm(X, y, family='poisson', link='log')
>>> print(result.summary())
plot_diagnostics(*, figsize=(12, 10))[source]

Generate standard diagnostic plots for the fitted GLM.

Creates a 2x2 grid of diagnostic plots: 1. Residuals vs Fitted: response residuals against fitted values 2. Q-Q Plot: theoretical normal quantiles vs studentized residuals 3. Scale-Location: sqrt(|studentized residuals|) vs fitted values 4. Residuals vs Leverage: studentized residuals vs leverage, with Cook’s distance contours

Parameters:

figsize (tuple of float, default=(12, 10)) – Figure size in inches (width, height).

Returns:

The created figure object containing the 4 diagnostic plots.

Return type:

matplotlib.figure.Figure

Raises:

ImportError – If matplotlib is not installed.

Examples

>>> import numpy as np
>>> from aurora.models.glm import fit_glm
>>> X = np.random.randn(100, 2)
>>> y = np.random.poisson(np.exp(X[:, 0] * 0.5))
>>> result = fit_glm(X, y, family='poisson')
>>> fig = result.plot_diagnostics()
>>> fig.savefig('diagnostics.png')
Parameters:
  • coef_ (Array)

  • intercept_ (float | None)

  • family (Family)

  • link (LinkFunction)

  • mu_ (Array)

  • eta_ (Array)

  • deviance_ (float)

  • null_deviance_ (float)

  • aic_ (float)

  • bic_ (float)

  • n_iter_ (int)

  • converged_ (bool)

  • log_likelihood_ (float)

  • dispersion_ (float)

  • rank_ (int | None)

  • condition_number_ (float | None)

  • theta_ (float | None)

  • _coef_cov (Array | None)

  • _std_errors (Array | None)

  • _p_values (Array | None)

  • _X (Array | None)

  • _y (Array | None)

  • _weights (Array | None)

  • _offset (Array | None)

  • _fit_intercept (bool)

  • _intercept_std_error (float | None)

  • _intercept_p_value (float | None)

  • _diagnostics_cache (GLMDiagnosticResult | None)