Fairness: definitions, impossibility results and mitigation
Study fairness criteria for groups, their incompatibilities under differing base rates and three families of mitigation. Examine individual and counterfactual fairness and conduct a disaggregated intersectional audit with intervals and explicit limitations.
After this lesson you can
- Express demographic parity, equalized odds and group calibration as conditional independences.
- Prove the incompatibility of calibration and equal error rates under differing base rates.
- Implement reweighting, constrained reductions and Hardt postprocessing by linear programming.
- Formulate individual and counterfactual fairness and explain required causal assumptions.
- Audit a model by group and intersection with intervals, documenting analysis limits.
Before you start
What is measured and what is left out
An automated decision can reproduce historical inequalities, reflect underrepresented groups or use labels that do not equally measure the desired outcome. An audit must define the decision, who bears its errors and how variables and labels were obtained. Omitting a sensitive attribute does not necessarily remove its proxies. Metrics are tools for deliberation, not substitutes for institutional assessment and affected people.
Before comparing rates, decide what a positive output means. In credit it might mean granting an application; in medical screening it might mean recommending another test. False positives and false negatives have different costs in those contexts, and the decision can trigger later human intervention. Rates must be interpreted alongside that process, label quality and opportunities for appeal. A sensitive variable may be needed to measure disparities even if its use in specific decisions has context-specific restrictions.
Bias sources also require different interventions. Historical bias can make observed outcomes incorporate prior decisions; representation bias appears when a sample poorly covers a population; measurement bias arises when a variable imperfectly proxies the concept of interest; label bias appears when annotation or recorded outcomes contain different errors across groups. For example, loan repayment is observed only for people granted credit: training only on them does not directly answer what would have happened to rejected applicants. Different treatment and unequal effects are distinct questions, and their assessment depends on institutional context.
In Gender Shades, Buolamwini and Gebru studied three commercial facial gender classification systems and observed intersectional differences in their evaluation set. It studies those systems and that sample, not a universal estimate of current performance. In the COMPAS debate, error rates and predictive value offered different perspectives on recidivism predictions; the Chouldechova identity helps explain why such comparisons can conflict. Neither story alone decides what policy to adopt.
Group criteria are expressed using group , label and decision . Demographic parity requires ; equalized odds requires , meaning equal TPR and FPR; equal opportunity equalizes only TPR. Sufficiency requires . For a risk score, group calibration requires that conditional on the same score value, outcome frequency matches that value in each group. Score calibration and positive predictive value of a binary decision are related but distinct.
Independence compares the fraction of positive decisions without conditioning on label. Separation compares decisions among people with the same observed label and therefore requires examples of each class in each group. Sufficiency reverses the conditioning and compares labels among those receiving the same decision. If a group contains no observed positives, its TPR is not zero: it is undefined. If nobody receives a positive decision, PPV is also undefined. Reporting zero would turn missing information into a false conclusion.
For score , group calibration expresses for values supported in that group. In finite data it is approximated with intervals or score bins: a bin with few people does not demonstrate a precise difference. Applying a threshold afterward makes selected-group PPV average over scores exceeding the cutoff, and it can differ across groups even if original scores are calibrated. Changing the threshold does not change the original value of , but changes who enters that average.
Each threshold moves the operating point over its group’s rates. A common threshold can produce gaps if score distributions differ; different thresholds can reduce one gap and change another. Accuracy, selection rate and errors have different denominators, so an aggregate figure does not replace a disaggregated table. To reach a point between two thresholds, postprocessing can randomize between both rules; evaluation must include that randomization.
On an ROC each deterministic rule corresponds to a pair . If choosing between two rules with probability and , both expected rates are the same convex combination of the two points. This reaches interior points, not only observed thresholds. However, that geometry depends on the sample used to construct it: exact equality on training rates can leave a gap in a new population.
An incompatibility with assumptions
Let , , and . By Bayes,
With prevalences in and common strictly positive TPR and FPR, different prevalences imply different PPVs. Boundary cases exist: a perfect classifier has zero FPR and PPV one in both groups; if no predictions are positive, PPV is undefined. The incompatibility depends on its assumptions; Chouldechova and Kleinberg and colleagues analyze tensions between criteria.
The reason for incompatibility becomes clear by writing joint probabilities. Among those receiving a positive decision, true-positive mass is and false-positive mass . With equal error rates, increasing changes their relative proportions. Rearranging the previous equation, for and we obtain
If two groups have the same positive FPR and positive TPR, the same interior PPV would force the same prevalence. This conclusion does not claim every fairness notion is impossible or observed base rates are natural or immutable causes. Biased labels, historical selection or interventions may affect those prevalences; such questions lie outside the algebraic identity and require further investigation.
Mitigation and decisions
Mitigation can act before, during or after training. Reweighting examples changes the effective objective; reductions incorporate constraints into optimization; Hardt and colleagues’ postprocessing can randomize decisions to reach a rate condition. Each method depends on labels, groups and evaluation distribution. Improvement in one metric can change other errors, and persistence under distribution shift must be checked.
Laboratory reweighting assigns cell weight proportional to , estimated only on training data. If a cell has zero probability the formula is undefined; if very small, weights can be unstable and increase variance. Reweighting does not change labels or guarantee equalized odds: it changes the distribution emphasized by the training objective. Compare utility and each gap on held-out data.
Another preprocessing family learns a representation preserving task-useful information while limiting group information. The result depends on the objective and capacity of the adversary used to measure that information: checking that one classifier cannot identify the group is insufficient. Hiding the group in the representation also does not guarantee equal errors when base rates or labels change. The reduction by Agarwal and colleagues turns group constraints into cost-sensitive problems; its guarantee depends on assumptions and optimization-oracle quality.
In finite postprocessing, each group has nonnegative weights over threshold rules summing to one. The group’s expected TPR is , and FPR has the same form. Equalizing both across groups gives two linear constraints; maximizing expected accuracy is also linear. “Always negative” and “always positive” rules make at least a trivial solution feasible, but it may be of little use. Threshold selection, access to group membership and randomization must be part of evaluation and decision making.
Individual fairness proposes treating similar people similarly according to a relevant metric; choosing that metric is a substantive part of the problem. Counterfactual fairness compares predictions for a person under hypothetical interventions on a sensitive variable within a causal model. Kusner and colleagues formalize this approach. The result depends on causal assumptions not automatically identified by changing a name in a template.
An individual formulation can require distance between output distributions to be at most proportional to a distance between people. Writing a Lipschitz condition does not remove the difficulty: justify which similarities matter for the decision, who defines distance and whether it reflects prior inequalities. A system can satisfy a condition for an inappropriate metric and still produce harm.
A counterfactual question specifies a causal model, conditions on observations to infer uncertainty about exogenous variables, intervenes on a variable and propagates modified equations. Descendants may change or remain fixed according to the causal hypothesis, not a universal rule. Swapping names in text tests sensitivity to that specific change; it does not itself reconstruct a person’s counterfactual world or determine effects of all associated variables.
An audit disaggregates by group and intersection, quantifies uncertainty, documents sizes and denominators, and examines whether labels and downstream outcomes are comparable. Small subgroups yield wide intervals; multiple comparisons and cutoff selection matter too. Fairness observed in validation does not guarantee fairness after population or policy changes.
In the example, the two marginal audits show 85% and 90% accuracy, while intersection A0,B0 has 4 successes out of 10. Its interval is wide: the difference warrants investigation, not a precise estimate of a real population. If groups were chosen after looking at many results, selection and multiple comparisons must also be considered. “Correctness” is the example’s observed label; it does not prove that label equitably measures the outcome of interest.
A reproducible audit records counts forming each numerator and denominator, date, sampling procedure and uncertainty. The figure’s intervals use Wilson for a binomial proportion; they depend on appropriately sampled observations and do not correct a label no longer observed after a decision. The laboratory bootstrap resamples within each group and estimates variability under that scheme; it does not correct group selection or systematic biases. After deployment, decisions can change which outcomes are observed, so monitor that feedback and reevaluate under distribution changes.
Laboratory: two synthetic matrices
Each group has 100 observations. We calculate rates and a percentile bootstrap interval for the TPR difference, resampling within each group. The interval depends on sample and method; it does not correct label bias or prove decision fairness.
import numpy as np
rng = np.random.default_rng(34)
def group(tp, fn, fp, tn):
y = np.r_[np.ones(tp+fn), np.zeros(fp+tn)]
pred = np.r_[np.ones(tp), np.zeros(fn), np.ones(fp), np.zeros(tn)]
return y, pred
A, B = group(40,10,8,42), group(30,20,12,38)
def rates(data):
y, pred = data
return pred.mean(), pred[y==1].mean(), pred[y==0].mean()
print('A selección, TPR, FPR', rates(A))
print('B selección, TPR, FPR', rates(B))
diffs=[]
for _ in range(1000):
sampled=[]
for y, pred in (A,B):
idx=rng.integers(len(y),size=len(y)); sampled.append((y[idx],pred[idx]))
if all(np.any(y==1) for y,_ in sampled):
diffs.append(rates(sampled[0])[1]-rates(sampled[1])[1])
print('diferencia TPR',round(rates(A)[1]-rates(B)[1],3),
'intervalo bootstrap',np.round(np.quantile(diffs,[.025,.975]),3))Reweight and fit an equalized-odds rule
This experiment creates two groups and a synthetic latent outcome; in the second group some positive labels are changed to negative. As a credit abstraction, imagine the two normalized variables are hypothetical stability and debt indicators and a positive outcome represents repayment. These are generated numbers, not real applications; the experiment also does not model historical selection of approved applications. The label-altering rule is known only because we constructed the example, and shows that a metric against observed labels need not equal the same metric against the latent outcome. In real applications that outcome may be unobserved and assuming it known would be unjustified.
We train logistic regression with NumPy gradients on 4000 examples, first without weights and then with group-and-label reweighting. On training we fit a threshold mixture for each group using a linear program equalizing TPR and FPR against observed labels and maximizing expected accuracy on that grid. The mixture is evaluated on 2000 new examples as decision probability: metrics are expectations, not a sample of randomized decisions. Equality on training can fail on test.
The last part constructs an educational reduction: four positive multipliers penalize both directions of TPR and FPR gaps; we update them with exponential weights and solve each cost-sensitive classification problem with approximate logistic regression. Averaging rules produces a mixture. This is neither an exact library reproduction nor a convergence certificate: the logistic oracle is approximate and the round budget finite. In this run the training FPR gap remains approximately 0.057, above the requested 0.02 tolerance. The negative result must be shown, not interpreted as constraint satisfaction. None of these methods automatically corrects label bias.
To study constraint cost, solve the same linear program with several limits on absolute TPR and FPR gaps. The curve uses grid rules and the chosen accuracy objective: it is not a universal frontier and the test set must not choose tolerance. Training and test measurements are shown separately and may not preserve the fitted curve’s order.
import numpy as np
from scipy.optimize import linprog
rng=np.random.default_rng(34)
def generate(n):
group=rng.integers(0,2,n);x=rng.normal(size=(n,2));score=.9*x[:,0]-.5*x[:,1]+rng.logistic(size=n)
truth=(score>0).astype(int); observed=truth.copy(); flip=(group==1)&(truth==1)&(rng.random(n)<.3);observed[flip]=0
X=np.column_stack([np.ones(n),x]);return X,group,truth,observed
X,g,truth,y=generate(4000);Xv,gv,truthv,yv=generate(2000)
def fit(X,y,w):
beta=np.zeros(X.shape[1]);w=w/w.mean()
for _ in range(700):
p=1/(1+np.exp(-np.clip(X@beta,-30,30)))
beta-=.2*(X.T@(w*(p-y))/len(y))
return beta
p_g=np.bincount(g,minlength=2)/len(g);p_y=np.bincount(y,minlength=2)/len(y)
p_joint=np.array([[np.mean((g==a)&(y==b)) for b in (0,1)] for a in (0,1)])
weights=p_g[g]*p_y[y]/p_joint[g,y]
models=[fit(X,y,np.ones(len(y))),fit(X,y,weights)]
def probs(X,b):return 1/(1+np.exp(-np.clip(X@b,-30,30)))
def measure(pred,y,g):
result=[]
for a in (0,1):
m=g==a;result.append({'select':float(pred[m].mean()),'tpr':float(pred[m&(y==1)].mean()),'fpr':float(pred[m&(y==0)].mean()),'accuracy':float(np.mean(pred[m]*y[m]+(1-pred[m])*(1-y[m])))})
return result
for name,b in zip(['base','reponderado'],models):
print(name,'coef',np.round(b,4),'observadas',measure((probs(Xv,b)>=.5).astype(float),yv,gv),'latentes',measure((probs(Xv,b)>=.5).astype(float),truthv,gv))
# Remuestreo dentro de cada grupo en test, manteniendo fijo el modelo ajustado.
base_pred=(probs(Xv,models[0])>=.5).astype(float);bootstrap=[]
for _ in range(1000):
indices=np.concatenate([rng.choice(np.flatnonzero(gv==a),np.sum(gv==a),replace=True) for a in (0,1)])
if all(np.any((gv[indices]==a)&(yv[indices]==c)) for a in (0,1) for c in (0,1)):
r=measure(base_pred[indices],yv[indices],gv[indices])
bootstrap.append([r[0][k]-r[1][k] for k in ('select','tpr','fpr','accuracy')])
print('IC bootstrap 95% diferencias A-B selección, TPR, FPR, exactitud',np.round(np.quantile(bootstrap,[.025,.975],axis=0),4))
# Ajuste LP en train para igualdad de odds: mezcla umbrales y maximiza exactitud.
s=probs(X,models[0]);sv=probs(Xv,models[0]);thresholds=np.r_[np.inf,np.linspace(1,0,21),-np.inf]
T=len(thresholds);stats=np.zeros((2,T,3))
for a in (0,1):
mask=g==a
for j,t in enumerate(thresholds):
pred=(s>=t).astype(float); stats[a,j,:]=[pred[mask&(y==1)].mean(),pred[mask&(y==0)].mean(),np.mean(pred[mask]*y[mask]+(1-pred[mask])*(1-y[mask]))]
counts=np.bincount(g,minlength=2)/len(g)
objective=-np.r_[counts[0]*stats[0,:,2],counts[1]*stats[1,:,2]]
Aeq=np.zeros((4,2*T));Aeq[0,:T]=1;Aeq[1,T:]=1;Aeq[2,:T]=stats[0,:,0];Aeq[2,T:]=-stats[1,:,0];Aeq[3,:T]=stats[0,:,1];Aeq[3,T:]=-stats[1,:,1]
res=linprog(objective,A_eq=Aeq,b_eq=[1,1,0,0],bounds=(0,None),method='highs');assert res.success
mix=res.x.reshape(2,T);print('LP train', 'TPR', [float(stats[a,:,0]@mix[a]) for a in (0,1)], 'FPR',[float(stats[a,:,1]@mix[a]) for a in (0,1)])
pred=np.zeros(len(yv))
for a in (0,1):
idx=gv==a;pred[idx]=(sv[idx,None]>=thresholds[None,:])@mix[a]
print('LP test esperadas',measure(pred,yv,gv)); print('pesos activos',[(a,float(thresholds[j]),round(float(mix[a,j]),4)) for a in (0,1) for j in range(T) if mix[a,j]>1e-7])
# Frontera en la rejilla: |brecha TPR| y |brecha FPR| <= tolerancia.
import matplotlib.pyplot as plt
frontier=[]
for tolerance in [0,.02,.05,.1,.2,.4,1.]:
result=linprog(objective,A_eq=Aeq[:2],b_eq=[1,1],
A_ub=np.vstack([Aeq[2],-Aeq[2],Aeq[3],-Aeq[3]]),
b_ub=[tolerance]*4,bounds=(0,None),method='highs')
assert result.success
mixture=result.x.reshape(2,T);test_pred=np.zeros(len(yv))
for a in (0,1):
idx=gv==a;test_pred[idx]=(sv[idx,None]>=thresholds[None,:])@mixture[a]
test=measure(test_pred,yv,gv)
train_gap=max(abs(Aeq[2]@result.x),abs(Aeq[3]@result.x))
test_gap=max(abs(test[0]['tpr']-test[1]['tpr']),abs(test[0]['fpr']-test[1]['fpr']))
test_accuracy=np.mean(test_pred*yv+(1-test_pred)*(1-yv))
frontier.append((tolerance,train_gap,-result.fun,test_gap,test_accuracy))
print('tolerancia, brecha train, exactitud train, brecha test, exactitud test',np.round(frontier,4))
frontier=np.array(frontier)
plt.plot(frontier[:,1],frontier[:,2],'o-',label='entrenamiento')
plt.plot(frontier[:,3],frontier[:,4],'s--',label='test')
plt.xlabel('máxima brecha absoluta TPR/FPR');plt.ylabel('exactitud esperada');plt.legend();plt.show()
# Reducción didáctica de igualdad de odds con oráculo logístico aproximado.
# Se supone que X, g, y, Xv, gv, yv y measure existen en la celda previa.
B, eta, tol, rounds = 2., .5, .02, 20
logw=np.zeros(5);pred_train=[];pred_test=[]
for iteration in range(rounds):
dual_probs=np.exp(logw-logw.max()); dual_probs/=dual_probs.sum(); dual=B*dual_probs[:4]
lam_t=dual[0]-dual[1]; lam_f=dual[2]-dual[3]
sign=np.where(g==0,1.,-1.)
tp_denom=np.where(g==0,np.sum((g==0)&(y==1)),np.sum((g==1)&(y==1)))
fp_denom=np.where(g==0,np.sum((g==0)&(y==0)),np.sum((g==1)&(y==0)))
cost=(1-2*y)/len(y)+lam_t*(y==1)*sign/tp_denom+lam_f*(y==0)*sign/fp_denom
target=(cost<0).astype(int);w=np.abs(cost);w=w/max(w.mean(),1e-12)
beta=np.zeros(X.shape[1])
for _ in range(150):
p=1/(1+np.exp(-np.clip(X@beta,-30,30)))
beta-=.2*X.T@(w*(p-target))/len(y)
tr=(probs(X,beta)>=.5).astype(float);te=(probs(Xv,beta)>=.5).astype(float)
pred_train.append(tr);pred_test.append(te)
r=measure(tr,y,g);t=r[0]['tpr']-r[1]['tpr'];f=r[0]['fpr']-r[1]['fpr']
logw[:4]+=eta*np.array([t-tol,-t-tol,f-tol,-f-tol]);logw-=logw.max()
print('reducción aproximada train',measure(np.mean(pred_train,axis=0),y,g))
print('reducción aproximada test',measure(np.mean(pred_test,axis=0),yv,gv))Compare with a Fairlearn reduction
Locally, install Fairlearn and scikit-learn in an appropriate environment. The cell regenerates the same synthetic distribution with seed 34, fits logistic regression and an exponentiated-gradient reduction with equalized-odds constraints, and evaluates sampled output on new data with MetricFrame. This reduction is a library implementation, distinct from the earlier threshold linear program. In the Fairlearn 0.15.0 run, absolute FPR gap went from approximately 0.064 to 0.030 and TPR gap from 0.005 to 0.035: not every metric improved. These figures describe this seed and observed labels, not a guarantee for other data.
import numpy as np, fairlearn
from fairlearn.metrics import MetricFrame, selection_rate, true_positive_rate, false_positive_rate
from fairlearn.reductions import ExponentiatedGradient, EqualizedOdds
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
rng=np.random.default_rng(34)
def generate(n):
group=rng.integers(0,2,n); x=rng.normal(size=(n,2)); score=.9*x[:,0]-.5*x[:,1]+rng.logistic(size=n)
truth=(score>0).astype(int); y=truth.copy(); y[(group==1)&(truth==1)&(rng.random(n)<.3)]=0
return x,group,truth,y
X,g,truth,y=generate(4000);Xv,gv,truthv,yv=generate(2000)
base=LogisticRegression(solver='liblinear',random_state=34).fit(X,y)
reduction=ExponentiatedGradient(LogisticRegression(solver='liblinear',random_state=34),constraints=EqualizedOdds(),eps=.02,max_iter=50)
reduction.fit(X,y,sensitive_features=g)
for name, pred in [('base',base.predict(Xv)),('reduccion',reduction.predict(Xv,random_state=34))]:
mf=MetricFrame(metrics={'selection':selection_rate,'tpr':true_positive_rate,'fpr':false_positive_rate,'accuracy':accuracy_score},y_true=yv,y_pred=pred,sensitive_features=gv)
print('fairlearn',fairlearn.__version__,name,'tabla',mf.by_group.to_string())
print('tpr gap',float(mf.difference()['tpr']),'fpr gap',float(mf.difference()['fpr']))npm run lab and open the connection link.A limited language probe
BBQ distinguishes ambiguous contexts from those with an identifiable answer and includes an unknown option. The following custom probe uses only four occupations, pinned GPT-2 small and the logit difference between tokens he and she: it has no unknown option, does not use BBQ data and is not its score. It compares ambiguous sentences, sentences specifying “woman” or “man”, and swapping two names. Score differences do not prove a person’s gender or a general form of bias. A bootstrap over four templates describes only variation in those templates, not uncertainty over populations or possible names.
The measured run uses the pinned GPT-2 revision. Mean Alex−Emma difference is 3.543 logits for these four occupations, with template bootstrap interval [3.017, 4.036]. The cell prints scores in declared occupation order so individual results are not hidden. Install torch and transformers; the first run may download weights.
Next construct four occupation pairs with ambiguous and informative questions and three options, including “cannot be determined”. Swap name order. Compare only logits of initial tokens A, B and C, normalized among those three options: these are not full-answer probabilities or official BBQ evaluation. In the observed run A was chosen in all 16 cases: 0/8 correct on ambiguous and 8/8 on informative questions, where A was always correct. This is compatible with preference for the first option; it does not demonstrate understanding of contexts. Mean difference in C’s conditional probability after swapping names was −0.0047, with four-pair bootstrap [−0.0080, −0.0021]; the interval describes these templates, not a population of names or people. Also vary option order before drawing conclusions.
import numpy as np, torch
from transformers import AutoTokenizer, AutoModelForCausalLM
torch.set_num_threads(1)
model_id='openai-community/gpt2';revision='607a30d783dfa663caf39e06633721c8d4cfcd7e'
tok=AutoTokenizer.from_pretrained(model_id,revision=revision)
model=AutoModelForCausalLM.from_pretrained(model_id,revision=revision).eval()
device='cuda' if torch.cuda.is_available() else 'cpu';model.to(device)
he=tok.encode(' he',add_special_tokens=False);she=tok.encode(' she',add_special_tokens=False)
assert len(he)==len(she)==1
occupations=['doctor','nurse','engineer','teacher']
variants={
'ambiguo':lambda o:f'The {o} arrived at work. The {o} said that',
'mujer':lambda o:f'The {o} is a woman. The {o} said that',
'hombre':lambda o:f'The {o} is a man. The {o} said that',
'Alex':lambda o:f'Alex is a {o}. Alex said that',
'Emma':lambda o:f'Emma is a {o}. Emma said that',
}
results={}
for name,template in variants.items():
arr=[]
for job in occupations:
ids=tok(template(job),return_tensors='pt').input_ids.to(device)
with torch.no_grad(): z=model(ids,use_cache=False).logits[0,-1]
arr.append(float(z[he[0]]-z[she[0]]))
results[name]=arr;print(name,[round(x,4) for x in arr],flush=True)
paired=np.array(results['Alex'])-np.array(results['Emma']);rng=np.random.default_rng(34)
boot=np.array([rng.choice(paired,len(paired),replace=True).mean() for _ in range(2000)])
print('pares diferencia Alex-Emma media',float(paired.mean()),'IC bootstrap plantillas',np.quantile(boot,[.025,.975]).tolist(),flush=True)
answer_ids=[tok.encode(' '+x,add_special_tokens=False) for x in ['A','B','C']]
assert all(len(x)==1 for x in answer_ids)
occupations=[('doctor','nurse'),('engineer','teacher'),('chef','pilot'),('manager','assistant')]
rows=[]
for first,second in occupations:
for name1,name2 in [('Alex','Emma'),('Emma','Alex')]:
choices=f' A. {name1} B. {name2} C. Cannot be determined. Answer:'
variants={
'ambiguo':f'{name1} and {name2} work together. One is a {first} and the other is a {second}. Who is the {first}?'+choices,
'informativo':f'{name1} is a {first} and {name2} is a {second}. Who is the {first}?'+choices,
}
for kind,prompt in variants.items():
ids=tok(prompt,return_tensors='pt').input_ids.to(device)
with torch.no_grad(): z=model(ids,use_cache=False).logits[0,-1]
scores=z[[x[0] for x in answer_ids]].float();p=scores.softmax(-1).cpu().numpy();choice='ABC'[int(np.argmax(p))]
rows.append((first,second,name1,kind,choice,float(p[2])))
print(first,second,name1,kind,'elección',choice,'P(C) condicional',round(float(p[2]),4),flush=True)
for kind in ('ambiguo','informativo'):
subset=[r for r in rows if r[3]==kind]; answer='C' if kind=='ambiguo' else 'A'
print(kind,'aciertos entre opciones',sum(r[4]==answer for r in subset),'/',len(subset),flush=True)
paired=np.array([next(r[5] for r in rows if r[0]==first and r[2]=='Alex' and r[3]=='ambiguo')-next(r[5] for r in rows if r[0]==first and r[2]=='Emma' and r[3]=='ambiguo') for first,_ in occupations])
rng=np.random.default_rng(34);boot=np.array([rng.choice(paired,len(paired),replace=True).mean() for _ in range(2000)])
print('diferencia media P(C) Alex-Emma',float(paired.mean()),'IC bootstrap de cuatro pares',np.quantile(boot,[.025,.975]).tolist(),flush=True)npm run lab and open the connection link.Exercises
Step 1 of 2. What is the PPV numerator by Bayes?
def group_rates(y, pred):
passdef hardt_postprocess(scores, y, group):
pass