knowledge-drift-experiments / dataset_stats.py
Raniahossam33's picture
Upload folder using huggingface_hub
14b2318 verified
Raw
History Blame Contribute Delete
16.8 kB
"""
Knowledge Drift Dataset Statistics
====================================
Produces comprehensive statistics for the clean dataset.
Outputs both console tables and a structured JSON report.
Usage:
python dataset_stats.py --dataset data/knowledge_drift_clean.json
python dataset_stats.py --dataset data/knowledge_drift_clean.json --output data/stats/
"""
import json
import argparse
import os
import logging
from collections import Counter, defaultdict
from itertools import groupby
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def load_dataset(path):
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
def print_section(title, width=90):
print(f"\n{'='*width}")
print(f" {title}")
print(f"{'='*width}")
def print_table(headers, rows, col_widths=None):
"""Print a formatted table."""
if col_widths is None:
col_widths = []
for i, h in enumerate(headers):
max_w = len(str(h))
for row in rows:
if i < len(row):
max_w = max(max_w, len(str(row[i])))
col_widths.append(max_w + 2)
# Header
header_line = ""
for i, h in enumerate(headers):
if i == 0:
header_line += f" {str(h):<{col_widths[i]}}"
else:
header_line += f"{str(h):>{col_widths[i]}}"
print(header_line)
print(" " + "-" * (sum(col_widths) + len(col_widths)))
# Rows
for row in rows:
line = ""
for i, val in enumerate(row):
if i == 0:
line += f" {str(val):<{col_widths[i]}}"
else:
line += f"{str(val):>{col_widths[i]}}"
print(line)
def compute_stats(dataset):
"""Compute all statistics from the dataset."""
samples = dataset["samples"]
metadata = dataset.get("metadata", {})
total = len(samples)
stats = {"total_samples": total, "metadata": metadata}
# ============================================================
# 1. CATEGORY DISTRIBUTION
# ============================================================
cat_counts = Counter(s["category"] for s in samples)
stats["categories"] = {k: {"count": v, "pct": round(100*v/total, 1)}
for k, v in sorted(cat_counts.items())}
# ============================================================
# 2. TEMPORAL ZONE DISTRIBUTION
# ============================================================
zone_counts = Counter(s["temporal_zone"] for s in samples)
stats["temporal_zones"] = {k: {"count": v, "pct": round(100*v/total, 1)}
for k, v in sorted(zone_counts.items())}
# ============================================================
# 3. CATEGORY Γ— TEMPORAL ZONE CROSS-TAB
# ============================================================
cross = defaultdict(lambda: defaultdict(int))
for s in samples:
cross[s["category"]][s["temporal_zone"]] += 1
stats["category_x_zone"] = {cat: dict(zones) for cat, zones in sorted(cross.items())}
# ============================================================
# 4. DRIFTED vs NON-DRIFTED BREAKDOWN
# ============================================================
drifted = [s for s in samples if s.get("is_drifted_query")]
not_drifted = [s for s in samples if not s.get("is_drifted_query")]
post_cutoff = [s for s in samples if s["temporal_zone"] == "post_cutoff"]
drifted_post = [s for s in drifted if s["temporal_zone"] == "post_cutoff"]
not_drifted_post = [s for s in not_drifted if s["temporal_zone"] == "post_cutoff"]
stats["drift_breakdown"] = {
"total_drifted": len(drifted),
"total_not_drifted": len(not_drifted),
"post_cutoff_total": len(post_cutoff),
"post_cutoff_drifted": len(drifted_post),
"post_cutoff_not_drifted": len(not_drifted_post),
"drift_ratio_post_cutoff": round(len(drifted_post) / max(len(post_cutoff), 1), 3),
}
# ============================================================
# 5. KNOWLEDGE TYPE DISTRIBUTION
# ============================================================
kt_counts = Counter(s["knowledge_type"] for s in samples)
stats["knowledge_types"] = {k: {"count": v, "pct": round(100*v/total, 1)}
for k, v in sorted(kt_counts.items())}
# Knowledge type Γ— category
kt_cat = defaultdict(lambda: defaultdict(int))
for s in samples:
kt_cat[s["knowledge_type"]][s["category"]] += 1
stats["knowledge_type_x_category"] = {kt: dict(cats) for kt, cats in sorted(kt_cat.items())}
# ============================================================
# 6. ENTITY ANALYSIS
# ============================================================
all_entities = set(s["entity"] for s in samples)
drifted_entities = set(s["entity"] for s in drifted)
unchanged_entities = set(s["entity"] for s in samples
if s["category"] == "no_drift" and s["knowledge_type"] == "entity_role")
stable_entities = set(s["entity"] for s in samples if s["category"] == "stable")
stats["entities"] = {
"total_unique": len(all_entities),
"drifted_unique": len(drifted_entities),
"unchanged_unique": len(unchanged_entities),
"stable_unique": len(stable_entities),
}
# Per-entity detail for drifted
entity_detail = {}
for s in drifted:
ent = s["entity"]
if ent not in entity_detail:
entity_detail[ent] = {
"relation": s.get("relation", ""),
"old_answer": s.get("model_likely_answer", ""),
"new_answer": s.get("expected_answer", ""),
"change_date": s.get("change_date", ""),
"knowledge_type": s.get("knowledge_type", ""),
"num_queries": 0,
}
entity_detail[ent]["num_queries"] += 1
stats["drifted_entity_details"] = entity_detail
# Per-entity detail for unchanged
unchanged_detail = {}
for s in samples:
if s["category"] == "no_drift" and s["knowledge_type"] == "entity_role":
ent = s["entity"]
if ent not in unchanged_detail:
unchanged_detail[ent] = {
"relation": s.get("relation", ""),
"answer": s.get("expected_answer", ""),
"num_queries": 0,
}
unchanged_detail[ent]["num_queries"] += 1
stats["unchanged_entity_details"] = unchanged_detail
# ============================================================
# 7. YEAR DISTRIBUTION
# ============================================================
year_counts = Counter(s["year"] for s in samples)
stats["year_distribution"] = {str(k): v for k, v in sorted(year_counts.items())}
# Year Γ— drift status
year_drift = defaultdict(lambda: {"drifted": 0, "not_drifted": 0})
for s in samples:
key = "drifted" if s.get("is_drifted_query") else "not_drifted"
year_drift[s["year"]][key] += 1
stats["year_x_drift"] = {str(k): dict(v) for k, v in sorted(year_drift.items())}
# ============================================================
# 8. TEMPLATE / QUERY ANALYSIS
# ============================================================
# Count unique query templates (strip year)
queries = [s["query"] for s in samples]
unique_queries = len(set(queries))
# Identify question vs cloze format
question_format = [s for s in samples if "?" in s["query"] or s["query"].lower().startswith("who")
or s["query"].lower().startswith("what") or s["query"].lower().startswith("which")]
cloze_format = [s for s in samples if "___" in s["query"] or s["query"].endswith(".")]
other_format = [s for s in samples if s not in question_format and s not in cloze_format]
stats["query_formats"] = {
"unique_queries": unique_queries,
"question_format": len(question_format),
"cloze_format": len(cloze_format),
"other_format": len(other_format),
}
# Question vs cloze Γ— drifted
q_drifted = len([s for s in question_format if s.get("is_drifted_query")])
c_drifted = len([s for s in cloze_format if s.get("is_drifted_query")])
stats["query_format_x_drift"] = {
"question_drifted": q_drifted,
"question_not_drifted": len(question_format) - q_drifted,
"cloze_drifted": c_drifted,
"cloze_not_drifted": len(cloze_format) - c_drifted,
}
# ============================================================
# 9. SOURCE DISTRIBUTION
# ============================================================
src_counts = Counter(s.get("source", "unknown") for s in samples)
stats["sources"] = dict(sorted(src_counts.items()))
# ============================================================
# 10. CONFIDENCE DISTRIBUTION
# ============================================================
conf_counts = Counter(s.get("confidence", "unknown") for s in samples)
stats["confidence"] = dict(sorted(conf_counts.items()))
return stats
def print_report(stats):
"""Print a formatted report to console."""
print("\n" + "β–ˆ" * 90)
print("β–ˆ" + " " * 30 + "DATASET STATISTICS REPORT" + " " * 34 + "β–ˆ")
print("β–ˆ" * 90)
# ---- OVERVIEW ----
print_section("1. OVERVIEW")
print(f" Total samples: {stats['total_samples']}")
print(f" Model: {stats['metadata'].get('model', 'N/A')}")
print(f" Model cutoff: {stats['metadata'].get('model_cutoff', 'N/A')}")
print(f" Unique entities: {stats['entities']['total_unique']}")
print(f" Unique queries: {stats['query_formats']['unique_queries']}")
# ---- CATEGORY DISTRIBUTION ----
print_section("2. CATEGORY DISTRIBUTION")
rows = []
for cat, info in stats["categories"].items():
desc = {
"stable": "Timeless facts (capitals, science, math)",
"no_drift": "Could change but didn't (same leader/CEO)",
"unknown_drift": "Changed after cutoff (model doesn't know)",
}.get(cat, "")
rows.append([cat, info["count"], f"{info['pct']}%", desc])
print_table(["Category", "Count", "%", "Description"], rows, [22, 8, 8, 48])
# ---- TEMPORAL ZONE ----
print_section("3. TEMPORAL ZONE DISTRIBUTION")
rows = [[z, info["count"], f"{info['pct']}%"] for z, info in stats["temporal_zones"].items()]
print_table(["Zone", "Count", "%"], rows, [18, 8, 8])
# ---- CROSS-TAB: Category Γ— Zone ----
print_section("4. CATEGORY Γ— TEMPORAL ZONE")
zones = sorted(set(z for zones in stats["category_x_zone"].values() for z in zones))
headers = ["Category"] + zones + ["Total"]
rows = []
for cat, zone_counts in sorted(stats["category_x_zone"].items()):
row = [cat] + [zone_counts.get(z, 0) for z in zones]
row.append(sum(zone_counts.values()))
rows.append(row)
print_table(headers, rows, [22] + [14]*len(zones) + [8])
# ---- DRIFT BREAKDOWN ----
print_section("5. DRIFT ANALYSIS (KEY EXPERIMENTAL GROUPS)")
db = stats["drift_breakdown"]
print(f"\n POST-CUTOFF SAMPLES (the experimental comparison):")
print(f" Total post-cutoff: {db['post_cutoff_total']}")
print(f" β”œβ”€β”€ DRIFTED: {db['post_cutoff_drifted']} ← answer changed, model doesn't know")
print(f" └── NOT DRIFTED: {db['post_cutoff_not_drifted']} ← answer unchanged, model correct")
print(f" Drift ratio: {db['drift_ratio_post_cutoff']:.1%}")
print(f"\n ALL SAMPLES:")
print(f" Drifted queries: {db['total_drifted']}")
print(f" Non-drifted queries: {db['total_not_drifted']}")
# ---- DRIFTED ENTITIES ----
print_section("6. DRIFTED ENTITIES (Post-Cutoff Changes)")
rows = []
for ent, info in sorted(stats["drifted_entity_details"].items()):
rows.append([
ent, info["relation"], info["old_answer"],
info["new_answer"], info["change_date"], info["num_queries"]
])
print_table(
["Entity", "Relation", "Old (pre-cutoff)", "New (post-cutoff)", "Changed", "#Q"],
rows, [18, 14, 28, 28, 12, 5]
)
# ---- UNCHANGED ENTITIES ----
print_section("7. UNCHANGED ENTITIES (Same Type, No Drift β€” Controls)")
rows = []
for ent, info in sorted(stats["unchanged_entity_details"].items()):
rows.append([ent, info["relation"], info["answer"], info["num_queries"]])
print_table(["Entity", "Relation", "Answer (stable)", "#Q"], rows, [18, 16, 32, 5])
# ---- KNOWLEDGE TYPE ----
print_section("8. KNOWLEDGE TYPE DISTRIBUTION")
rows = []
for kt, info in stats["knowledge_types"].items():
rows.append([kt, info["count"], f"{info['pct']}%"])
print_table(["Type", "Count", "%"], rows, [18, 8, 8])
# Knowledge type Γ— category
print("\n Knowledge Type Γ— Category:")
for kt, cats in sorted(stats["knowledge_type_x_category"].items()):
parts = ", ".join(f"{c}={n}" for c, n in sorted(cats.items()))
print(f" {kt:<18} {parts}")
# ---- YEAR DISTRIBUTION ----
print_section("9. YEAR DISTRIBUTION")
rows = []
for year, count in sorted(stats["year_distribution"].items()):
drift_info = stats["year_x_drift"].get(year, {})
d = drift_info.get("drifted", 0)
nd = drift_info.get("not_drifted", 0)
rows.append([year, count, d, nd])
print_table(["Year", "Total", "Drifted", "Not Drifted"], rows, [8, 8, 10, 14])
# ---- QUERY FORMAT ----
print_section("10. QUERY FORMAT ANALYSIS")
qf = stats["query_formats"]
print(f" Question format (Who is...?): {qf['question_format']}")
print(f" Cloze format (X was ___.): {qf['cloze_format']}")
print(f" Other: {qf['other_format']}")
qfd = stats["query_format_x_drift"]
print(f"\n Format Γ— Drift status:")
print(f" Question β€” drifted: {qfd['question_drifted']}, not drifted: {qfd['question_not_drifted']}")
print(f" Cloze β€” drifted: {qfd['cloze_drifted']}, not drifted: {qfd['cloze_not_drifted']}")
# ---- DATA QUALITY ----
print_section("11. DATA QUALITY")
src = stats["sources"]
conf = stats["confidence"]
print(f" Sources:")
for s, c in src.items():
print(f" {s}: {c}")
print(f" Confidence levels:")
for c, n in conf.items():
print(f" {c}: {n}")
# ---- PAPER-READY SUMMARY ----
print_section("12. PAPER-READY SUMMARY")
db = stats["drift_breakdown"]
ent = stats["entities"]
print(f"""
"We construct a temporally-scoped factual knowledge dataset comprising
{stats['total_samples']} query instances across {ent['total_unique']} unique entities.
The dataset spans three categories:
- {stats['categories'].get('unknown_drift', {}).get('count', 0)} queries about {ent['drifted_unique']} entities whose facts
changed after the model's knowledge cutoff (August 2024),
- {stats['categories'].get('no_drift', {}).get('count', 0)} queries about {ent['unchanged_unique']} entities of the same
type that did NOT change (controls), and
- {stats['categories'].get('stable', {}).get('count', 0)} queries about timeless facts (geography, science, math).
Each query is instantiated across {len(stats['year_distribution'])} time points
({', '.join(sorted(stats['year_distribution'].keys()))}), yielding
{db['post_cutoff_drifted']} drifted and {db['post_cutoff_not_drifted']} non-drifted
post-cutoff instances for the primary experimental comparison."
""")
print("=" * 90)
def main():
parser = argparse.ArgumentParser(description="Dataset Statistics")
parser.add_argument("--dataset", default="data/knowledge_drift_clean.json")
parser.add_argument("--output", default=None, help="Output directory for JSON stats")
args = parser.parse_args()
dataset = load_dataset(args.dataset)
stats = compute_stats(dataset)
print_report(stats)
# Save JSON
if args.output:
os.makedirs(args.output, exist_ok=True)
out_path = os.path.join(args.output, "dataset_statistics.json")
with open(out_path, 'w') as f:
json.dump(stats, f, indent=2, ensure_ascii=False)
logger.info(f"Statistics saved to {out_path}")
if __name__ == "__main__":
main()