cosmicmicra's picture
Upload analyze.py with huggingface_hub
c2eb89a verified
"""Core empirical analysis: separate linguistic vs mathematical contribution to MWP difficulty.
Experiments:
E1. Block-wise regression to predict grade (math-difficulty proxy):
LING-only vs MATH-only vs COMBINED -> R2 (CV), shows the two blocks carry
distinct, partly-independent signal.
E2. Inter-block correlation: how correlated are the linguistic and math axes?
Low correlation => they are genuinely separate dials.
E3. SVAMP linguistic-perturbation test: hold the math (Equation/Type) constant,
vary phrasing -> linguistic features move while math features don't.
"""
import json
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score, KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
RNG = 42
asdiv = pd.read_parquet("asdiv_features.parquet")
svamp = pd.read_parquet("svamp_features.parquet")
LING = [c for c in asdiv.columns if c.startswith("ling_")]
MATH = [c for c in asdiv.columns if c.startswith("math_")]
print("LING features:", LING)
print("MATH features:", MATH)
results = {}
# ---------- E1: block-wise prediction of grade ----------
y = asdiv["grade"].values.astype(float)
cv = KFold(n_splits=5, shuffle=True, random_state=RNG)
def cv_r2(cols):
X = asdiv[cols].values
model = make_pipeline(StandardScaler(),
RandomForestRegressor(n_estimators=300, random_state=RNG, n_jobs=-1))
s = cross_val_score(X if False else X, y, cv=cv, scoring="r2",
estimator=model) if False else cross_val_score(model, X, y, cv=cv, scoring="r2")
return float(np.mean(s)), float(np.std(s))
e1 = {
"ling_only": cv_r2(LING),
"math_only": cv_r2(MATH),
"combined": cv_r2(LING + MATH),
}
results["E1_grade_prediction_r2"] = e1
print("\n=== E1: predict grade (5-fold CV R2) ===")
for k, (m, s) in e1.items():
print(f" {k:12s}: R2 = {m:.3f} ± {s:.3f}")
# Linear (Ridge) variant for interpretability
def cv_r2_ridge(cols):
X = asdiv[cols].values
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
s = cross_val_score(model, X, y, cv=cv, scoring="r2")
return float(np.mean(s)), float(np.std(s))
results["E1_grade_prediction_r2_ridge"] = {
"ling_only": cv_r2_ridge(LING),
"math_only": cv_r2_ridge(MATH),
"combined": cv_r2_ridge(LING + MATH),
}
# ---------- E2: inter-block correlation ----------
# Reduce each block to a single difficulty index = its correlation-aligned PC1
from sklearn.decomposition import PCA
def block_index(cols):
Xs = StandardScaler().fit_transform(asdiv[cols].values)
pc = PCA(n_components=1, random_state=RNG).fit_transform(Xs)[:, 0]
# align sign so it positively correlates with grade
if spearmanr(pc, y).correlation < 0:
pc = -pc
return pc
ling_idx = block_index(LING)
math_idx = block_index(MATH)
rho_blocks, p_blocks = spearmanr(ling_idx, math_idx)
rho_ling_grade = spearmanr(ling_idx, y).correlation
rho_math_grade = spearmanr(math_idx, y).correlation
results["E2_block_indices"] = {
"ling_vs_math_spearman": [float(rho_blocks), float(p_blocks)],
"ling_vs_grade_spearman": float(rho_ling_grade),
"math_vs_grade_spearman": float(rho_math_grade),
}
print("\n=== E2: separability of the two difficulty axes ===")
print(f" LING index vs MATH index : rho = {rho_blocks:.3f} (p={p_blocks:.2e})")
print(f" LING index vs grade : rho = {rho_ling_grade:.3f}")
print(f" MATH index vs grade : rho = {rho_math_grade:.3f}")
# Per-feature Spearman vs grade
percorr = {}
for c in LING + MATH:
r = spearmanr(asdiv[c].values, y).correlation
percorr[c] = float(r)
results["E2_per_feature_spearman_vs_grade"] = percorr
# ---------- E3: SVAMP linguistic perturbation ----------
# Group SVAMP by math signature (Type + rounded equation structure). Within a group the
# MATH is (near-)constant; measure variance of LING features vs MATH features across the group.
SVAMP_LING = [c for c in svamp.columns if c.startswith("ling_")]
SVAMP_MATH = [c for c in svamp.columns if c.startswith("math_")]
svamp["math_sig"] = svamp["type"].astype(str) + "|" + svamp["math_n_ops"].astype(str)
grp = svamp.groupby("math_sig")
# within-group coefficient of variation, averaged over groups with >=5 members
def within_group_cv(cols):
cvs = []
for _, g in grp:
if len(g) < 5:
continue
for c in cols:
mu = g[c].mean()
sd = g[c].std()
if abs(mu) > 1e-6:
cvs.append(sd / abs(mu))
return float(np.mean(cvs)) if cvs else float("nan")
results["E3_svamp_within_math_group_variability"] = {
"ling_mean_cv": within_group_cv(SVAMP_LING),
"math_mean_cv": within_group_cv(SVAMP_MATH),
"n_groups_ge5": int(sum(len(g) >= 5 for _, g in grp)),
}
print("\n=== E3: SVAMP — hold math constant, does language still vary? ===")
print(f" mean within-math-group CoV LING = {results['E3_svamp_within_math_group_variability']['ling_mean_cv']:.3f}")
print(f" mean within-math-group CoV MATH = {results['E3_svamp_within_math_group_variability']['math_mean_cv']:.3f}")
# ---------- E4: commonality / variance partitioning (Ridge R2) ----------
r2_l = results["E1_grade_prediction_r2_ridge"]["ling_only"][0]
r2_m = results["E1_grade_prediction_r2_ridge"]["math_only"][0]
r2_c = results["E1_grade_prediction_r2_ridge"]["combined"][0]
unique_l = max(r2_c - r2_m, 0.0)
unique_m = max(r2_c - r2_l, 0.0)
shared = max(r2_l + r2_m - r2_c, 0.0)
results["E4_variance_partition_ridge"] = {
"unique_linguistic": unique_l,
"unique_mathematical": unique_m,
"shared": shared,
"total_combined": r2_c,
}
print("\n=== E4: variance partitioning (Ridge, predicting grade) ===")
print(f" unique LINGUISTIC : {unique_l:.3f}")
print(f" unique MATHEMATICAL : {unique_m:.3f}")
print(f" shared : {shared:.3f}")
print(f" total (combined) : {r2_c:.3f}")
with open("results.json", "w") as f:
json.dump(results, f, indent=2)
print("\nSaved results.json")
# ---------- Figures ----------
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# Fig 1: block-wise R2 bars (RF + Ridge)
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
for a, key, title in zip(ax, ["E1_grade_prediction_r2", "E1_grade_prediction_r2_ridge"],
["Random Forest", "Ridge (linear)"]):
d = results[key]
names = ["ling_only", "math_only", "combined"]
means = [d[n][0] for n in names]
errs = [d[n][1] for n in names]
a.bar(["Language", "Math", "Combined"], means, yerr=errs,
color=["#4C72B0", "#C44E52", "#55A868"], capsize=4)
a.set_ylabel("CV $R^2$ (predict grade)")
a.set_title(title)
a.set_ylim(0, max(0.6, max(means) + 0.1))
plt.tight_layout()
plt.savefig("fig_block_r2.png", dpi=150)
plt.close()
# Fig 2: variance partition pie/stacked
fig, ax = plt.subplots(figsize=(5, 4))
parts = [unique_l, shared, unique_m]
labels = [f"Unique language\n{unique_l:.2f}", f"Shared\n{shared:.2f}",
f"Unique math\n{unique_m:.2f}"]
ax.pie(parts, labels=labels, colors=["#4C72B0", "#8C8C8C", "#C44E52"],
autopct=lambda p: f"{p:.0f}%", startangle=90)
ax.set_title("Variance in math grade-level\nexplained (Ridge)")
plt.tight_layout()
plt.savefig("fig_variance_partition.png", dpi=150)
plt.close()
# Fig 3: per-feature spearman vs grade
pc = results["E2_per_feature_spearman_vs_grade"]
items = sorted(pc.items(), key=lambda kv: kv[1])
names = [k.replace("ling_", "L:").replace("math_", "M:") for k, _ in items]
vals = [v for _, v in items]
colors = ["#4C72B0" if k.startswith("ling_") else "#C44E52" for k, _ in items]
fig, ax = plt.subplots(figsize=(7, 6))
ax.barh(names, vals, color=colors)
ax.set_xlabel("Spearman $\\rho$ with grade level")
ax.axvline(0, color="k", lw=0.5)
ax.set_title("Per-feature correlation with math grade\n(blue=language, red=math)")
plt.tight_layout()
plt.savefig("fig_feature_corr.png", dpi=150)
plt.close()
# Fig 4: scatter of the two difficulty indices (separability)
fig, ax = plt.subplots(figsize=(5.5, 4.5))
sc = ax.scatter(math_idx, ling_idx, c=y, cmap="viridis", s=14, alpha=0.7)
ax.set_xlabel("Mathematical difficulty index (PC1)")
ax.set_ylabel("Linguistic difficulty index (PC1)")
ax.set_title(f"Two difficulty axes are near-orthogonal\nSpearman $\\rho$={rho_blocks:.2f}")
plt.colorbar(sc, label="grade")
plt.tight_layout()
plt.savefig("fig_axes_scatter.png", dpi=150)
plt.close()
print("Saved 4 figures.")