Download scripts/subjective_stats.py from Banglabox/banglaeval: direct link, hf CLI and curl.
- Browser
- Download file 4.33 kB
-
https://huggingface.co/datasets/Banglabox/banglaeval/resolve/main/scripts/subjective_stats.py
- Command line
-
hf download hf://datasets/Banglabox/banglaeval/scripts/subjective_stats.py
-
curl -L -o subjective_stats.py https://huggingface.co/datasets/Banglabox/banglaeval/resolve/main/scripts/subjective_stats.py
4.33 kB
| """Recompute the subjective results (Table 5) from the raw per-rating records. | |
| Usage: python subjective_stats.py subjective_ratings.xlsx [--focal banglabox] | |
| Outputs, per scale (naturalness, similarity_mos, clarity): | |
| * mean per system and 95% CI half-width = 1.96 x marginal SE of a crossed random-effects | |
| decomposition (rater + item random effects, additive; method-of-moments variance components); | |
| * Krippendorff's alpha (ordinal) over all raters; | |
| * paired Wilcoxon signed-rank tests of the focal system against every other synthesized system on | |
| per-item means (n = items), Bonferroni-corrected over the number of comparisons. | |
| Only numpy/pandas/scipy are required. | |
| """ | |
| import sys, argparse, itertools, numpy as np, pandas as pd | |
| from scipy.stats import wilcoxon | |
| def krippendorff_alpha_ordinal(df, value_col, unit_col="utterance_id", rater_col="rater_id"): | |
| """Krippendorff's alpha with the ordinal metric. Units = (item, system) pairs; each unit rated by all raters.""" | |
| d = df.copy(); d["unit"] = d[unit_col].astype(str) + "|" + d["system"].astype(str) | |
| vals = sorted(d[value_col].dropna().unique()); K = len(vals); idx = {v: i for i, v in enumerate(vals)} | |
| # value-by-unit matrix of counts | |
| units = d.groupby("unit")[value_col].apply(list) | |
| units = units[units.apply(len) > 1] | |
| n_uk = np.zeros((len(units), K)) | |
| for r, lst in enumerate(units): | |
| for v in lst: n_uk[r, idx[v]] += 1 | |
| n_k = n_uk.sum(0); n = n_k.sum() | |
| # ordinal distance metric | |
| cum = np.cumsum(n_k) | |
| def delta(c, k): | |
| if c == k: return 0.0 | |
| lo, hi = min(c, k), max(c, k) | |
| s = n_k[lo:hi + 1].sum() - (n_k[lo] + n_k[hi]) / 2.0 | |
| return s ** 2 | |
| D = np.array([[delta(c, k) for k in range(K)] for c in range(K)]) | |
| m_u = n_uk.sum(1) | |
| Do = sum((n_uk[u][:, None] * n_uk[u][None, :] * D).sum() / (m_u[u] - 1) for u in range(len(units))) / n | |
| De = (n_k[:, None] * n_k[None, :] * D).sum() / (n * (n - 1)) | |
| return 1 - Do / De | |
| def crossed_re_halfwidth(sub, value_col, rater_col="rater_id", item_col="utterance_id"): | |
| """95% half-width for the system mean under an additive crossed random-effects model | |
| y = mu + a_rater + b_item + e (method-of-moments components; balanced design assumed).""" | |
| y = sub.pivot_table(index=rater_col, columns=item_col, values=value_col, aggfunc="mean") | |
| R, I = y.shape; Y = y.values | |
| ms_r = I * np.var(Y.mean(1), ddof=1); ms_i = R * np.var(Y.mean(0), ddof=1) | |
| resid = Y - Y.mean(1, keepdims=True) - Y.mean(0, keepdims=True) + Y.mean() | |
| ms_e = (resid ** 2).sum() / ((R - 1) * (I - 1)) | |
| var_r = max(0.0, (ms_r - ms_e) / I); var_i = max(0.0, (ms_i - ms_e) / R); var_e = ms_e | |
| se = np.sqrt(var_r / R + var_i / I + var_e / (R * I)) | |
| return 1.96 * se | |
| def main(): | |
| ap = argparse.ArgumentParser(); ap.add_argument("xlsx"); ap.add_argument("--focal", default="banglabox"); ap.add_argument("--reference", default="human") | |
| a = ap.parse_args() | |
| df = pd.read_excel(a.xlsx, sheet_name="Ratings") | |
| scales = [c for c in ("naturalness", "similarity_mos", "clarity") if c in df.columns] | |
| for c in scales: df[c] = pd.to_numeric(df[c], errors="coerce") | |
| systems = sorted(df["system"].unique()); baselines = [s for s in systems if s not in (a.focal, a.reference)] | |
| print(f"raters={df.rater_id.nunique()} items={df.utterance_id.nunique()} systems={len(systems)} ratings={len(df)}\n") | |
| for sc in scales: | |
| print(f"=== {sc} ===") | |
| alpha = krippendorff_alpha_ordinal(df, sc); print(f"Krippendorff's alpha (ordinal): {alpha:.2f}") | |
| for s in systems: | |
| sub = df[df.system == s]; print(f" {s:12s} mean={sub[sc].mean():.2f} +/-{crossed_re_halfwidth(sub, sc):.2f}") | |
| focal = df[df.system == a.focal].groupby("utterance_id")[sc].mean() | |
| m = len(baselines) | |
| for b in baselines: | |
| other = df[df.system == b].groupby("utterance_id")[sc].mean().reindex(focal.index) | |
| diff = (focal - other).values | |
| if np.allclose(diff, 0): p = 1.0 | |
| else: p = wilcoxon(focal.values, other.values, zero_method="wilcox").pvalue | |
| p_adj = min(1.0, p * m) | |
| print(f" {a.focal} vs {b:12s}: per-item mean diff={diff.mean():+.2f} Wilcoxon p={p:.2e} Bonferroni(x{m}) p={p_adj:.2e}") | |
| print() | |
| if __name__ == "__main__": main() | |