WorksMathematics
KernelMix: Bayesian kernel machine regression in Python
Abstract
Exposures measured together can have nonlinear associations with an outcome, and the association with one exposure may depend on another. Bayesian kernel machine regression represents these patterns through a flexible exposure-response function. We implement this approach in KernelMix, a Python package. To handle different outcome types, KernelMix combines the exposure function with continuous, binary, count and survival models, including selected extensions for clustered observations and censored event times. For fitted models, it returns posterior summaries, uncertainty intervals, joint predictions and sampling diagnostics. Fitting and prediction use NumPy and SciPy without requiring R. To assess the implementation, we compare selected Gaussian and probit posterior summaries and conditional calculations with installed R bkmr 0.2.2 and check additional model components against independent mathematical calculations. A daily ozone analysis illustrates how these components form an analysis workflow.
Motivation
Exposure-mixture analyses ask how an outcome varies with several exposures measured together. A model with only separate linear exposure terms cannot represent curved associations or an association that changes with another exposure. Bayesian kernel machine regression (BKMR) replaces those terms with a joint exposure–response function, allowing these patterns without specifying each nonlinear term and interaction in advance [1].
We develop KernelMix to provide this analysis workflow in Python. The package combines model fitting with exposure contrasts, joint prediction, uncertainty summaries and sampling checks. NumPy [2] and SciPy [3] handle these calculations, so fitting and prediction do not require R. Our contribution is the software implementation and its documented numerical checks; the BKMR formulation is due to Bobb and colleagues.
Related software
The R package bkmr provides Gaussian and probit BKMR models and summaries of exposure associations [4]. We use installed bkmr 0.2.2 as a numerical reference for selected calculations in these models. Constructed parameter states check conditional calculations. We also compare fitted posterior summaries under matched data and priors, allowing for Monte Carlo error from finite sampling.
KernelMix also supports count and survival outcomes, additional cluster and residual models, and alternative kernel representations. These options have separate likelihoods, priors and prediction rules, so agreement with the Gaussian and probit reference does not validate them.
Methods and implementation
We first describe how the joint exposure function enters a model for a continuous outcome. Following Bobb et al. [1], let be the outcome for observation , its exposures, and its adjustment covariates. We write the joint exposure contribution as and retain linear adjustment through coefficients . Together, these terms give the Gaussian model
The function contains the nonlinear associations and interactions, while represents independent error with variance .
Fitting requires a way to relate its values at different exposure combinations. We specify this relationship through a Gaussian process (GP) prior. A prior describes parameter or function values before using the outcome data; the posterior updates that distribution using the data. For observations, write . The GP prior relates these values through the Gaussian kernel [1, 5],
The kernel describes similarity between exposure combinations, while controls variation in . Each controls how exposure affects that similarity. Setting removes exposure from , which permits exposure selection. Group selection restricts each included group to at most one exposure [1]. Inclusion probabilities summarize selection under the fitted model; neither they nor measure causal importance.
The Gaussian model above combines the exposure function and linear adjustment with a continuous outcome. To handle other outcomes, we retain those two contributions but change their link to the outcome distribution. For binary outcomes, the probit model gives outcome one when an underlying normal variable exceeds zero [4]. Poisson and negative-binomial models describe counts [6]. For event times, a piecewise-exponential model uses a baseline hazard that is constant within each time interval [7]. A hazard is an instantaneous event rate among individuals still at risk [6].
Event-time fitting also depends on what is observed about each event. Survival records can specify entry after time zero, competing event causes, or an event known only to occur within an interval. Supplied covariate histories remain constant within each recorded risk interval. With delayed entry, inference concerns the included cohort and does not recover the distribution of unobserved risk before entry.
Beyond the outcome type, repeated observations may share variation within a cluster. Random intercepts and slopes represent this variation through shared coefficients [4, 8]. For Gaussian outcomes, residual models can separately specify unequal error variances or correlation within clusters [8].
These outcome and dependence options are distinct from the kernel that relates exposure combinations. The Gaussian kernel can be replaced by Matérn 3/2 or rational-quadratic kernels [5]. To reduce the number of GP coordinates, we also provide predictive-process and paired random-Fourier representations [9, 10]. This reduction changes the model approximation: the predictive process omits variation remaining after conditioning on knots, and random-Fourier inference conditions on the sampled features. Large residual-correlation blocks and joint prediction requests can still require dense matrices.
These model choices also affect sampling and prior conventions. The default Gaussian sampler averages over analytically during parameter sampling; default Gaussian and probit fits store , with for probit. Count, survival and structured fits instead store the direct amplitude as lambda and use proper normal priors for adjustment coefficients. The Gaussian-prior blocks in these fits use elliptical slice sampling [11]. Priors therefore need to be compared on their stated parameter scales. The manual specifies the inputs, priors and prediction rules for each option.
Software checks
We check fitted posterior summaries against installed R bkmr 0.2.2 on four fixed datasets: Gaussian and probit models, each with and without random intercepts. Both implementations use identical observations, exposure standardization, adjustment design and priors, with exposure selection disabled. Four chains per implementation provide means and 10th, 50th and 90th posterior percentiles for parameters, three values of and one exposure contrast. Each R chain retains 120,000 draws after 3,000 warmup transitions; each Python chain retains 60,000. All 160 checked summaries pass the fixed diagnostic, precision and discrepancy rules. We require rank-normalized/folded split , bulk/tail effective sample sizes at least 400 and Monte Carlo standard errors at most 2% of the pooled posterior standard deviation. The manual gives the complete comparison rules and results; these numerical screens do not establish posterior equivalence or general convergence. Constructed-state checks additionally compare conditional means, covariances, inclusion probabilities and prior densities.
For models without an R reference, we compare selected posterior moments with independent numerical integration. Three fixed cases cover negative-binomial counts, right-censored survival and a Gaussian model with random intercepts/slopes and AR1 residual correlation. All use a constant exposure function, with its GP amplitude sampled. The structured case fixes random-coefficient covariance and residual correlation. All 12 checked moments and four selected covariances pass their error and precision rules. These small cases assess the stated posterior quantities, not every structured option or general convergence.
An installed wheel passes 512 tests in each of two native macOS environments: Python 3.14 with current dependencies and Python 3.10 with minimum dependencies. Configured hosted Linux and Windows jobs stop before runner startup, so Windows and hosted Linux compatibility remain unverified.
Numerical agreement is distinct from reproducing the original BKMR studies. The original simulations used 300 datasets per scenario with and resampled empirical exposure rows; the applications analyzed 375 children and 142 exposure records from 13 dogs [1]. The original Bangladesh, Boston and dog datasets and sufficient fitting settings were not recovered from the inspected open assets. Gaussian-generated exposures with a similar covariance would define a different experiment. We therefore use the observed-data example below to demonstrate the workflow, without treating it as original-study reproduction or a study of interval coverage.
Observed-data example
Data
We use the public airquality data to examine how daily ozone varies with solar radiation, wind and temperature, after adjustment for calendar month [12, 13]. The data contain 153 New York daily records from May–September 1973. Ozone and weather measurements come from different stations and times, so they do not describe a person’s joint exposures.
Before fitting, we identify the days with all required measurements: 111 are retained and 42 are excluded. There are 37 missing ozone values and seven missing solar-radiation values, with overlap. Figure 1 shows that this exclusion is uneven across months: June retains 9 of 30 days, compared with 29 of 30 in September. For these retained days, Figure 2 shows ozone against each weather measurement. These pairwise plots leave the other weather variables and month unadjusted.
Figure 1. Measurement availability among 153 daily records, May–September 1973. (a) Each cell represents one day: filled cells indicate recorded measurements and crosses indicate missing values. Fractions report recorded measurements out of 153 days. (b) Filled bars show complete days within outlines for all recorded days; fractions give complete/recorded counts. The analysis uses 111 complete days. Missing values are neither imputed nor treated as zero.
Figure 2. Ozone against solar radiation, wind and temperature among the 111 complete days. Each point represents one day. The plots show unadjusted observations, without holding other weather variables or month fixed.
Model and fitted associations
To estimate the weather associations together and adjust for month, we fit the Gaussian model to , with solar radiation, wind and temperature in . The adjustment vector contains an intercept and four indicators for June through September, with May as the reference. We standardize exposures using the retained days. This month adjustment represents broad seasonal differences; the independent-error assumption does not account for dependence between consecutive days.
We use independent priors, an inverse-gamma prior for , and the default flat prior for . Gamma parameters are shape and rate. Exposure selection is disabled, so this analysis estimates the joint exposure function without selecting a subset of weather variables.
With the model and priors specified, we ran four chains sequentially with seed 73. Each used 5,000 discarded warmup iterations followed by 20,000 saved draws. An initial run with 4,000 saved draws had maximum , after which we extended sampling without changing the model, data or priors. Curve and fitted-residual summaries use 400 evenly spaced draws per chain. Fitting took 72.6 seconds in the recorded local environment.
In the longer run, the maximum was 1.0053, the minimum bulk effective sample size was 885 and the minimum tail effective sample size was 1,193. These summaries concern ten individual parameters; the full diagnostics are shown below.
Figure 3 separates each fitted weather association by varying one exposure while fixing the others at their medians. The posterior mean curve generally rises with temperature and falls with wind; the solar-radiation curve is nonlinear. These are fitted conditional associations, with pointwise uncertainty under the independent-error model.
Figure 3. Fitted exposure associations and residuals (). (a–c) Posterior means and 95% pointwise credible intervals for , with other exposures fixed at their medians and the all-median profile. (d–f) Fitted versus observed log ozone, residuals by date, and residual pairs one calendar day apart. Missing dates are not connected. Intervals assume independent Gaussian working errors.
The displayed contrast is , where is the vector of exposure medians. On the log-ozone scale, exponentiating this contrast gives a ratio of fitted ozone medians at the two exposure combinations, with month held fixed. It does not give a difference in arithmetic means.
To inspect the variation remaining after fitting, we examine the fitted-versus-observed and residual panels. These use the same days used for fitting, so they assess the fitted sample rather than prediction on new data. Among 92 residual pairs from consecutive calendar days, the sample correlation is 0.0136; this small correlation does not establish independent errors.
The fitted model separates the exposure function from month adjustment. Figure 4 reports their parameters separately, distinguishing kernel relevance from month coefficients . Their different roles require separate axes. Each 95% credible interval contains 95% of the posterior probability under the fitted model. Because exposure selection is disabled, positive values describe the fitted kernel and do not establish variable-selection evidence.
Figure 4. Posterior means and 95% equal-tailed credible intervals for (a) kernel relevance parameters and (b) month coefficients in , relative to May, on the log-ozone scale. The intercept is omitted. The panels have different scales; kernel relevance does not measure causal importance.
Sampling checks and exposure support
The preceding intervals depend on adequate posterior sampling. We assess sampling with split , which compares chains, and effective sample sizes, which account for dependence between draws [14] (Figure 5). Bulk effective sample size concerns the main posterior distribution, while tail effective sample size concerns its tails. These checks cover ten individual parameters; favorable values do not prove convergence of every exposure curve or validate the model assumptions.
Figure 5. Sampling diagnostics for ten parameters from four chains, each with 20,000 saved draws. (a) Rank-normalized/folded split . (b) Bulk effective sample size. (c) Tail effective sample size. These diagnostics assess sampling, not the model assumptions.
Adequate sampling also does not ensure that the plotted exposure combinations occur in the data. Each curve uses the exposure’s 5th–95th percentiles, with duplicate values removed, while fixing the other exposures at their medians. This construction can produce combinations far from observed rows. We therefore report the distance to the nearest complete exposure combination after training standardization (Figure 6). Larger distances indicate less nearby data; no cutoff is used to declare a prediction reliable.
Figure 6. Nearest observed-combination distance after exposure standardization. Each plotted value is combined with medians of the other exposures. The grids contain 21 solar-radiation, 17 wind and 21 temperature values. Distance measures proximity to the complete observed data, without a model-validity threshold.
Limits and reproducibility
The ozone curves describe conditional associations under the specified priors and independent Gaussian errors. Month adjustment does not model daily dependence, and complete-case analysis may introduce selection bias [15]. Sampling diagnostics address neither issue, so the analysis supports no causal or forecasting claim. The numerical checks also leave repeated-dataset bias, interval coverage, original-study reproduction and large-data performance unresolved.
To make these calculations and the ozone workflow reproducible, the repository at https://github.com/nilson01/kernelmix includes installation instructions, a function reference, tests, source data and analysis scripts. Saved tables record the data hash, fitting settings, environment and diagnostics. Figure scripts use Matplotlib [16]. The software is distributed under GPL-2.0; the R reference and data sources are credited separately.
Acknowledgements
Computations were performed on the Arseven Computing Cluster, Department of Statistics, Texas A&M University.
This work received no grant funding.
References
- [1]Bobb JF et al. (2015). Bayesian kernel machine regression for estimating the health effects of multi-pollutant mixtures. Biostatistics 16, 493–508. doi:10.1093/biostatistics/kxu058.DOI
- [2]Harris CR et al. (2020). Array programming with NumPy. Nature 585, 357–362. doi:10.1038/s41586-020-2649-2.DOI
- [3]Virtanen P et al. (2020). SciPy 1.0: fundamental algorithms for scientific computing in Python. Nature Methods 17, 261–272. doi:10.1038/s41592-019-0686-2.DOI
- [4]Bobb JF, Claus Henn B, Valeri L and Coull BA (2018). Statistical software for analyzing the health effects of multiple concurrent exposures via Bayesian kernel machine regression. Environmental Health 17, 67. doi:10.1186/s12940-018-0413-y.DOI
- [5]Rasmussen CE and Williams CKI (2006). Gaussian Processes for Machine Learning. MIT Press. Chapter 4.DOI
- [6]Stan Development Team. Stan documentation, version 2.40. Count distributions; survival models.
- [7]Martino S and Rue H (2009). Implementing Approximate Bayesian Inference using Integrated Nested Laplace Approximation: a manual for the inla program, Section 3.15. Manual.
- [8]Pinheiro JC and Bates DM. nlme documentation, version 3.1-168. Mixed-effects models; AR(1) correlation; exponential variance.
- [9]Banerjee S, Gelfand AE, Finley AO and Sang H (2008). Gaussian predictive process models for large spatial data sets. Journal of the Royal Statistical Society: Series B 70, 825–848. doi:10.1111/j.1467-9868.2008.00663.x.DOI
- [10]Rahimi A and Recht B (2007). Random features for large-scale kernel machines. Advances in Neural Information Processing Systems 20. Proceedings paper.
- [11]Murray I, Adams RP and MacKay DJC (2010). Elliptical slice sampling. Proceedings of Machine Learning Research 9, 541–548. Proceedings paper.arxiv.org/abs/1001.0175
- [12]R Core Team (2025). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna. Data export: R 4.5.0, datasets::airquality. Dataset documentation.
- [13]Chambers JM, Cleveland WS, Kleiner B and Tukey PA (1983). Graphical Methods for Data Analysis. Wadsworth & Brooks/Cole.
- [14]Vehtari A, Gelman A, Simpson D, Carpenter B and Bürkner PC (2021). Rank-normalization, folding, and localization: an improved R̂ for assessing convergence of MCMC. Bayesian Analysis 16, 667–718. doi:10.1214/20-BA1221.DOI
- [15]Sterne JAC et al. (2009). Multiple imputation for missing data in epidemiological and clinical research: potential and pitfalls. BMJ 338, b2393. doi:10.1136/bmj.b2393.DOI
- [16]Hunter JD (2007). Matplotlib: a 2D graphics environment. Computing in Science & Engineering 9(3), 90–95. doi:10.1109/MCSE.2007.55.DOI





