Statistical significance in ML II: many models, many tasks, few seeds
Comparing k methods on N tasks requires aggregating different scales, controlling multiplicity, and drawing conclusions with few runs per task. Study Friedman and post hoc comparisons, critical-difference diagrams, Bayesian signed-rank comparison with ROPE, robust rliable aggregates, stratified bootstrap, and Dolan-Moré performance profiles.
After this lesson you can
- Apply Friedman and a Holm-corrected post hoc test and draw a critical-difference diagram.
- Explain limitations of mean-rank post hoc tests and prefer direct paired comparisons for specific pairs.
- Perform a Bayesian signed-rank comparison with a ROPE and interpret the probability simplex.
- Calculate IQM, optimality gap, performance profiles, and improvement probability with stratified-bootstrap intervals.
- Choose task aggregation robust to outliers and transparent about few seeds.
Before you start
A ranking for 26 games
Two methods can exchange first place when a few seeds change. With one score per method and game, you cannot tell how much ranking is signal and how much is run variability. Agarwal and colleagues studied this problem in Atari 100k and proposed intervals, profiles, and robust aggregates. Their rliable library implements these tools. Here we use another public matrix of individual Atari 100k runs, not their original study’s results.
The matrix comes from Simulus, per-run results: four methods, 26 games, and five runs per game and method. These data were published by the repository authors; they are not trainings performed for this lesson. Seed columns are not considered paired across methods without evidence of pairing. The same repository’s RANDOM and HUMAN tables define the normalization denominator.
What gets averaged
Multi-dataset comparison treats each task as a block for rank tests. Atari uses different scales: a point in Pong is not a point in Breakout. A common higher-is-better normalization is , with random reference and human reference for each game. Zero corresponds to the random reference and one to human when ; negative values or values above one are possible and are not clipped. Reference choice affects aggregation; if is close to , the denominator can amplify noise.
The estimand changes if you first average seeds per task and then aggregate 26 means, or aggregate all 130 runs. With five runs per game, the overall mean agrees both ways, but median and IQM need not. If runs are missing, the mean of all runs weights better-represented games more heavily. Decide whether each game or each run receives equal weight and show run counts per task.
Ranks, Friedman, and critical differences
For each task assign rank 1 to the largest result and average ranks for ties. With methods and tasks, let be method ‘s mean rank. Without ties, Friedman’s statistic is
The asymptotic reference is approximate and requires appropriately independent blocks and comparable procedures within each block. Ties require correction. An overall rejection does not identify differing pairs. For pairwise comparisons, calculate a paired task test and adjust the p-value family: Holm orders and compares sequentially with , stopping at the first nonrejection. It controls familywise error when each test is valid, without requiring independence between tests.
A critical-difference diagram places mean ranks on an axis. Nemenyi post hoc compares their distance with , where is the studentized-range quantile divided by . This differs from pairwise Wilcoxon with Holm. A line joining nonrejected methods does not establish equivalence; nonrejection is not transitive. With ties or few tasks, check the correction and approximation’s scope.
A pair’s rank also depends on other methods: inserting one between A and B can change their mean-rank difference even if A and B do not change. This is one reason to prefer direct paired task comparisons with multiplicity correction when the question concerns a specific pair; see Benavoli, Corani, and Mangili. The classic Friedman and CD-diagram proposal is by Demšar. Do not mix a Nemenyi threshold with Holm-calculated links and call them the same test.
Robust average
IQM and other robust aggregates address the influence of extreme tasks. Sort values and remove the lowest and highest 25%; the mean of the rest is the interquartile mean (IQM). For sizes not divisible by four, state the convention. scipy.stats.trim_mean removes values from each end. The mean uses all values but one arbitrarily large observation can shift it without bound. The median resists more extremes but ignores the magnitude of much of the data.
In a finite sample of distinct values, replacing more than the trimmed fraction at one end lets an untrimmed value go to infinity. Thus IQM’s asymptotic breakdown point is 25%, not the median’s 50%. Robustness does not imply narrower IQM intervals in every case: efficiency depends on distribution, run count, and estimand. In the figure IQM applies to 26 per-game means, while the lab also calculates IQM of 130 runs.
The optimality gap at threshold is , estimated by averaging normalized scores. It measures shortfall from the threshold without offsetting a run above it against one below. Changing changes the question. Mean, median, IQM, and gap are complementary summaries: none alone guarantees acceptable behavior in every game.
Intervals and profiles
The stratified bootstrap resamples runs within each task, retaining that task’s original sample count. It fixes games and estimates uncertainty associated with runs on those games; it does not generalize to an unknown task population. Inference about new tasks would require modeling or resampling tasks according to their sampling and resolving variation between levels. Shared seeds require preserving their pairing if it actually exists, not inferring it from a column number.
rliable performance profiles show against threshold , estimated over runs and tasks. Height at is the fraction exceeding the normalized human reference, not the fraction of games whose mean does so. The figure evaluates thresholds separated by 0.1 and joins points with segments; the exact empirical profile is stepped. Reducing runs uses the first ones in published order, not a random selection. Bootstrap bands at each threshold are pointwise intervals, not automatically a simultaneous band for the whole curve. Crossing curves can each be better in a different region; one ranking would hide that difference.
Dolan and Moré profiles answer another question. For positive costs of solving problem with method , define and plot the fraction of problems with . The value at measures fraction of wins or ties; the high limit measures fraction solved. Failures are treated as infinity or by an explicit convention. This is not the normalized-score tail profile, and its denominator changes if the method set changes.
The probability of improvement of X over Y compares independent runs on the same task, counting ties as half a win: , then averages across tasks. The pairs must not be treated as independent observations: one run appears in many pairs. A stratified bootstrap resamples each method’s original runs within each task. This estimand asks about a random run of each method, not the posterior probability that X’s mean exceeds Y’s.
A Bayesian comparison
Bayesian classifier comparison assigns a posterior distribution to uncertainty and reports masses for worse, equivalent, and better with a prespecified ROPE. The Bayesian signed-rank test of Benavoli and colleagues uses paired task differences, a Dirichlet distribution over observed differences, and a prior pseudo-observation at zero. Each weight sample induces masses in the three regions from pairwise averages of differences (Walsh sums). The posterior depends on prior and task exchangeability; it does not turn a convenience selection of games into a random sample of all possible tasks.
The cloud’s mean coordinates summarize expected mass in each region of the predictive distribution of Walsh sums; they are not the probability that each of the 26 observed games changes its result. baycomp also calculates the posterior probability that each region has the largest mass: it counts the fraction of simplex points where that coordinate exceeds the others. Dominant-region probability and mean predictive mass are different quantities. A decision rule such as “better if dominant-region probability exceeds 0.95” must be declared in advance with the cost of error. Repeat analysis with reasonable priors and different ROPE widths to assess sensitivity.
+## Lab: public results
The cell embeds a copy of the six JSON files fixed to the cited revision; it needs no network or author-computer path. scores[method] has shape runs × games. Normalization uses exactly the repository’s references and does not invent seed pairing.
import json
import numpy as np
raw=json.loads('''{"dreamerv3":{"Alien":[850.8333333333333,957.5,932.5,1320,736.25],"Amidar":[120,157.83333333333334,144.83333333333331,140.75,132.08333333333334],"Assault":[881.75,698,434,526.6666666666667,987.75],"Asterix":[933.3333333333334,1170.8333333333333,992.5,795.8333333333334,770],"BankHeist":[311.66666666666663,342.08333333333337,387.08333333333337,1037.5,1165],"BattleZone":[8500,13000,14500,14500,10750],"Boxing":[80.5,63.25,85.5,85.5,75.5],"Breakout":[30.333333333333332,19.133333333333333,67.8,17.1,21.25],"ChopperCommand":[550,400,200,700,200],"CrazyClimber":[112600,75200,79350,123200,95600],"DemonAttack":[171.04166666666669,212.08333333333331,620,201.66666666666669,311.6666666666667],"Freeway":[0,0,0,0,0],"Frostbite":[258,356.25,445,3170,317.5],"Gopher":[8020,1535,3130,1790,4175],"Hero":[7654.375,12992.5,13420.833333333332,8346.25,13388.75],"Jamesbond":[487.5,345.83333333333337,337.5,252.08333333333334,800],"Kangaroo":[12200,4150,1625,1700,816.6666666666667],"Krull":[6387.5,7717.5,6807.5,9122.5,8872.5],"KungFuMaster":[25250,23650,19100,14000,25100],"MsPacman":[1475,1423.3333333333335,858.75,1223.75,1653.75],"Pong":[20,20.5,18.5,18,15],"PrivateEye":[4263.5,48,100,-10.5,7],"Qbert":[3500,1100,4342.708333333334,3436.875,4645.833333333333],"RoadRunner":[25400,8675,11800,24450,7500],"Seaquest":[450,825,475,510,830],"UpNDown":[4863.333333333334,11915,5923.333333333334,4600.416666666666,10533.333333333334]},"HUMAN":{"Alien":[7127.7],"Amidar":[1719.5],"Assault":[742],"Asterix":[8503.3],"BankHeist":[753.1],"BattleZone":[37187.5],"Boxing":[12.1],"Breakout":[30.5],"ChopperCommand":[7387.8],"CrazyClimber":[35829.4],"DemonAttack":[1971],"Freeway":[29.6],"Frostbite":[4334.7],"Gopher":[2412.5],"Hero":[30826.4],"Jamesbond":[302.8],"Kangaroo":[3035],"Krull":[2665.5],"KungFuMaster":[22736.3],"MsPacman":[6951.6],"Pong":[14.6],"PrivateEye":[69571.3],"Qbert":[13455],"RoadRunner":[7845],"Seaquest":[42054.7],"UpNDown":[11693.2]},"IRIS":{"Alien":[368.7,452.5,437.2,331.7,510],"Amidar":[196,126,164.9,162.9,65.1],"Assault":[1481.3,928.1,1121.8,1556,2534.8],"Asterix":[762.5,1114,1082,716.5,593],"BankHeist":[42.2,48.8,68.4,46.4,59.6],"BattleZone":[16990,14570,11300,10070,12440],"Boxing":[86.2,49.3,55.8,83.5,75.5],"Breakout":[104.6,85.6,69.7,70.3,88.1],"ChopperCommand":[1150,1276,1659,2162,1578],"CrazyClimber":[64101,66127,62740,77066,26587],"DemonAttack":[905,2011.9,2888.5,2613.4,1753],"Freeway":[30.9,31.5,30.5,30.8,31.6],"Frostbite":[274.3,250,295,250,226.3],"Gopher":[2987.2,2476.8,3110.4,1171.4,1434.8],"Hero":[6916.2,6933.9,6740.6,7881.6,6714.7],"Jamesbond":[487.5,394,486,464,482],"Kangaroo":[2249,732,750,90,370],"Krull":[6047.4,7364.8,4980.6,6006.3,8683],"KungFuMaster":[7301,15949,34406,14372,36771],"MsPacman":[1251.6,941.5,590.3,770.8,1441.1],"Pong":[19.3,18.5,16.6,6.2,12.4],"PrivateEye":[100,100,100,100,100],"Qbert":[853,575,790.2,1027.2,483.2],"RoadRunner":[11355,2033,17106,7614,9965],"Seaquest":[752.2,855.8,691,386,621.6],"UpNDown":[3793,5367.5,2943.7,3637.9,1988.9]},"RANDOM":{"Alien":[227.8],"Amidar":[5.8],"Assault":[222.4],"Asterix":[210],"BankHeist":[14.2],"BattleZone":[2360],"Boxing":[0.1],"Breakout":[1.7],"ChopperCommand":[811],"CrazyClimber":[10780.5],"DemonAttack":[152.1],"Freeway":[0],"Frostbite":[65.2],"Gopher":[257.6],"Hero":[1027],"Jamesbond":[29],"Kangaroo":[52],"Krull":[1598],"KungFuMaster":[258.5],"MsPacman":[307.3],"Pong":[-20.7],"PrivateEye":[24.9],"Qbert":[163.9],"RoadRunner":[11.5],"Seaquest":[68.4],"UpNDown":[533.4]},"REM":{"Alien":[912,835.3,496.6,462.5,329.8],"Amidar":[120.7,105.42,64.62,99.89,85.86],"Assault":[1590.54,1650.69,2215.04,1543.5,1821.45],"Asterix":[1294.5,2105.5,1933,1891,963.5],"BankHeist":[30.9,26.6,27,10.3,1.3],"BattleZone":[14480,15480,7560,10780,10830],"Boxing":[93.76,88.41,90.26,76.39,88.82],"Breakout":[98.22,70.21,90.65,90.24,104.06],"ChopperCommand":[2019,1445,2105,2042,5195],"CrazyClimber":[72457,85506,78462,73653,72660],"DemonAttack":[6893.9,6275.9,5523.7,3883.95,6115.8],"Freeway":[31.71,33.08,31.92,32,32.99],"Frostbite":[173.125,279.9,259.3,222.5,267.8],"Gopher":[5447,6593.6,6222.2,4191.4,4807.8],"Hero":[7376.15,11394.7,2992.45,3541.75,7118.9],"Jamesbond":[397,346,384,475.5,353.5],"Kangaroo":[1048,130,566,314,280],"Krull":[4395.5,3971.9,4378.7,4352.9,2989.7],"KungFuMaster":[12309,34452,19434,26519,33147],"MsPacman":[875.6,1052.3,841.4,664,1379.2],"Pong":[20.52,20,21,8.15,20.15],"PrivateEye":[100,100,100,100,98],"Qbert":[632.25,712.5,879.25,738.75,752.25],"RoadRunner":[17790,17743,10839,6882,17047],"Seaquest":[826.4,1106,801.8,1576.6,872.6],"UpNDown":[4660.9,1893.7,2937.3,3449.1,5847.1]},"Simulus":{"Alien":[905.3,611.5,652.3,672.7,594.1],"Amidar":[125.06,115.71,110.03,73.96,87.4],"Assault":[1690.65,1411.19,1883.47,2593.63,1534.81],"Asterix":[1266,1552,1231.5,1346,1450],"BankHeist":[314.6,311.8,347.8,366,395.1],"BattleZone":[18560,17640,7360,14960,7790],"Boxing":[94.68,94.72,93.61,92.52,92.1],"Breakout":[159.78,148.1,151.79,141.86,142.75],"ChopperCommand":[3033,4322,4219,2371,4113],"CrazyClimber":[90810,88467,95567,106277,86045],"DemonAttack":[2204.45,3621.8,6707.95,6069.25,5334.75],"Freeway":[33.9,31.89,31.34,31.86,30.58],"Frostbite":[254.2,267.6,268.1,250.1,252.1],"Gopher":[4116,4166.4,4279.2,4532.6,4722],"Hero":[7673,7464.55,7473.05,7302,7421.4],"Jamesbond":[572.5,711,509.5,752.5,844.5],"Kangaroo":[12856,5030,1370,4114,9910],"Krull":[6144.9,5332.4,7918.8,7318.9,6671.5],"KungFuMaster":[30282,22577,42688,49410,13570],"MsPacman":[1112,948.1,1305.5,1369.6,1678.3],"Pong":[20.73,19.98,19.03,19.47,20.11],"PrivateEye":[100,100,100,100,100],"Qbert":[790.25,2717,3449.25,1127.5,4044],"RoadRunner":[16976,25718,29079,21927,28659],"Seaquest":[1828.2,1768.8,1818,1777.8,1809.4],"UpNDown":[5706.3,2518.3,1308.5,4543.5,38006.1]}}''')
games=sorted(raw['HUMAN'])
methods=['IRIS','Simulus','dreamerv3','REM']
scores={m:np.array([[(v-raw['RANDOM'][g][0])/(raw['HUMAN'][g][0]-raw['RANDOM'][g][0]) for v in raw[m][g]] for g in games]).T for m in methods}
assert all(x.shape==(5,26) and np.isfinite(x).all() for x in scores.values())
print('métodos',methods,'formas',[scores[m].shape for m in methods])
print('juegos',games)Aggregates, profiles, and probability of improvement
The following implementations use each game as a stratum. The percentile bootstrap is approximate, particularly with five runs. The improvement-probability function compares all pairs within each game and awards half a point for a tie.
import numpy as np
from scipy.stats import trim_mean
def iqm(values):
x=np.sort(np.asarray(values,float).ravel()); cut=len(x)//4
if len(x)==0: raise ValueError('sin puntuaciones')
return float(x[cut:len(x)-cut].mean())
def optimality_gap(values,gamma=1.):
return float(np.maximum(gamma-np.asarray(values,float),0).mean())
def profile(values,thresholds):
x=np.asarray(values,float); return np.array([(x>t).mean() for t in thresholds])
def probability_improvement(x,y):
x=np.asarray(x,float);y=np.asarray(y,float)
if x.ndim!=2 or y.ndim!=2 or x.shape[1]!=y.shape[1]: raise ValueError('mismas tareas requeridas')
delta=x[:,None,:]-y[None,:,:]
return float(((delta>0)+.5*(delta==0)).mean())
def stratified_bootstrap_ci(x,aggregate,n_boot=500,seed=0):
x=np.asarray(x,float)
if x.ndim!=2 or min(x.shape)<2 or n_boot<1: raise ValueError('matriz ejecución × tarea')
rng=np.random.default_rng(seed); n,tasks=x.shape; out=[]
for _ in range(n_boot):
idx=rng.integers(n,size=(n,tasks))
out.append(aggregate(x[idx,np.arange(tasks)[None,:]]))
return aggregate(x),np.quantile(out,[.025,.975],axis=0)
for m in methods:
x=scores[m]
assert np.isclose(iqm(x),trim_mean(x.ravel(),.25))
estimate,ci=stratified_bootstrap_ci(x,iqm,500,31)
print(m,'IQM',round(estimate,4),'IC',np.round(ci,4),'gap',round(optimality_gap(x),4))
print('P(Simulus > IRIS)',probability_improvement(scores['Simulus'],scores['IRIS']))
print('perfil Simulus en 0,1,2:',profile(scores['Simulus'],[0,1,2]))In this run IQM over 130 scores is 0.9904 for Simulus and 0.5012 for IRIS; percentile intervals with 500 resamples are approximately [0.8770, 1.1176] and [0.4430, 0.5618]. This describes run uncertainty within fixed games. It does not show the same differences would appear with another game selection or that the original implementations of all four methods used equal training resources. Estimated Simulus-over-IRIS improvement probability is 0.8254 and the following cell’s approximate stratified interval is [0.7815, 0.8777]. This asks another question: it compares one run of each method on a game, weighting each game equally.
The previous interval resamples each method separately. An improvement-probability interval needs two matrices and two independent resamples per stratum, not a bootstrap of the average of 25 comparisons per game. The next code constructs that interval and pointwise profile bands.
def improvement_ci(x,y,n_boot=500,seed=0):
rng=np.random.default_rng(seed);a=np.asarray(x,float);b=np.asarray(y,float)
if a.ndim!=2 or b.ndim!=2 or a.shape[1]!=b.shape[1]: raise ValueError('tareas incompatibles')
out=[]; tasks=a.shape[1]
for _ in range(n_boot):
ia=rng.integers(a.shape[0],size=a.shape);ib=rng.integers(b.shape[0],size=b.shape)
out.append(probability_improvement(a[ia,np.arange(tasks)[None,:]],b[ib,np.arange(tasks)[None,:]]))
return probability_improvement(a,b),np.quantile(out,[.025,.975])
thresholds=np.linspace(0,2,21)
pp,pci=improvement_ci(scores['Simulus'],scores['IRIS'],500,32)
curve,band=stratified_bootstrap_ci(scores['Simulus'],lambda x:profile(x,thresholds),500,33)
print('mejora e IC:',pp,pci)
print('perfil en 1 e IC:',curve[10],band[:,10])Friedman, Holm, and the diagram
First calculate each method’s mean per game. Friedman uses 26 games as blocks with tie correction; the scipy test provides an independent check. Post hoc uses pairwise Wilcoxon and Holm correction. The Nemenyi diagram separately uses the quantile for four methods. It should not be interpreted as a drawing of Holm results.
from itertools import combinations
from scipy.stats import rankdata,chi2,friedmanchisquare,wilcoxon
import numpy as np
def friedman_from_scratch(matrix):
x=np.asarray(matrix,float); N,k=x.shape
ranks=np.array([rankdata(-row,method='average') for row in x]); means=ranks.mean(axis=0)
q=12*N*np.sum(means**2)/(k*(k+1))-3*N*(k+1)
ties=0
for row in x:
_,counts=np.unique(row,return_counts=True)
ties+=np.sum(counts**3-counts)
correction=1-ties/(N*(k**3-k))
if correction<=0: raise ValueError('todos los rangos empatados')
q=q/correction
return q,float(chi2.sf(q,k-1)),means
def holm(pvals):
p=np.asarray(pvals,float);order=np.argsort(p);adj=np.empty(len(p));running=0.
for i,j in enumerate(order):
running=max(running,(len(p)-i)*p[j]);adj[j]=min(1.,running)
return adj
table=np.column_stack([scores[m].mean(axis=0) for m in methods])
q,p,ranks=friedman_from_scratch(table); reference=friedmanchisquare(*table.T)
print('Friedman propio:',q,p,'scipy:',reference)
print('rangos',dict(zip(methods,ranks)))
assert np.allclose([q,p],[reference.statistic,reference.pvalue])
pairs=list(combinations(range(len(methods)),2))
raw_p=[wilcoxon(table[:,i],table[:,j],method='auto').pvalue for i,j in pairs]
for (i,j),p0,ph in zip(pairs,raw_p,holm(raw_p)):
print(methods[i],methods[j],'p',round(p0,5),'Holm',round(ph,5))Friedman returns and for these game means. In six paired tests, Holm keeps Simulus versus IRIS and versus REM below 0.05. Simulus versus DreamerV3 has unadjusted approximately 0.0272, but after Holm approximately 0.1088. Correction changes the conclusion for that family; it does not mean the methods are equivalent or effect size is zero. These analyses do not fully quantify uncertainty of each game mean obtained from only five runs.
The following graph marks ranks and CD length. A different method set also changes and potentially ranks. It should therefore accompany pairwise tests, not replace them.
import matplotlib.pyplot as plt
N,k=table.shape; q_alpha=2.569
cd=q_alpha*np.sqrt(k*(k+1)/(6*N))
fig,ax=plt.subplots(figsize=(7,2.5))
for i,(name,r) in enumerate(zip(methods,ranks)):
ax.plot(r,i,'o');ax.text(r+.04,i,name,va='center')
ax.plot([1,1+cd],[4,4],color='black',lw=2);ax.text(1,4.15,'CD = '+str(round(cd,3)))
ax.set_xlim(.8,4.8);ax.set_ylim(-.5,4.7);ax.set_xlabel('rango medio, 1 es mejor');ax.set_yticks([])
plt.tight_layout();plt.show()Bayesian simplex via Dirichlet
With differences and a zero pseudodifference, sample Dirichlet weights with parameter 0.5 for the pseudo-observation and 1 for each game. For each weight sample, sum over averages in the three regions. Exact ties at boundaries receive half the mass on each side, as in baycomp. Convention and prior matter. The three masses sum to one by construction.
def bayesian_signed_rank(a,b,rope=.1,draws=1000,seed=31,prior=.5):
a=np.asarray(a,float);b=np.asarray(b,float)
if a.shape!=b.shape or a.ndim!=1 or rope<0 or prior<=0: raise ValueError('entrada inválida')
d=np.r_[0.,b-a];sums=d[:,None]+d[None,:]
rng=np.random.default_rng(seed);alpha=np.r_[prior,np.ones(len(a))]
weights=rng.dirichlet(alpha,size=draws)
heaviside=lambda x,limit:(x>limit).astype(float)+.5*(x==limit)
left=np.einsum('bi,ij,bj->b',weights,heaviside(-sums,2*rope),weights)
right=np.einsum('bi,ij,bj->b',weights,heaviside(sums,2*rope),weights)
return np.column_stack([left,1-left-right,right])
posterior=bayesian_signed_rank(table[:,0],table[:,1],rope=.1)
print('masas posteriores medias peor/ROPE/mejor:',posterior.mean(axis=0))
print('probabilidad posterior de región dominante:',np.bincount(np.argmax(posterior,axis=1),minlength=3)/len(posterior))
assert np.allclose(posterior.sum(axis=1),1)With illustrative ROPE 0.1, prior 0.5, and one thousand Dirichlet samples, mean mass is approximately [0, 0.251, 0.749] for worse, ROPE, and better. The better region is largest in 0.997 of samples in this run. The margin is a teaching choice, not a tolerance registered before these results. The result is conditional on prior, margin, 26 games, and their means: it differs from improvement probability between two runs and does not itself correct any later selection of margin or methods.
Compare with libraries
The local cell downloads the six public files from the fixed commit so its session is independent of the browser session. In an isolated environment install rliable, autorank, and baycomp; the checked comparison used autorank 1.3.0, baycomp 1.0.3, and pandas 2.3.3. Dependency compatibility matters: different versions may change intervals or automatic rules. Bootstrap intervals are approximated with finitely many resamples, so need not match the above digit for digit.
import json, urllib.request
import numpy as np
import pandas as pd
from scipy.stats import trim_mean, friedmanchisquare
from rliable import metrics, library as rly
from autorank import autorank
from baycomp import SignedRankTest
base='https://raw.githubusercontent.com/leor-c/Simulus/7577556056bc09e449b69b74ae9f278a043b0644/results/data/atari/'
files=['IRIS','Simulus','dreamerv3','REM','HUMAN','RANDOM']
raw={name:json.loads(urllib.request.urlopen(base+name+'.json',timeout=30).read()) for name in files}
games=sorted(raw['HUMAN']);methods=files[:4]
scores={m:np.array([[(v-raw['RANDOM'][g][0])/(raw['HUMAN'][g][0]-raw['RANDOM'][g][0]) for v in raw[m][g]] for g in games]).T for m in methods}
assert all(v.shape==(5,26) for v in scores.values())
for m,x in scores.items():
print(m,'IQM propia/rliable:',trim_mean(x.ravel(),.25),metrics.aggregate_iqm(x))
assert np.isclose(trim_mean(x.ravel(),.25),metrics.aggregate_iqm(x))
point,ci=rly.get_interval_estimates(scores,metrics.aggregate_iqm,reps=500)
print('rliable IQM e intervalos:',point,ci)
table=pd.DataFrame({m:scores[m].mean(axis=0) for m in methods})
result=autorank(table,force_mode='nonparametric',order='descending',verbose=False)
ref=friedmanchisquare(*(table[m].to_numpy() for m in methods))
print('autorank Friedman:',result.pvalue,'scipy:',ref.pvalue,'CD Nemenyi:',result.cd)
assert np.isclose(result.pvalue,ref.pvalue)
samples=SignedRankTest.sample(table['IRIS'].to_numpy(),table['Simulus'].to_numpy(),rope=.1,prior=.5,nsamples=2000,random_state=31)
print('baycomp masas medias:',samples.mean(axis=0),'suma',samples.mean(axis=0).sum())
print('baycomp probabilidad de región dominante:',np.bincount(np.argmax(samples,axis=1),minlength=3)/len(samples))npm run lab and open the connection link.Exercises
Step 1 of 2. What happens if you replace less than one quarter with values tending to +infinity?
def stratified_bootstrap_ci(scores, aggregate, n_boot, seed):
pass