Weighted samples
Every sampler returns WeightedSamples. The samples and their weights together define the estimate.
Weighted moments
using ImportanceSamplers, PureRNGs, Statisticssamples = importance_sample( Threefry4x32(42), x -> -sum(abs2, x) / 2, ImportanceSampling(SphericalGaussian(zeros(3), 1.5); nsamples=5_000),)(mean=mean(samples), variance=var(samples), covariance=cov(samples))(mean = [-0.009344971287580196, 0.00702216840468725, -0.018963717701197303], variance = [0.9626795503259313, 0.9695934159711251, 0.9577720999851802], covariance = [0.9626795503259293 0.0072253088670014105 0.010806896000543938; 0.0072253088670014105 0.9695934159711267 -0.0066714010694321965; 0.010806896000543938 -0.0066714010694321965 0.957772099985181])These Statistics methods use normalized importance weights. var, std, and cov describe the weighted target approximation. They use corrected=false. The usual unweighted sample-size correction is not valid here.
Compute a scalar function of each sampled parameter vector directly:
( expectation=mean(x -> sum(abs2, x), samples), variance=var(x -> sum(abs2, x), samples), probability=mean(x -> x[1] > 0, samples),)(expectation = 2.8905413282087595, variance = 5.9716518562919845, probability = 0.4843558901541335)std(f, samples) follows the same convention. The variance describes f(X) under the target, not the Monte Carlo error of its estimated mean. The logistic tutorial estimates that error for independent fixed-proposal production draws. Weight ESS is not a substitute for this calculation.
Indexing and provenance
samples[1](sample = [0.74054707356691, 2.3428756899583814, -1.9362045993176733], logweight = 1.2547762802759044, provenance = NamedTuple())Scalar indexing returns (; sample, logweight, provenance). Iteration returns the same aligned records.
| One draw | Storage in samples.samples |
|---|---|
| Scalar | Length-n vector |
Length-d vector | d × n matrix |
| Named tuple | Named tuple of vector/matrix leaves |
samples.logweights holds the raw log weights. samples.provenance holds aligned identifiers when the method has proposals or rounds. samples.diagnostics contains run-level information.
Pass save_logtargets=true to prepare_sampler or importance_sample to retain the exact target log densities used in weighting as samples.logtargets. These values are in sampling coordinates, including the forward log Jacobian when transform= is used, even when returned samples have logical coordinates. They are recorded during sampling without evaluating the target again. The default is nothing, with no additional sample-sized storage or work. Retained values remain aligned through slicing and explicit device copies; scalar indexing and iteration still return the same three-field records.
Population methods expose provenance.proposal_id. Adaptive methods expose provenance.round. These are generating identifiers, not a request to recompute weights.
Interpret method diagnostics according to the samples and weights they summarize:
| Diagnostic | Interpretation |
|---|---|
AMIS round_ess | Cumulative retained history after retrospective reweighting |
N-PMC round_ess, adaptation_ess | Current-round raw estimator weights versus clipped fitting weights |
CAIS local_ess | Proposal-local weights used for covariance fitting |
LAIS transition | Initial, warmup, and production upper-chain work |
The pilot example interprets an AMIS trace. Compare concentration with retained counts and independent estimates, not an arbitrary ESS cutoff.
Sample subsets
subset = samples[1:100](length(subset), mean(subset))(100, [0.04377144976224365, -0.09530297131533774, 0.11808284329728436])Ranges, integer vectors, and Boolean masks return an aligned WeightedSampleView. Its weighted summaries normalize within that subset.
A subset does not preserve the complete estimator. lognormalizer(subset) is therefore unavailable. A target-dependent selection also changes the population described by the summary.
Results contain separate arrays. Later sampler calls do not change an earlier result. Treat result arrays as read-only to preserve alignment and weight semantics.
Weighted quantiles
( median=median(samples), interval=quantile(samples, [0.025, 0.975]),)(median = [-0.04308097898546047, 0.004586169501441181, -0.038159050956802346], interval = [-1.9077481669566012 1.989151197475573; -1.9078762469824868 1.9920884739964462; -1.9258301589519347 1.9514511315293992])Quantiles are component-wise weighted quantiles. A vector of probabilities gives one output column per probability for vector samples.
Quantiles, medians, scalar indexing, and iteration require CPU storage. Transfer a GPU result explicitly before using them.
Resampling
draws, next_rng = resample_next(Threefry4x32(7), samples)(length(draws), mean(draws))(5000, [-0.02414394291723858, 0.00962316893655212, -0.02011266831804327])The default is multinomial resampling with replacement. Omitting the count requests length(samples) draws. Use resample_next(rng, samples, n) for another count. Pass the returned RNG to continue the stream.
The returned UnweightedSamples contains no importance weights. Its summaries use ordinary unweighted definitions. Resampling adds randomness and does not increase the information in the weighted result. Keep the original result for weighted summaries and normalizer estimates.
Effective sample size and normalizers
weights = normalized_weights(samples)(ess=inv(sum(abs2, weights)), lognormalizer=lognormalizer(samples))(ess = 2871.307261917652, lognormalizer = 2.7834726809252466)Weight ESS is $1/\sum_i\bar w_i^2$. It measures concentration, not mode coverage, tail accuracy, or chain mixing. Adaptive dependence also prevents treating it as a general independent-sample count.
For a complete result with n draws,
\[\log\widehat Z=\operatorname{logsumexp}(\ell_1,\ldots,\ell_n)-\log n.\]
The linear estimate may be unbiased under a method's assumptions. Taking its logarithm does not preserve unbiasedness. Self-normalized expectations generally have finite-sample bias. AMIS has additional retrospective-weight caveats.
If every raw log weight is -Inf, the plain IS result remains inspectable and lognormalizer returns -Inf. Normalized summaries throw AllZeroWeightsError.
Pareto smoothing
psis(samples) creates a separate result with smoothed weights. The Pareto smoothing guide compares it with raw IS on the same draws and explains diagnostics, bias, normalizers, and device support.
Score control variates
fit_control_variate fits a correction for one functional from a pilot. control_variate_mean applies it to independent production samples. The control-variate guide gives an example and the required target-score and boundary conditions. Samples and weights stay unchanged.
Device results
normalized_weights, moments, scalar functionals, slicing, and resampling have device paths. Array outputs stay on the device. Scalar reductions can require synchronization.
For explicit CPU access:
import MLDataDeviceshost_samples = MLDataDevices.CPUDevice()(samples)See Devices for backend limits and Reactant scalar results.