prediction
Prediction helpers for brms models.
This module wraps brms prediction utilities and returns typed result objects that
contain both an ArviZ InferenceData view and the underlying R result.
Notes
Executed inside the worker process that hosts the embedded R session.
Attributes¶
FitResult = IDResult[IDBrm]
module-attribute
¶
ProxyListSexpVector = Union[SexpWrapper, ListSexpVector, None]
module-attribute
¶
Classes¶
IDLogLikelihoodInsample
¶
IDLogLikelihoodOutsample
¶
Bases: IDPredictionsConstantData
Typed .log_likelihood extension to idata
Source code in brmspy/types/brms_results.py
IDObservedData
¶
IDPosteriorPredictive
¶
Bases: IDConstantData
Typed .posterior_predictive extension to idata
Source code in brmspy/types/brms_results.py
IDPredictions
¶
IDResult
dataclass
¶
Bases: Generic[T_idata], RListVectorExtension
Generic result container with arviz and R objects.
Attributes:
| Name | Type | Description |
|---|---|---|
idata |
InferenceData
|
arviz InferenceData object |
r |
ListVector
|
R object from brms |
Source code in brmspy/types/brms_results.py
IDPosterior
¶
Functions¶
_arviz_add_constant_data(idata, constant_data_dict, group_name='constant_data', obs_id=None)
¶
Add a non-draw group (constant_data or predictions_constant_data) to an idata.
Extracts obs_id coords directly from the existing idata. This avoids ArviZ's auto (chain, draw) dims and keeps the group purely 1D along obs_id.
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_constant_data(brmsfit_obj, newdata=None, resp_names=None)
¶
Extract constant_data for ArviZ.
- If newdata is None: use brmsfit$data.
- Else: use the provided newdata.
- Drop response columns and 'obs_id' (responses go to observed_data, obs_id is handled as a coord).
- Return a dict[var_name -> np.ndarray] with length N (N = number of rows).
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_dims_and_coords(brmsfit_obj, newdata=None, resp_names=None)
¶
Infer dims/coords for ArviZ from a brmsfit object and optional newdata.
Rules for obs_id:
- If newdata is None:
1) If obs_id column exists in fit$data and is unique: use that.
2) Else, if rownames of fit$data are unique: use those.
3) Else: use a sequential integer range [0, N).
- If newdata is not None:
1) If obs_id column exists in newdata and is unique: use that.
2) Else: use newdata.index (with a warning if not unique).
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_observed_data(brmsfit_obj, resp_names=None)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_posterior(brmsfit_obj, **kwargs)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_predict_generic(brmsfit_obj, function='brms::posterior_predict', resp_names=None, **kwargs)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_brmsfit_get_response_names(brmsfit_obj)
¶
Source code in brmspy/helpers/_rpy2/_conversion.py
_idata_add_resp_names_suffix(idata, suffix, resp_names)
¶
In-place: append suffix to all variables in resp_names across all
applicable InferenceData groups.
Mutates idata directly.
Source code in brmspy/helpers/_rpy2/_conversion.py
kwargs_r(kwargs)
¶
Convert Python keyword arguments to R-compatible format.
Convenience function that applies py_to_r() to all values in a keyword arguments dictionary, preparing them for R function calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kwargs
|
dict or None
|
Dictionary of keyword arguments where values may be Python objects (dicts, lists, DataFrames, arrays, etc.) |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with same keys but R-compatible values, or empty dict if None |
Notes
This is a thin wrapper around py_to_r() that operates on dictionaries.
It's commonly used to prepare keyword arguments for R function calls via rpy2.
Examples:
from brmspy.helpers.conversion import kwargs_r
import pandas as pd
import numpy as np
# Prepare kwargs for R function
py_kwargs = {
'data': pd.DataFrame({'y': [1, 2], 'x': [1, 2]}),
'prior': {'b': [0, 1]},
'chains': 4,
'iter': 2000
}
r_kwargs = kwargs_r(py_kwargs)
# All values converted to R objects
# Can now call: r_function(**r_kwargs)
See Also
py_to_r : Underlying conversion function for individual values brmspy.brms.fit : Uses this to prepare user kwargs for R
Source code in brmspy/helpers/_rpy2/_conversion.py
py_to_r(obj)
¶
Convert arbitrary Python objects to R objects via rpy2.
Comprehensive converter that handles nested structures (dicts, lists), DataFrames, arrays, and scalars. Uses rpy2's converters with special handling for dictionaries (→ R named lists) and lists of dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
any
|
Python object to convert. Supported types: - None → R NULL - dict → R named list (ListVector), recursively - list/tuple of dicts → R list of named lists - list/tuple (other) → R vector or list - pd.DataFrame → R data.frame - np.ndarray → R vector/matrix - scalars (int, float, str, bool) → R atomic types |
required |
Returns:
| Type | Description |
|---|---|
rpy2 R object
|
R representation of the Python object |
Notes
Conversion Rules:
- None: → R NULL
- DataFrames: → R data.frame (via pandas2ri)
- Dictionaries: → R named list (ListVector), recursively converting values
- Lists of dicts: → R list with 1-based indexed names containing named lists
- Other lists/tuples: → R vectors or lists (via rpy2 default)
- NumPy arrays: → R vectors/matrices (via numpy2ri)
- Scalars: → R atomic values
Recursive Conversion:
Dictionary values are recursively converted, allowing nested structures:
List of Dicts:
Lists containing only dicts are converted to R lists with 1-based indexing:
Examples:
from brmspy.helpers.conversion import py_to_r
import numpy as np
import pandas as pd
# Scalars
py_to_r(5) # R: 5
py_to_r("hello") # R: "hello"
py_to_r(None) # R: NULL
# Arrays
py_to_r(np.array([1, 2, 3])) # R: c(1, 2, 3)
# DataFrames
df = pd.DataFrame({'x': [1, 2], 'y': [3, 4]})
py_to_r(df) # R: data.frame(x = c(1, 2), y = c(3, 4))
See Also
r_to_py : Convert R objects back to Python kwargs_r : Convert keyword arguments dict for R function calls brmspy.brms.fit : Uses this for converting data to R
Source code in brmspy/helpers/_rpy2/_converters/_dispatch.py
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 | |
posterior(model, **kwargs)
¶
Return posterior draws as idata.
Wrapper around R posterior::as_draws_df().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorEpredResult
|
Result containing |
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
ep = brms.posterior(fit)
ep.idata.posterior
Source code in brmspy/_brms_functions/prediction.py
observed_data(model)
¶
Source code in brmspy/_brms_functions/prediction.py
posterior_epred(model, newdata=None, **kwargs)
¶
Compute expected posterior predictions (noise-free).
Wrapper around R brms::posterior_epred(). This returns draws of the
expected value (typically on the response scale), without observation noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data for predictions. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorEpredResult
|
Result containing |
See Also
brms::posterior_epred : R documentation
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
ep = brms.posterior_epred(fit)
ep.idata.posterior
Source code in brmspy/_brms_functions/prediction.py
posterior_predict(model, newdata=None, **kwargs)
¶
Draw from the posterior predictive distribution (includes observation noise).
Wrapper around R brms::posterior_predict().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data for predictions. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorPredictResult
|
Result containing |
See Also
brms::posterior_predict : R documentation
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
pp = brms.posterior_predict(fit)
pp.idata.posterior_predictive
Source code in brmspy/_brms_functions/prediction.py
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 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 | |
posterior_linpred(model, newdata=None, **kwargs)
¶
Draw from the linear predictor.
Wrapper around R brms::posterior_linpred(). This typically returns draws
on the link scale (before applying the inverse link), unless you pass
transform=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data for predictions. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
PosteriorLinpredResult
|
Result containing |
See Also
brms::posterior_linpred : R documentation
Examples:
from brmspy import brms
fit = brms.brm("y ~ x", data=df, chains=4)
lp = brms.posterior_linpred(fit, transform=False)
lp.idata.predictions
Source code in brmspy/_brms_functions/prediction.py
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 | |
log_lik(model, newdata=None, **kwargs)
¶
Compute pointwise log-likelihood draws.
Wrapper around R brms::log_lik(). The result is useful for LOO/WAIC via ArviZ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
FitResult
|
Fitted model. |
required |
newdata
|
DataFrame or None
|
New data. If |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
LogLikResult
|
Result containing |
See Also
brms::log_lik : R documentation
Examples:
from brmspy import brms
import arviz as az
fit = brms.brm("y ~ x", data=df, chains=4)
ll = brms.log_lik(fit)
az.loo(ll.idata)