Skip to contents

Posterior expectation at the training locations: the column means of brms::posterior_epred(). These are in-sample values.

Usage

# S3 method for class 'bayesian_fit'
fitted(object, ...)

Arguments

object

A bayesian_fit.

...

Ignored.

Value

Numeric vector of length object$n. A posterior that cannot be drawn is an error, as is a family with a probability per response category (ordinal, categorical), which has no single fitted value per row.

The result is cached

posterior_epred() is O(draws x n), and summary(), residuals(), model_metrics() and compare_models() each call fitted() independently, so the value is memoised in an environment carried in object$info$.cache (reference semantics, so it survives R's copy-on-modify). The cache holds epred column means only, which is why predict(object, summary = "median") and predict(object, type = "predict") recompute it from scratch. Call clear_fitted_cache if the engine has been mutated by hand after fitting.

The cache is shared by copies, and validated

An environment has reference semantics, which is what makes the memo survive R's copy-on-modify. But it also means fit2 <- fit gives the two objects the same cache. Assigning a different data_sf to the copy would then have returned the original's cached values, at the original's length, which residuals() silently recycled against the copy's shorter response. The entry therefore carries the n and a digest of the training data it was computed from, and is recomputed whenever either fails to match, so a copy with different data recomputes instead of reading the original's answer.

Two consequences of the shared environment remain and cannot be removed from here: clear_fitted_cache on one copy empties the cache both share (harmless, since the other simply recomputes), and identical() cannot distinguish two fits by their caches. The digest covers data_sf only. The entry is also tied to the engine that computed it – a refit or update() of the brmsfit is a different sampling run and recomputes – but a brmsfit edited by hand in place is what clear_fitted_cache is for. The entry holds only the values and a small identifier of the sampling run, so a fit saved with saveRDS() after fitted() is no larger for it.