Sampling a Logistic Variable and a Bivariate Chain
Statistics & ExperimentsModel answerLast updated
Derive an inverse-CDF sampler for the logistic distribution, build a Gibbs sampler for a bivariate target, and explain how to check correctness, burn-in, thinning and sample size.
You need to generate random draws from two different targets using only a source of Uniform(0,1) random numbers and standard normal draws.
Part A. Produce samples from a Logistic distribution with location μ and scale s > 0.
- Derive the quantile function (inverse CDF) and explain why it yields the right distribution.
- Describe how you would confirm the generated sample is correct.
- Mention numerical edge cases.
Part B. Produce samples from a bivariate density p(x, y) using Gibbs sampling. Assume a bivariate normal with means μx, μy, standard deviations σx, σy and correlation ρ.
- Derive the full conditional distributions.
- Write the sampler.
- Explain how many draws you need, how much to discard as burn-in, and whether thinning helps.
- Explain how you would detect that the chain has not converged.
State the general recipe for finding full conditionals when the joint density is not normal. Discuss what happens as |ρ| approaches 1.
Hints
Hint 1
For Part A, set u = F(x) and solve for x. The logistic CDF inverts cleanly into a log-odds expression, and you only need U to lie strictly inside (0,1).
Hint 2
For Part B, treat one variable as a constant in the joint density and complete the square. After standardizing, the X-chain of the Gibbs sampler is an AR(1) process, which gives you autocorrelations and an effective sample size.
Hint 3
For sample size, compare the target Monte Carlo error with sigma divided by the square root of the effective sample size, not the raw number of draws. Think about what discarding correlated draws does to the information you keep.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: Inverse-transform sampling for Logistic(μ, s)
Principle. If U ~ Uniform(0,1) and F is a continuous, strictly increasing CDF, then X = F⁻¹(U) has CDF F, because P(F⁻¹(U) ≤ x) = P(U ≤ F(x)) = F(x).
Derivation. The logistic CDF is F(x) = 1 / (1 + exp(−(x−μ)/s)). Setting u = F(x):
1 + exp(−(x−μ)/s) = 1/uexp(−(x−μ)/s) = (1−u)/ux = μ + s·log(u/(1−u))
So the quantile function is μ plus s times the logit of u.
Edge cases.
u = 0oru = 1gives ±∞. Draw from the open interval, or clip. Many generators return values in [0,1), so guard against 0.- Require
s > 0. A negativeswould just reflect the sample, which is still logistic by symmetry, but it is almost certainly a bug. - For numerical stability use
log(u) − log1p(−u)instead oflog(u/(1−u)).
Verification.
- Moments: mean = median =
μ, variance =s²π²/3, skewness 0, excess kurtosis 1.2. - A Kolmogorov–Smirnov test against
F. One p-value is weak evidence, so repeat over many seeds and check that the p-values look roughly uniform. - A QQ plot against theoretical quantiles, paying attention to the tails where bugs hide.
Because the draws are i.i.d., the number needed for a mean to within ±ε at 95% confidence is about n ≈ (1.96·sπ/(√3·ε))².
Part B: Gibbs sampling
Full conditionals. In the joint normal density, fix y and complete the square in x. The result is again normal:
X | Y=y ~ N( μx + ρ(σx/σy)(y − μy), σx²(1 − ρ²) )Y | X=x ~ N( μy + ρ(σy/σx)(x − μx), σy²(1 − ρ²) )
General recipe for any joint p(x, y):
- Treat
p(x | y) ∝ p(x, y)as a function ofxalone. - Drop every factor that does not contain
x. - Recognize the remaining kernel (normal, gamma, beta, binomial and so on), and repeat for
y.
For instance, a joint kernel proportional to C(n,x)·y^(x+α−1)·(1−y)^(n−x+β−1) gives X|y ~ Binomial(n, y) and Y|x ~ Beta(x+α, n−x+β).
Why it works. Each conditional update leaves the joint distribution invariant. When the conditionals have full support the chain is irreducible and aperiodic, so it converges to the target.
Mixing. Standardize both variables. Then Y_{t+1} = ρX_t + noise and X_{t+1} = ρY_{t+1} + noise, which combine to X_{t+1} = ρ²X_t + ε. The X-chain is AR(1) with coefficient ρ²:
- Lag-k autocorrelation:
ρ^(2k) - Integrated autocorrelation time:
τ = (1+ρ²)/(1−ρ²) - Effective sample size:
ESS ≈ N/τ
For ρ = 0.9, τ ≈ 9.5, so 100,000 draws are worth about 10,500 independent ones. As |ρ| → 1 the sampler crawls along the diagonal. Fixes: reparameterize (rotate onto principal axes), or use blocked updates, which here means drawing (X, Y) jointly and exactly.
How many draws. The Monte Carlo standard error of a mean is roughly σ/√ESS. To estimate E[X] within ±0.01 at 95% confidence with σx = 1, you need ESS ≈ (1.96/0.01)² ≈ 38,400. At ρ = 0.9 multiply by τ ≈ 9.5 to get about 366,000 post-burn-in iterations.
Burn-in. Burn-in removes dependence on the starting point.
- Start several chains from overdispersed initial values.
- Discard until trace plots overlap and Gelman–Rubin
R̂ < 1.01. - For this AR(1) chain the start's influence decays like
ρ^(2t), so forρ = 0.9it is below 10⁻⁶ after roughly 66 iterations. A few hundred iterations is generous.
Thinning. Thinning does not improve statistical efficiency, since throwing away correlated draws still discards information. It is justified only to save memory or reduce the cost of expensive downstream calculations. Saying that thinning "makes samples independent and therefore better" is a common mistake.
Diagnostics.
- Trace and autocorrelation plots.
R̂across four or more chains.- Bulk and tail ESS.
- Comparison with known truth: marginal means and variances, and sample correlation against
ρ. If you run a KS test onX, apply it to thinned draws because the test assumes independence.
Code
import numpy as np
from scipy import stats
def sample_logistic(mu, s, n, rng=None):
if s <= 0:
raise ValueError("s must be positive")
rng = np.random.default_rng(rng)
u = rng.random(n)
u = np.clip(u, np.finfo(float).tiny, 1 - np.finfo(float).eps)
return mu + s * (np.log(u) - np.log1p(-u))
def gibbs_bvn(mu_x, mu_y, sd_x, sd_y, rho, n_iter,
burn_in=500, x0=0.0, y0=0.0, rng=None):
if not (-1 < rho < 1):
raise ValueError("rho must be in (-1, 1)")
rng = np.random.default_rng(rng)
cx = sd_x * np.sqrt(1 - rho**2)
cy = sd_y * np.sqrt(1 - rho**2)
x, y = x0, y0
out = np.empty((n_iter, 2))
for t in range(burn_in + n_iter):
x = rng.normal(mu_x + rho * sd_x / sd_y * (y - mu_y), cx)
y = rng.normal(mu_y + rho * sd_y / sd_x * (x - mu_x), cy)
if t >= burn_in:
out[t - burn_in] = (x, y)
return out
def ess_ar1(chain):
c = chain - chain.mean()
r1 = np.dot(c[:-1], c[1:]) / np.dot(c, c)
return len(chain) * (1 - r1) / (1 + r1)
Complexity is O(n) for both samplers.
Common mistakes
- Using the wrong sign in the inverse CDF. Flipping the sign still gives a logistic sample by symmetry, but it breaks asymmetric checks if
μor the formula is misapplied elsewhere. - Allowing
uto hit exactly 0 or 1. - Quoting the nominal number of draws as the sample size instead of the ESS.
- Treating thinning as a way to gain accuracy.
- Using a single chain and a single KS p-value as proof of convergence.
- Forgetting that the KS test assumes independent data, which MCMC output is not.