concept-analysis / scripts /analyze_concept_drift.py
revan1230's picture
compliance: HF-sourcing build provenance
f326e95 verified
Raw
History Blame Contribute Delete
8.39 kB
# ruff: noqa: T201 # CLI build-script report payload (CLAUDE.md whitelist)
"""Concept drift analysis across LXX / NT / Vulgate strata.
Implements two complementary methods from Schlattmann & Vogl 2024
("Trajectories of Change: Approaches for Tracking Knowledge Evolution",
arXiv:2501.00391), adapted from time-sliced corpora to biblical transmission
strata (LXX Greek → NT Greek → Vulgate Latin).
Method 1 — Crystallization index (EDE intra-stratum):
mean_cosine_to_centroid per concept per stratum, already in concept_trajectory_sp.
Paper's Method 2 analogy: density at the centroid using the stratum's own documents.
High = tight cluster (crystallized); low = diffuse (polysemous).
Method 2 — Cross-stratum density at reference centroid:
For a concept C transitioning from stratum A → B, compute the average cosine
similarity of B's verse embeddings to A's centroid.
cross_density(A→B) = mean_cos(emb_B, centroid_A)
High → B verses echo A's semantic centre (concept preserved)
Low → B verses are far from A's centre (concept drifted)
Consolidated 2026-06-23 into NuBerea/concept-analysis:scripts/ from the retired
NuBerea/concept-trajectories repo so build.py resolves this import in-tree.
The three pure functions (cosine_sim, cross_density, compute_drift_dataframe)
are imported by build.py; analytic logic is unchanged from the original module.
Inputs (HF-native via load_hf_or_local with sibling-build-dir fallback):
NuBerea/concept-analysis concept_trajectory_sp — 190 rows
NuBerea/concept-analysis concept_verse_edge_sp — 59,478 rows
Output: writes concept_drift_analysis.csv to the resolved data dir, or to
--out if specified.
CLI:
python analyze_concept_drift.py [--out /path/to/output.csv] [--quiet]
"""
from __future__ import annotations
import argparse
import pathlib
import sys
import numpy as np
import pandas as pd
BUILD = pathlib.Path("huggingface/candidates/build")
DATA = BUILD / "concept-analysis/data"
DEFAULT_OUT = DATA / "concept_drift_analysis.csv"
# Make hf_registry importable
_THIS = pathlib.Path(__file__).resolve()
_CANDIDATES = _THIS.parents[2]
if str(_CANDIDATES) not in sys.path:
sys.path.insert(0, str(_CANDIDATES))
def cosine_sim(a: np.ndarray, b: np.ndarray) -> float:
na, nb = np.linalg.norm(a), np.linalg.norm(b)
if na < 1e-8 or nb < 1e-8:
return float("nan")
return float(np.dot(a, b) / (na * nb))
def cross_density(emb_b: np.ndarray, centroid_a: np.ndarray) -> float:
"""Mean cosine similarity of stratum-B verses to stratum-A centroid."""
cn = np.linalg.norm(centroid_a)
if cn < 1e-8:
return float("nan")
c = centroid_a / cn
norms = np.linalg.norm(emb_b, axis=1, keepdims=True)
units = emb_b / (norms + 1e-8)
return float((units @ c).mean())
def compute_drift_dataframe(traj: pd.DataFrame, cve: pd.DataFrame) -> pd.DataFrame:
"""Compute drift metrics from trajectory + verse-edge dataframes.
Both inputs use the SPhilBerta 768-dim embedding space.
"""
traj_idx = traj.set_index(["concept_id", "stratum"])
emb_index: dict[tuple, np.ndarray] = {}
for (cid, stratum), grp in cve.groupby(["concept_id", "stratum"]):
emb_index[(cid, stratum)] = np.stack(
[np.array(e, dtype=np.float32) for e in grp["embedding"]]
)
all_concepts = traj["concept_id"].unique()
concept_label = traj.drop_duplicates("concept_id").set_index("concept_id")["concept_label"].to_dict()
pairs = [("lxx", "nt"), ("nt", "vg"), ("lxx", "vg")]
records = []
for cid in all_concepts:
label = concept_label.get(cid, "")
row: dict = {"concept_id": cid, "concept_label": label}
for s in ["lxx", "nt", "vg"]:
key = (cid, s)
if key in traj_idx.index:
row[f"verse_count_{s}"] = int(traj_idx.loc[key, "verse_count"])
row[f"crystallization_{s}"] = float(traj_idx.loc[key, "mean_cosine_to_centroid"])
row[f"dispersion_{s}"] = 1.0 - row[f"crystallization_{s}"]
else:
row[f"verse_count_{s}"] = 0
row[f"crystallization_{s}"] = float("nan")
row[f"dispersion_{s}"] = float("nan")
for s_a, s_b in pairs:
tag = f"{s_a}_{s_b}"
key_a = (cid, s_a)
key_b = (cid, s_b)
have_a = key_a in traj_idx.index
have_b = key_b in traj_idx.index
if have_a and have_b:
c_a = np.array(traj_idx.loc[key_a, "centroid"], dtype=np.float32)
c_b = np.array(traj_idx.loc[key_b, "centroid"], dtype=np.float32)
cc = cosine_sim(c_a, c_b)
row[f"centroid_cosine_{tag}"] = cc
row[f"centroid_drift_{tag}"] = 1.0 - cc
else:
row[f"centroid_cosine_{tag}"] = float("nan")
row[f"centroid_drift_{tag}"] = float("nan")
row[f"delta_dispersion_{tag}"] = (
row[f"dispersion_{s_b}"] - row[f"dispersion_{s_a}"]
if (not np.isnan(row[f"dispersion_{s_a}"]) and
not np.isnan(row[f"dispersion_{s_b}"]))
else float("nan")
)
if have_a and key_b in emb_index:
c_a = np.array(traj_idx.loc[key_a, "centroid"], dtype=np.float32)
emb_b = emb_index[key_b]
cd_ab = cross_density(emb_b, c_a)
row[f"cross_density_{tag}"] = cd_ab
row[f"cross_drift_{tag}"] = 1.0 - cd_ab
else:
row[f"cross_density_{tag}"] = float("nan")
row[f"cross_drift_{tag}"] = float("nan")
if have_b and key_a in emb_index:
c_b = np.array(traj_idx.loc[key_b, "centroid"], dtype=np.float32)
emb_a = emb_index[key_a]
cd_ba = cross_density(emb_a, c_b)
row[f"cross_density_{s_b}_{s_a}"] = cd_ba
else:
row[f"cross_density_{s_b}_{s_a}"] = float("nan")
cd_tag = row[f"centroid_drift_{tag}"]
xd_tag = row[f"cross_drift_{tag}"]
both_ok = not np.isnan(cd_tag) and not np.isnan(xd_tag)
row[f"drift_score_{tag}"] = (cd_tag + xd_tag) / 2.0 if both_ok else float("nan")
records.append(row)
return pd.DataFrame(records)
def load_inputs() -> tuple[pd.DataFrame, pd.DataFrame]:
"""Load concept_trajectory_sp + concept_verse_edge_sp via load_hf_or_local."""
from hf_registry import load_hf_or_local
print("Loading trajectory and verse-edge data ...")
traj_ds = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_sp", verbose=True)
cve_ds = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp", verbose=True)
traj = traj_ds.to_pandas()
cve = cve_ds.to_pandas()
print(f" trajectory rows: {len(traj)} verse-edge rows: {len(cve):,}")
return traj, cve
def print_report(df: pd.DataFrame) -> None:
"""Pretty-print drift summary tables (verbose mode)."""
pairs = [("lxx", "nt"), ("nt", "vg"), ("lxx", "vg")]
W = 70
print("\n" + "=" * W)
print("CONCEPT DRIFT ANALYSIS (LXX → NT → Vulgate)")
print("=" * W)
for s_a, s_b in pairs:
tag = f"{s_a}_{s_b}"
col = f"drift_score_{tag}"
sub = df[df[col].notna()].sort_values(col, ascending=False)
print(f"\n--- {s_a.upper()}{s_b.upper()} ({len(sub)} concepts with both strata) ---")
for _, r in sub.head(10).iterrows():
print(f" {r['concept_id']:<23} {str(r['concept_label'])[:32]:<33} drift={r[col]:.4f}")
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description="Compute concept drift analysis")
ap.add_argument("--out", type=pathlib.Path, default=DEFAULT_OUT, help="Output CSV path")
ap.add_argument("--quiet", action="store_true", help="Skip the verbose report block")
args = ap.parse_args(argv)
traj, cve = load_inputs()
df = compute_drift_dataframe(traj, cve)
args.out.parent.mkdir(parents=True, exist_ok=True)
df.to_csv(args.out, index=False)
print(f"Saved: {args.out} ({len(df)} concepts, {len(df.columns)} columns)")
if not args.quiet:
print_report(df)
return 0
if __name__ == "__main__":
sys.exit(main())