Time-varying treatments: g-formula, marginal structural models and dynamic regimes
Time-varying confounders affected by prior treatment require careful sequential methods. Derive the g-formula, stabilized marginal structural models, dynamic regimes, and offline policy evaluation.
After this lesson you can
- Use a temporal DAG to explain confounding affected by prior treatment.
- Derive the g-formula under sequential exchangeability and positivity.
- Implement parametric g-computation by Monte Carlo simulation.
- Estimate a marginal structural model with stabilized weights and diagnose them.
- Learn a two-stage dynamic regime with Q-learning and relate it to offline RL.
Before you start
One decision changes the next situation
A team decides each week whether to escalate alerts. Accumulated workload influences the next decision and outcome; prior decisions also change that workload. Comparing only observed decision histories can confound a strategy’s effect with the situation that led to its selection.
A time-varying confounder has a double role. In a DAG with , and a cause of and , helps explain later assignment but also mediates part of the effect of . Conditioning on can block that mediation and open ; omitting it can leave confounding of . Bias depends on estimand and model: if is random, its marginal comparison is not necessarily biased merely by omitting .
The question and available history
Fix the order , where each action is chosen after observing history and . For static regime , is the potential outcome if those actions are fixed. Dynamic regime assigns and has value .
Sequential exchangeability requires, at each time, no unmeasured confounding of the current action with future regime outcomes conditional on available history. Consistency, no interference, and positivity are also needed: every action prescribed by the regime must have positive probability in histories it can reach. A temporal SWIG separates intervention-fixed values from observed random values and helps represent those conditions; it does not verify them.
Positivity is relative to population and strategy: if a regime-compatible history has positive probability, the prescribed action must be possible there. A rare pattern in a finite sample can create a practical problem even with positive population probability. In a SWIG under , fixed action parts enter descendant equations and precedes the second decision; later variables are not conditioned on to justify its assignment.
The g-formula
For discrete variables, the g-formula for a static two-decision strategy is
The proof uses iterated expectation twice: first relate the potential outcome to the observed conditional mean under the later action, then relate the intervened distribution of to that observed under . Exchangeability at each step permits substitution; consistency links the regime to corresponding observations. For continuous variables integrate instead of summing.
For example, fixing , the first application decomposes the mean over possible values of . Within each, exchangeability of allows replacing the potential-outcome mean by the mean among those with that history receiving . Exchangeability of replaces the distribution of with . Finally average over . Every replacement needs support: there is no observed mean to substitute when the relevant action never occurs in that history.
A dynamic regime substitutes with in each factor. To estimate by simulation, generate , fix , generate under that action, apply to the simulated history, and generate or average . Do not simply reuse factual for a unit whose first action changed: it belongs to another history. Parametric estimation approximates conditional distributions with models and is sensitive to misspecification.
The g-null paradox describes a specification difficulty: in certain models with treatment-affected confounders, causal-null restrictions and ordinary parametric families can be incompatible. It does not mean the g-formula is algebraically false or every test always rejects. See the review by McGrath and colleagues.
Weights along a trajectory
For a particular static strategy define
With true probabilities, consistency, sequential exchangeability, and positivity, . This population identity reconstructs the distribution under fixed action for each history using the indicator and denominator. A Horvitz–Thompson mean with known probabilities is unbiased under suitable sampling; estimating propensities or dividing by observed weight sum generally does not preserve exact finite-sample unbiasedness.
Marginal structural models describe a family of potential means and are often fitted in a weighted pseudopopulation. For the observed trajectory, one possible stabilized weight is
Each probability corresponds to the action actually observed: for it is one minus the probability of . The numerator defines a normalized reference mechanism; if it includes baseline covariates, the MSM and standardization must agree with that choice. With true mechanisms and support, . The unstabilized product of inverse observed-trajectory probabilities does not have mean one: with two positive actions at each of decisions, its expectation is . It differs from the indicator weight for a fixed strategy.
An empirical mean near one is a diagnostic, not proof of exchangeability or positivity. Examine extremes, distribution by history, and effective sample size . Truncating weights changes the estimator and may reduce spread at the cost of bias; it does not guarantee lower mean squared error in every setting. Stabilization does not guarantee ESS increases in every DGP. See Robins, Hernán and Brumback and Cole and Hernán.
If there is attrition, define as “remains observed” and when it is measured. Under conditional censoring independence and positivity among those still observed, incorporate inverse probability of remaining uncensored into the product, with the corresponding stabilizing numerator if used. A missing outcome does not become zero; censoring requires its own models and assumptions.
Choose and evaluate a rule
Dynamic treatment regimes answer “what to do given the history.” With two decisions, Q-learning estimates backward
The maximum defines the decision objective; a rule learned from finite data need not be truly optimal. Separate policy-learning and evaluation data or use cross-fitting. Near ties, the maximum operator can cause nonregular inference. A-learning models action contrasts and needs its own conditions; Q-learning is not automatically doubly robust.
In a binary stage, the A-learning contrast or blip is the difference between values of the two actions for a given history under a specified continuation. Its sign selects the action when maximizing the outcome. Instead of fitting the whole mean as in Q-learning, one can model this contrast with assignment and outcome nuisance models; guarantees depend on formulation and cannot be transferred unchecked. The connection to Q-learning in RL is the same value recursion, but actions in an observational record were not necessarily random and off-policy evaluation needs justification.
To evaluate fixed policy in another sample, define , , and . An augmented longitudinal score is
In this evaluation, is the conditional mean value of continuing with rule , not necessarily the maximum if evaluating a nonoptimal rule. With true models and the causal assumptions above, the score expectation is policy value. Robustness depends on which sequential models are correct and how they are estimated; it is not enough to declare any “one model” correct. This connects to offline policy evaluation in reinforcement learning: histories are states only if the chosen representation retains information relevant to transitions, assignment, and outcome.
Before fitting, emulate a target trial: define eligibility, time zero, strategies, follow-up, outcome, contrast, and uncertainty. Specifying order avoids, for example, assigning a strategy using information available only after initiation.
In the alert example the trial might include eligible services at the start of week zero and compare “always escalate” with “escalate when observed load exceeds a threshold.” Decide how load is measured before each action, follow-up duration, how attrition and rule deviations are handled, and final outcome. If services affect each other, no interference is doubtful and the design must change or an intervention accounting for it be defined.
NHEFS and the limits of a real comparison
Causal Inference: What If uses NHEFS to study smoking cessation and weight change. That extract represents one cessation decision in the study window and later observation; it does not contain our example’s weekly longitudinal decisions. The real-data cell estimates a one-decision comparison and separates treatment from final-observation weights. Exchangeability and selection assumptions remain substantive; the example does not by itself prove a causal conclusion.
Lab: strategies, weights, and policies
The synthetic panel has an explicit mechanism, known truth, and reproducible seed. Separate the policy-learning sample from value evaluation. NHEFS comparisons are complementary, not purported validation of repeated treatment in those data.
The first cell calculates four true means by enumeration; subsequent cells estimate transitions and average simulated outcomes. That simulation’s Monte Carlo error measures only draw noise with fixed models, not uncertainty from estimating them. The saturated MSM permits a different mean for every action pair; a marginal model without interaction would impose an additional restriction.
Longitudinal experiment with known truth
Each stage’s treatment depends on observed history; unobserved U affects workload and outcome but does not directly enter assignment after conditioning on that history. The experiment uses saturated transition and outcome tables. Truth is calculated by enumerating mechanism variables, not from estimates. Run cells in order.
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def generate(n, seed):
"""L0=B; U afecta a L1 e Y, pero no decide el tratamiento dada la historia."""
rng = np.random.default_rng(seed)
B = rng.binomial(1, .5, n)
U = rng.binomial(1, .5, n)
A0 = rng.binomial(1, sigmoid(-.2 + .5 * B))
L = rng.binomial(1, sigmoid(-1 + .6 * B + .9 * A0 + U))
A1 = rng.binomial(1, sigmoid(-.8 + .2 * B + .4 * A0 + 1.4 * L))
Y = 2 + .3 * B + .8 * L + (.4 - .9 * B) * A0 + (.8 - 1.6 * L) * A1 + 1.2 * U + rng.normal(0, .4, n)
return dict(B=B, U=U, A0=A0, L=L, A1=A1, Y=Y)
train = generate(16000, 272401)
test = generate(20000, 272402)
def true_value(rule0, rule1):
"""Enumera B, U y L en el régimen; integra el error de media cero."""
result = 0.
for b in (0, 1):
for u in (0, 1):
a0 = int(rule0(b))
pl = float(sigmoid(-1 + .6 * b + .9 * a0 + u))
for l in (0, 1):
a1 = int(rule1(b, a0, l))
mean = 2 + .3*b + .8*l + (.4-.9*b)*a0 + (.8-1.6*l)*a1 + 1.2*u
result += .25 * (pl if l else 1-pl) * mean
return result
truth = {(a0, a1): true_value(lambda b, a=a0: a, lambda b, a, l, v=a1: v)
for a0 in (0, 1) for a1 in (0, 1)}
optimal = true_value(lambda b: 1-b, lambda b, a0, l: 1-l)
print('Valor verdadero por estrategia fija:', {k: round(v, 4) for k, v in truth.items()})
print('Regla óptima: A0=1−B, A1=1−L; valor:', round(optimal, 4))
print('Muestras independientes: entrenamiento', len(train['Y']), 'evaluación', len(test['Y']))
assert np.isclose(optimal, 3.75)def fitted_tables(data):
"""Probabilidades y medias saturadas, estimadas en entrenamiento."""
b,a0,l,a1,y = [data[k] for k in ('B','A0','L','A1','Y')]
e0 = np.empty(2)
e1 = np.empty((2,2,2))
pL = np.empty((2,2))
outcome = np.empty((2,2,2,2))
for B in (0,1):
e0[B] = a0[b==B].mean()
for A in (0,1):
mask = (b==B)&(a0==A)
if mask.sum() < 10: raise ValueError('Falta soporte de entrenamiento')
pL[B,A] = l[mask].mean()
for L in (0,1):
m = mask & (l==L)
if m.sum() < 10: raise ValueError('Falta soporte de entrenamiento')
e1[B,A,L] = a1[m].mean()
for A1 in (0,1):
m2 = m & (a1==A1)
if m2.sum() < 10: raise ValueError('Falta soporte de entrenamiento')
outcome[B,A,L,A1] = y[m2].mean()
if np.any((e0<=0)|(e0>=1)) or np.any((e1<=0)|(e1>=1)):
raise ValueError('Probabilidad estimada fuera del soporte')
return e0,e1,pL,outcome
e0,e1,pL,m = fitted_tables(train)
print('Propensión A0=1 por B:', np.round(e0, 4))
print('Rango de P(A1=1|B,A0,L):', round(e1.min(), 4), round(e1.max(), 4))
print('Los modelos se ajustan sin U, no observada; A1 depende solo de la historia medida.')rg = np.random.default_rng(272403)
n_mc = 80000
bmc = rg.choice(train['B'], n_mc, replace=True)
g_est = {}
for a0 in (0,1):
lmc = rg.binomial(1, pL[bmc,a0])
for a1 in (0,1):
predictions = m[bmc,a0,lmc,a1]
g_est[a0,a1] = float(predictions.mean())
mcse = float(predictions.std(ddof=1)/np.sqrt(n_mc))
print('Estrategia', (a0,a1), 'verdad', round(truth[a0,a1],4),
'g-fórmula', round(g_est[a0,a1],4), 'EE Monte Carlo', round(mcse,4))
print('El EE Monte Carlo no incluye la incertidumbre de estimar los modelos.')b,a0,l,a1,y = [test[k] for k in ('B','A0','L','A1','Y')]
p0 = np.where(a0==1,e0[b],1-e0[b])
p1 = np.where(a1==1,e1[b,a0,l],1-e1[b,a0,l])
train_a0,train_a1 = train['A0'],train['A1']
num0_one = train_a0.mean()
num1_one = np.array([train_a1[train_a0==a].mean() for a in (0,1)])
num0 = np.where(a0==1,num0_one,1-num0_one)
num1 = np.where(a1==1,num1_one[a0],1-num1_one[a0])
sw = num0*num1/(p0*p1)
design = np.column_stack([np.ones(len(y)),a0,a1,a0*a1])
coef = np.linalg.lstsq(design * np.sqrt(sw)[:,None], y*np.sqrt(sw), rcond=None)[0]
print('Peso estabilizado medio:', round(sw.mean(),4), '| ESS:', round(sw.sum()**2/np.sum(sw**2),1))
print('Percentiles 1, 50, 99:', np.round(np.quantile(sw,[.01,.5,.99]),3))
for aa0 in (0,1):
for aa1 in (0,1):
estimate = np.array([1,aa0,aa1,aa0*aa1]) @ coef
print('MSM', (aa0,aa1), 'estimado', round(float(estimate),4), 'verdad', round(truth[aa0,aa1],4))
print('El MSM saturado tiene cuatro medias; los pesos y el modelo se estimaron fuera de evaluación.')# Dos regresiones de trabajo: ilustran contrastes condicionados diferentes.
# Ninguna está definida automáticamente como efecto de pasar de (0,0) a (1,0).
def regression_coefficient(data, adjust_l):
B,A0,A1,L,Y = [data[k] for k in ('B','A0','A1','L','Y')]
cols = [np.ones(len(Y)),B,A0,A1]
if adjust_l: cols.append(L)
return np.linalg.lstsq(np.column_stack(cols),Y,rcond=None)[0][2]
print('Contraste verdadero de regímenes (1,0) − (0,0):', round(truth[1,0]-truth[0,0],4))
print('Coeficiente A0 sin ajustar L:', round(regression_coefficient(test,False),4))
print('Coeficiente A0 ajustando L:', round(regression_coefficient(test,True),4))
print('Son contrastes de regresión, no efectos totales automáticamente comparables.')Learn and evaluate a policy
The linear implementation uses explicit basis functions and the second uses boosting. In code q2 denotes the last decision and q1 the first: they correspond respectively to and in earlier formulas. Both train on one sample and evaluate on another, with propensities fitted in training. Each learned rule’s truth is enumerated from the known mechanism; reported standard error concerns evaluation conditional on trained models.
from sklearn.ensemble import HistGradientBoostingRegressor
def features2(B,A0,L,A1):
# Función base saturada en B,A0,L, más contraste A1 que depende de L.
return np.column_stack([np.ones(len(B)),B,A0,L,B*A0,B*L,A0*L,B*A0*L,A1,A1*L])
def features1(B,A0):
return np.column_stack([np.ones(len(B)),B,A0,B*A0])
tb,ta0,tl,ta1,ty = [train[k] for k in ('B','A0','L','A1','Y')]
q2_coef = np.linalg.lstsq(features2(tb,ta0,tl,ta1), ty, rcond=None)[0]
def q2_linear(B,A0,L,A1):
return features2(B,A0,L,A1) @ q2_coef
q2_boost = HistGradientBoostingRegressor(max_iter=50, max_leaf_nodes=7,
learning_rate=.12, random_state=272404)
q2_boost.fit(np.column_stack([tb,ta0,tl,ta1]),ty)
def q2_tree(B,A0,L,A1):
return q2_boost.predict(np.column_stack([B,A0,L,A1]))
print('Q2 lineal y boosting ajustados solo en entrenamiento.')zeros,ones = np.zeros_like(ta1),np.ones_like(ta1)
target_linear = np.maximum(q2_linear(tb,ta0,tl,zeros),q2_linear(tb,ta0,tl,ones))
q1_coef = np.linalg.lstsq(features1(tb,ta0),target_linear,rcond=None)[0]
def q1_linear(B,A0): return features1(B,A0) @ q1_coef
target_tree = np.maximum(q2_tree(tb,ta0,tl,zeros),q2_tree(tb,ta0,tl,ones))
q1_boost = HistGradientBoostingRegressor(max_iter=50, max_leaf_nodes=7,
learning_rate=.12, random_state=272405)
q1_boost.fit(np.column_stack([tb,ta0]),target_tree)
def q1_tree(B,A0): return q1_boost.predict(np.column_stack([B,A0]))
print('Q1 ajustado hacia atrás, con máximo de Q2 y sin usar datos de evaluación.')def evaluate_policy(q1,q2):
B,A0,L,A1,Y = [test[k] for k in ('B','A0','L','A1','Y')]
z,o = np.zeros_like(B),np.ones_like(B)
d0 = (q1(B,o)>q1(B,z)).astype(int)
d1 = (q2(B,A0,L,o)>q2(B,A0,L,z)).astype(int)
prop0 = np.where(A0==1,e0[B],1-e0[B])
prop1 = np.where(A1==1,e1[B,A0,L],1-e1[B,A0,L])
w0 = (A0==d0)/prop0
w01 = w0*(A1==d1)/prop1
v0 = q1(B,d0)
v1 = q2(B,A0,L,d1)
score = v0 + w0*(v1-q1(B,A0)) + w01*(Y-q2(B,A0,L,A1))
ipw = w01*Y
def rule0(b):
arr=np.array([b]); return int(q1(arr,np.ones(1,dtype=int))[0] > q1(arr,np.zeros(1,dtype=int))[0])
def rule1(b,a,l):
B0,A00,L0=np.array([b]),np.array([a]),np.array([l])
return int(q2(B0,A00,L0,np.ones(1,dtype=int))[0] > q2(B0,A00,L0,np.zeros(1,dtype=int))[0])
actual = true_value(rule0,rule1)
return dict(ipw=float(ipw.mean()), aipw=float(score.mean()),
se=float(score.std(ddof=1)/np.sqrt(len(score))), true=actual,
d0=[rule0(b) for b in (0,1)],
d1=[rule1(b,a,l) for b in (0,1) for a in (0,1) for l in (0,1)])
for name,q1,q2 in [('lineal',q1_linear,q2_linear),('boosting',q1_tree,q2_tree)]:
result = evaluate_policy(q1,q2)
print(name, 'regla A0 por B:', result['d0'], 'reglas A1 por B,A0,L:', result['d1'])
print('Valor verdadero de la regla:', round(result['true'],4),
'| IPW:', round(result['ipw'],4), '| AIPW:', round(result['aipw'],4),
'| EE de evaluación condicional a la regla:', round(result['se'],4))
print('El óptimo del modelo vale', round(optimal,4), '; su comparación no demuestra optimalidad general.')
print('La puntuación AIPW longitudinal usa el producto de propensiones y residuos en ambas etapas.')One observed decision: NHEFS
Download the NHEFS extract from a versioned mirror of the book’s data. The comparison includes one-window treatments, not repeated decision histories. Treatment and observation models use baseline covariates; causal interpretation needs additional assumptions. Weighted differences depend on specification and are not a randomized trial.
import io
import pandas as pd
from pyodide.http import pyfetch
# Espejo de causallib fijado a un commit; datos del libro What If.
url = ('https://raw.githubusercontent.com/BiomedSciAI/causallib/'
'de64cf65d0e2fa1cc5a12d2cc847c970fc43a717/'
'causallib/datasets/data/nhefs/NHEFS.csv')
respuesta = await pyfetch(url)
if not respuesta.ok:
raise RuntimeError(f'Descarga NHEFS: HTTP {respuesta.status}')
nhefs = pd.read_csv(io.StringIO(await respuesta.string()))
assert nhefs.shape == (1629, 64)
assert nhefs.seqn.is_unique
print('Participantes:', len(nhefs), 'peso final observado:', nhefs.wt82_71.notna().sum())
print('Cambio de peso observado por qsmk:')
print(nhefs.groupby('qsmk').wt82_71.agg(['count', 'mean']).round(4))import numpy as np
from scipy.special import expit
def logistica_newton(X, y):
X, y = np.asarray(X, float), np.asarray(y, float)
beta = np.zeros(X.shape[1])
for it in range(100):
p = expit(X @ beta)
paso = np.linalg.solve(X.T @ ((p*(1-p))[:, None]*X), X.T @ (y-p))
beta += paso
if np.max(np.abs(paso)) < 1e-9:
return beta, it+1
raise RuntimeError('La regresión logística no convergió')
print('NumPy y función logística cargados')# Restricción inicial explícita: las variables pretratamiento usadas aquí
# están completas en este extracto. El resultado final falta en 63 filas.
campos = ['qsmk', 'sex', 'race', 'age', 'wt71', 'smokeintensity',
'smokeyrs', 'education', 'exercise', 'active']
assert not nhefs[campos].isna().any().any()
L = pd.DataFrame({'constante': np.ones(len(nhefs)),
'sex': nhefs.sex, 'race': nhefs.race})
for nombre in ['age', 'wt71', 'smokeintensity', 'smokeyrs']:
# Reescalar no cambia el espacio lineal del modelo cuadrático.
z = (nhefs[nombre] - nhefs[nombre].mean()) / nhefs[nombre].std()
L[nombre] = z
L[nombre + '_2'] = z*z
for nombre, niveles in [('education', [2, 3, 4, 5]),
('exercise', [1, 2]), ('active', [1, 2])]:
for nivel in niveles:
L[f'{nombre}_{nivel}'] = (nhefs[nombre] == nivel).astype(float)
assert np.linalg.matrix_rank(L.to_numpy()) == L.shape[1]
A = nhefs.qsmk.to_numpy(dtype=float)
R = nhefs.wt82_71.notna().to_numpy(dtype=int)
coef_a, iter_a = logistica_newton(L, A)
e = expit(L.to_numpy() @ coef_a)
Lc = L.copy()
Lc['qsmk'] = A
assert np.all((e > 0) & (e < 1))
print('Propensión estimada: min, mediana, max', np.round(np.quantile(e, [0, .5, 1]), 4))
print('Iteraciones Newton tratamiento:', iter_a)coef_r, iter_r = logistica_newton(Lc, R)
r = expit(Lc.to_numpy() @ coef_r)
assert np.all((r > 0) & (r < 1))
print('Probabilidad de peso observado: min, mediana, max', np.round(np.quantile(r, [0, .5, 1]), 4))
print('Iteraciones Newton observación:', iter_r)observados = R == 1
Y = nhefs.wt82_71.to_numpy()
# Numerador del tratamiento: distribución marginal en la muestra completa.
p = A.mean()
wa = np.where(A == 1, p/e, (1-p)/(1-e))
# Numerador de observación dado tratamiento, para conservar su distribución.
pr = np.array([R[A == a].mean() for a in (0, 1)])
wc = pr[A.astype(int)]/r
def medias_ponderadas(w):
return np.array([np.average(Y[observados & (A == a)],
weights=w[observados & (A == a)])
for a in (0, 1)])
for nombre, w in [('Sin ajustar', np.ones(len(A))),
('Solo tratamiento', wa), ('Tratamiento y observación', wa*wc)]:
medias = medias_ponderadas(w)
wo = w[observados]
ess = wo.sum()**2 / (wo @ wo)
print(nombre, 'medias control/tratamiento:', np.round(medias, 4),
'diferencia:', round(medias[1]-medias[0], 4),
'ESS observados:', round(ess, 1))
print('Pesos tratamiento, media/min/max:', np.round([wa.mean(), wa.min(), wa.max()], 4))
print('Peso combinado entre observados, media/min/max:',
np.round([(wa*wc)[observados].mean(), (wa*wc)[observados].min(),
(wa*wc)[observados].max()], 4))
# WLS saturada en tratamiento coincide con diferencia de medias ponderadas.
X = np.column_stack([np.ones(observados.sum()), A[observados]])
W = (wa*wc)[observados]
beta_wls = np.linalg.solve(X.T @ (W[:, None]*X), X.T @ (W*Y[observados]))
assert np.allclose(beta_wls[1], np.diff(medias_ponderadas(wa*wc))[0], atol=1e-9)
print('Contraste WLS igual a diferencia ponderada:', round(beta_wls[1], 4))Comparison with statsmodels checks both logistic fits on the same design. Numerical agreement verifies implementation, not validity of causal assumptions.
from statsmodels.discrete.discrete_model import Logit
print('Modelo logístico de statsmodels disponible')ref_a = Logit(A, L).fit(disp=False, maxiter=100)
if not ref_a.mle_retvals['converged']:
raise RuntimeError('El ajuste de tratamiento de statsmodels no convergió')
np.testing.assert_allclose(e, ref_a.predict(L), atol=1e-9, rtol=0)
print('Coinciden las propensiones de tratamiento con statsmodels.')ref_r = Logit(R, Lc).fit(disp=False, maxiter=100)
if not ref_r.mle_retvals['converged']:
raise RuntimeError('El ajuste de observación de statsmodels no convergió')
np.testing.assert_allclose(r, ref_r.predict(Lc), atol=1e-9, rtol=0)
print('Coinciden las probabilidades de observación con statsmodels.')Exercises
Step 1 of 3. Which distribution of L₁ is needed under the fixed first action?
Step 1 of 3. What does the last-decision factor do inside an expectation conditional on H₁?
def stabilized_weights(df, id, time, treatment, confounders):
"""Ajusta propensiones binarias y devuelve el peso acumulado por fila."""
raise NotImplementedErrorCheck both products after attempting the exercises:
from math import prod
denominador = [.8, .5, .25]
numerador = [.6, .5, .4]
peso_no_estabilizado = 1 / prod(denominador)
peso_estabilizado = prod(numerador) / prod(denominador)
assert abs(peso_no_estabilizado-10) < 1e-12
assert abs(peso_estabilizado-1.2) < 1e-12
print('Pesos de la trayectoria:', peso_no_estabilizado, peso_estabilizado)