indus-sequences-nulls / example_stats.py
joyboseroy's picture
Upload 7 files
9bd31b0 verified
Raw History Blame Contribute Delete
3.82 kB
"""Worked example: four statistics for held-out real inscriptions vs each null, with bootstrap 95% CIs.
All reference quantities (bigram model, top-5 first and final signs) are fit on the real TRAIN half.
Bootstrap resamples whole sequences (2,000 draws). Nulls pool their three seeds.
Statistics
xent_bits per-token bigram cross-entropy in bits (lower = more bigram-typical)
top5_final share of sequences whose last sign is one of the 5 most common final signs in train
top5_first same for the first sign
adjacent_repeat share of sequences containing the same sign twice in a row
The `real_train` row is an in-sample reference: the nulls are built from train inscriptions, so
they share that advantage, and real_train - real_test shows how large it is.
Usage: python example_stats.py --data data --corpus indus_website --out example_stats.csv
"""
import argparse
import math
from collections import Counter, defaultdict
import numpy as np
import pandas as pd
K = 0.1
B = 2000
def fit(train):
uni, bi = Counter(), defaultdict(Counter)
first, last = Counter(), Counter()
for s in train:
t = ["<s>"] + s + ["</s>"]
for a, b in zip(t, t[1:]):
bi[a][b] += 1
uni[b] += 1
first[s[0]] += 1
last[s[-1]] += 1
return bi, len(set(uni) | {"<unk>"}), {k for k, _ in first.most_common(5)}, {k for k, _ in last.most_common(5)}
def per_seq(seqs, model):
bi, v, top_first, top_last = model
rows = []
for s in seqs:
s = list(s)
t = ["<s>"] + s + ["</s>"]
bits = 0.0
for a, b in zip(t, t[1:]):
ca = bi.get(a, {})
na = sum(ca.values())
bits += -math.log2((ca.get(b, 0) + K) / (na + K * v))
rows.append(
(
bits,
len(t) - 1,
float(s[-1] in top_last),
float(s[0] in top_first),
float(any(x == y for x, y in zip(s, s[1:]))),
)
)
return np.array(rows)
def boot(arr, rng):
n = len(arr)
idx = rng.integers(0, n, size=(B, n))
xs = arr[idx] # B x n x 5
xent = xs[:, :, 0].sum(1) / xs[:, :, 1].sum(1)
others = xs[:, :, 2:].mean(1)
stats = np.column_stack([xent, others])
point = np.array([arr[:, 0].sum() / arr[:, 1].sum(), *arr[:, 2:].mean(0)])
lo, hi = np.percentile(stats, [2.5, 97.5], axis=0)
return point, lo, hi
def main(data, corpus, out):
real = pd.read_parquet(f"{data}/real.parquet")
nulls = pd.read_parquet(f"{data}/nulls.parquet")
rg = real[(real.corpus == corpus) & (~real.damaged)]
train = [list(s) for s in rg[rg.split == "train"].signs]
test = [list(s) for s in rg[rg.split == "test"].signs]
model = fit(train)
rng = np.random.default_rng(0)
names = ["xent_bits", "top5_final", "top5_first", "adjacent_repeat"]
rows = []
def add(label, seqs):
p, lo, hi = boot(per_seq(seqs, model), rng)
for n_, a, b, c in zip(names, p, lo, hi):
rows.append({"sequences": label, "statistic": n_, "value": a, "ci_low": b, "ci_high": c, "n": len(seqs)})
add("real_test", test)
add("real_train", train)
for m, g in nulls[nulls.corpus == corpus].groupby("null_model"):
add(m, [list(s) for s in g.signs])
df = pd.DataFrame(rows)
df.to_csv(out, index=False)
for stat, g in df.groupby("statistic"):
print(stat)
print(g[["sequences", "value", "ci_low", "ci_high"]].round(3).to_string(index=False))
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--data", default="data")
ap.add_argument("--corpus", default="indus_website")
ap.add_argument("--out", default="example_stats.csv")
a = ap.parse_args()
main(a.data, a.corpus, a.out)