Download v2_code/compute_kappa.py from LHUThacSi/ViSportSent: direct link, hf CLI and curl.
- Browser
- Download file 4.74 kB
-
https://huggingface.co/datasets/LHUThacSi/ViSportSent/resolve/main/v2_code/compute_kappa.py
- Command line
-
hf download hf://datasets/LHUThacSi/ViSportSent/v2_code/compute_kappa.py
-
curl -L -o compute_kappa.py https://huggingface.co/datasets/LHUThacSi/ViSportSent/resolve/main/v2_code/compute_kappa.py
4.74 kB
| """ | |
| compute_kappa.py | |
| ───────────────── | |
| Tính Cohen's κ pairwise + Fleiss' κ cho 3 annotator LLM | |
| (Claude, Gemini, GPT) trên cột sentiment_claude / _gemini / _gpt. | |
| Cài đặt: | |
| pip install pandas scikit-learn statsmodels | |
| Chạy: | |
| python compute_kappa.py | |
| python compute_kappa.py --input combined_dataset_merged_v1_final.csv | |
| """ | |
| import argparse | |
| import pandas as pd | |
| from sklearn.metrics import cohen_kappa_score, confusion_matrix | |
| from statsmodels.stats.inter_rater import fleiss_kappa, aggregate_raters | |
| LABELS = ["negative", "neutral", "positive"] | |
| RATERS = ["sentiment_claude", "sentiment_gemini", "sentiment_gpt"] | |
| def kappa_interpretation(k: float) -> str: | |
| """Phân loại Landis & Koch (1977).""" | |
| if k < 0: return "poor (< 0)" | |
| if k < 0.20: return "slight (0.00–0.20)" | |
| if k < 0.40: return "fair (0.21–0.40)" | |
| if k < 0.60: return "moderate (0.41–0.60)" | |
| if k < 0.80: return "substantial (0.61–0.80)" | |
| return "almost perfect (0.81–1.00)" | |
| def main(input_path: str): | |
| df = pd.read_csv(input_path, encoding="utf-8-sig") | |
| print(f"📂 Đọc {len(df):,} dòng từ {input_path}") | |
| missing = [c for c in RATERS if c not in df.columns] | |
| if missing: | |
| raise SystemExit(f"❌ Thiếu cột: {missing}") | |
| sub = df.dropna(subset=RATERS).copy() | |
| print(f" {len(sub):,} dòng có đủ ba nhãn ({len(sub)/len(df)*100:.1f}%)") | |
| # ── 1. Cohen's κ pairwise ──────────────────────────────────────────────── | |
| print("\n=== Cohen's κ (pairwise) ===") | |
| pairs = [(RATERS[0], RATERS[1]), | |
| (RATERS[0], RATERS[2]), | |
| (RATERS[1], RATERS[2])] | |
| cohen_results = {} | |
| for a, b in pairs: | |
| k = cohen_kappa_score(sub[a], sub[b], labels=LABELS) | |
| cohen_results[(a, b)] = k | |
| print(f" {a:18s} vs {b:18s} κ = {k:.4f} ({kappa_interpretation(k)})") | |
| # ── 2. Fleiss' κ (3 raters, 3 categories) ──────────────────────────────── | |
| print("\n=== Fleiss' κ ===") | |
| data = sub[RATERS].values | |
| table, cats = aggregate_raters(data) | |
| k_fleiss = fleiss_kappa(table, method="fleiss") | |
| print(f" Categories : {list(cats)}") | |
| print(f" Subjects : {table.shape[0]:,}") | |
| print(f" Fleiss' κ = {k_fleiss:.4f} ({kappa_interpretation(k_fleiss)})") | |
| # ── 3. Tỉ lệ đồng thuận và phân bố nhãn ───────────────────────────────── | |
| if "agreement" in df.columns: | |
| agree3 = (sub["agreement"] == 1).sum() | |
| print(f"\n=== Đồng thuận 3/3 ===") | |
| print(f" 3/3 đồng ý : {agree3:,} ({agree3/len(sub)*100:.2f}%)") | |
| print(f" Bất đồng : {len(sub)-agree3:,} ({(len(sub)-agree3)/len(sub)*100:.2f}%)") | |
| print("\n=== Phân bố nhãn theo từng rater ===") | |
| for col in RATERS: | |
| d = sub[col].value_counts().reindex(LABELS, fill_value=0) | |
| total = d.sum() | |
| print(f"\n[{col}] (n = {total:,})") | |
| for lbl, n in d.items(): | |
| print(f" {lbl:9s}: {n:6,} ({n/total*100:5.2f}%)") | |
| # ── 4. Ma trận lẫn (giúp viết phần Bàn luận) ───────────────────────────── | |
| print("\n=== Confusion matrix: Claude vs GPT ===") | |
| cm = confusion_matrix(sub[RATERS[0]], sub[RATERS[2]], labels=LABELS) | |
| cm_df = pd.DataFrame(cm, | |
| index=[f"Claude={l}" for l in LABELS], | |
| columns=[f"GPT={l}" for l in LABELS]) | |
| print(cm_df.to_string()) | |
| # ── 5. Tóm tắt để dán vào bài báo ─────────────────────────────────────── | |
| print("\n" + "=" * 60) | |
| print("📋 Đoạn văn dán thẳng vào mục Inter-annotator agreement:") | |
| print("=" * 60) | |
| k_cg = cohen_results[(RATERS[0], RATERS[1])] | |
| k_cp = cohen_results[(RATERS[0], RATERS[2])] | |
| k_gp = cohen_results[(RATERS[1], RATERS[2])] | |
| print( | |
| f"On {len(sub):,} comments with three independent labels, " | |
| f"pairwise Cohen's κ ranges from {min(k_cg, k_cp, k_gp):.2f} " | |
| f"to {max(k_cg, k_cp, k_gp):.2f}; overall Fleiss' κ across the " | |
| f"three raters is {k_fleiss:.4f}, which corresponds to substantial " | |
| f"agreement under the Landis and Koch (1977) classification." | |
| ) | |
| if __name__ == "__main__": | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--input", default="combined_dataset_merged_v1_final.csv") | |
| args = p.parse_args() | |
| main(args.input) | |