Download Script/analysis/agreement_analysis.py from JX-Lab/YJT: direct link, hf CLI and curl.
- Browser
- Download file 9.71 kB
-
https://huggingface.co/datasets/JX-Lab/YJT/resolve/main/Script/analysis/agreement_analysis.py
- Command line
-
hf download hf://datasets/JX-Lab/YJT/Script/analysis/agreement_analysis.py
-
curl -L -o agreement_analysis.py https://huggingface.co/datasets/JX-Lab/YJT/resolve/main/Script/analysis/agreement_analysis.py
9.71 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """在共同候选集上比较无标签KG与其他中药表示的药精预测一致性。""" | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import itertools | |
| import re | |
| import sys | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.metrics import cohen_kappa_score | |
| ROOT = Path(__file__).resolve().parents[2] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from Script.project_paths import ANALYSIS_DIR, RE_DIR, SEED2_CSV | |
| INPUT_FILES = { | |
| "Chem": (RE_DIR / "KNN" / "seed2" / "5_KNN_results_final.csv", "herb"), | |
| "Text1": (RE_DIR / "embedding" / "output" / "KNN_embedding_results.csv", "herb"), | |
| "Text2": (RE_DIR / "embedding" / "output1" / "KNN_embedding_results.csv", "herb"), | |
| "KG": (RE_DIR / "kg" / "pharmacopoeia_herb_predictions_label_free.csv", "pharma_name"), | |
| } | |
| PRIMARY_METHODS = ("Chem", "Text1", "KG") | |
| ALL_METHODS = tuple(INPUT_FILES) | |
| OUT_DIR = ANALYSIS_DIR / "label_free_common" | |
| def clean_name(value): | |
| text = str(value) | |
| text = re.sub(r"(.*?)", "", text) | |
| text = re.sub(r"\(.*?\)", "", text) | |
| return text.strip() | |
| def read_seed_names(): | |
| try: | |
| seed = pd.read_csv(SEED2_CSV, encoding="utf-8-sig") | |
| except UnicodeDecodeError: | |
| seed = pd.read_csv(SEED2_CSV, encoding="gb18030") | |
| seed.columns = seed.columns.str.replace("\ufeff", "", regex=False).str.strip() | |
| return set(seed["herb"].astype(str).str.strip()) | |
| def load_predictions(path, herb_column, seed_names): | |
| try: | |
| frame = pd.read_csv(path, encoding="utf-8-sig") | |
| except UnicodeDecodeError: | |
| frame = pd.read_csv(path, encoding="gb18030") | |
| required = {herb_column, "pred_label"} | |
| missing = required.difference(frame.columns) | |
| if missing: | |
| raise ValueError(f"{path} missing columns: {sorted(missing)}") | |
| frame = frame.copy() | |
| frame["herb_clean"] = frame[herb_column].map(clean_name) | |
| frame["pred_label"] = frame["pred_label"].astype(str).str.strip() | |
| frame = frame.loc[~frame["herb_clean"].isin(seed_names)] | |
| conflicts = ( | |
| frame.groupby("herb_clean")["pred_label"].nunique().loc[lambda values: values > 1] | |
| ) | |
| if not conflicts.empty: | |
| raise ValueError( | |
| f"{path} contains conflicting predictions for: {conflicts.index.tolist()}" | |
| ) | |
| return frame.drop_duplicates(subset=["herb_clean"]).set_index("herb_clean") | |
| def fleiss_kappa(prediction_frame, methods): | |
| labels = sorted( | |
| { | |
| label | |
| for method in methods | |
| for label in prediction_frame[method].astype(str).unique() | |
| } | |
| ) | |
| counts = np.array([ | |
| [(row[list(methods)] == label).sum() for label in labels] | |
| for _, row in prediction_frame.iterrows() | |
| ], dtype=float) | |
| raters = len(methods) | |
| observed = ((counts ** 2).sum(axis=1) - raters) / (raters * (raters - 1)) | |
| category_proportions = counts.sum(axis=0) / (len(counts) * raters) | |
| expected = (category_proportions ** 2).sum() | |
| if np.isclose(expected, 1.0): | |
| return np.nan | |
| def fleiss_kappa(prediction_frame, methods): | |
| label_columns = [f"{method}_label" for method in methods] | |
| labels = sorted( | |
| { | |
| label | |
| for column in label_columns | |
| for label in prediction_frame[column].astype(str).unique() | |
| } | |
| ) | |
| counts = np.array([ | |
| [(row[label_columns] == label).sum() for label in labels] | |
| for _, row in prediction_frame.iterrows() | |
| ], dtype=float) | |
| raters = len(methods) | |
| observed = ((counts ** 2).sum(axis=1) - raters) / (raters * (raters - 1)) | |
| category_proportions = counts.sum(axis=0) / (len(counts) * raters) | |
| expected = (category_proportions ** 2).sum() | |
| if np.isclose(expected, 1.0): | |
| return np.nan | |
| return float((observed.mean() - expected) / (1.0 - expected)) | |
| OUT_DIR.mkdir(parents=True, exist_ok=True) | |
| seed_names = read_seed_names() | |
| predictions = { | |
| method: load_predictions(path, herb_column, seed_names) | |
| for method, (path, herb_column) in INPUT_FILES.items() | |
| } | |
| herb_sets = { | |
| method: set(frame.index) | |
| for method, frame in predictions.items() | |
| } | |
| common_herbs = set.intersection(*herb_sets.values()) | |
| coverage_rows = [ | |
| { | |
| "method": method, | |
| "available_candidates": len(herb_sets[method]), | |
| "common_candidates": len(common_herbs), | |
| "excluded_outside_common_set": len(herb_sets[method] - common_herbs), | |
| } | |
| for method in ALL_METHODS | |
| ] | |
| pd.DataFrame(coverage_rows).to_csv( | |
| OUT_DIR / "method_coverage.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| candidate_rows = [] | |
| agreement_pair_rows = [] | |
| for herb in sorted(common_herbs): | |
| labels_by_method = { | |
| method: predictions[method].at[herb, "pred_label"] | |
| for method in ALL_METHODS | |
| } | |
| methods_by_label = defaultdict(list) | |
| for method, label in labels_by_method.items(): | |
| methods_by_label[label].append(method) | |
| max_support = max(len(methods) for methods in methods_by_label.values()) | |
| top_labels = sorted( | |
| label | |
| for label, methods in methods_by_label.items() | |
| if len(methods) == max_support | |
| ) | |
| consensus_label = top_labels[0] if len(top_labels) == 1 else "" | |
| primary_methods_by_label = defaultdict(list) | |
| for method in PRIMARY_METHODS: | |
| primary_methods_by_label[labels_by_method[method]].append(method) | |
| primary_max_support = max( | |
| len(methods) for methods in primary_methods_by_label.values() | |
| ) | |
| primary_top_labels = sorted( | |
| label | |
| for label, methods in primary_methods_by_label.items() | |
| if len(methods) == primary_max_support | |
| ) | |
| primary_consensus_label = ( | |
| primary_top_labels[0] if len(primary_top_labels) == 1 else "" | |
| ) | |
| candidate_rows.append({ | |
| "herb": herb, | |
| **{f"{method}_label": labels_by_method[method] for method in ALL_METHODS}, | |
| "consensus_label": consensus_label, | |
| "max_support_count": max_support, | |
| "primary_consensus_label": primary_consensus_label, | |
| "primary_max_support_count": primary_max_support, | |
| "name_baseline_agrees_with_primary": bool( | |
| primary_consensus_label | |
| and labels_by_method["Text2"] == primary_consensus_label | |
| ), | |
| }) | |
| for label, supporting_methods in sorted(methods_by_label.items()): | |
| agreement_pair_rows.append({ | |
| "herb": herb, | |
| "pred_label": label, | |
| "methods": "+".join(supporting_methods), | |
| "method_count": len(supporting_methods), | |
| "primary_method_count": sum( | |
| method in PRIMARY_METHODS for method in supporting_methods | |
| ), | |
| }) | |
| candidate_df = pd.DataFrame(candidate_rows) | |
| agreement_df = pd.DataFrame(agreement_pair_rows) | |
| candidate_df.to_csv( | |
| OUT_DIR / "candidate_predictions.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| agreement_df.to_csv( | |
| OUT_DIR / "agreement_pairs.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| for support_count, output_name in ( | |
| (4, "four_methods_overlap.csv"), | |
| (3, "three_methods_overlap.csv"), | |
| (2, "two_methods_overlap.csv"), | |
| (1, "one_method_only.csv"), | |
| ): | |
| agreement_df.loc[agreement_df["method_count"] == support_count].to_csv( | |
| OUT_DIR / output_name, | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| agreement_df.loc[agreement_df["method_count"] >= 3].to_csv( | |
| OUT_DIR / "high_agreement_pairs.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| agreement_df.loc[agreement_df["primary_method_count"] == len(PRIMARY_METHODS)].to_csv( | |
| OUT_DIR / "primary_three_methods_overlap.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| pairwise_rows = [] | |
| for method_a, method_b in itertools.combinations(ALL_METHODS, 2): | |
| labels_a = candidate_df[f"{method_a}_label"] | |
| labels_b = candidate_df[f"{method_b}_label"] | |
| pairwise_rows.append({ | |
| "method_a": method_a, | |
| "method_b": method_b, | |
| "n_candidates": len(candidate_df), | |
| "agreement_rate": float((labels_a == labels_b).mean()), | |
| "cohen_kappa": float(cohen_kappa_score(labels_a, labels_b)), | |
| }) | |
| pd.DataFrame(pairwise_rows).to_csv( | |
| OUT_DIR / "pairwise_agreement.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| overall_df = pd.DataFrame([ | |
| { | |
| "methods": "+".join(ALL_METHODS), | |
| "n_methods": len(ALL_METHODS), | |
| "n_candidates": len(candidate_df), | |
| "fleiss_kappa": fleiss_kappa(candidate_df, ALL_METHODS), | |
| }, | |
| { | |
| "methods": "+".join(PRIMARY_METHODS), | |
| "n_methods": len(PRIMARY_METHODS), | |
| "n_candidates": len(candidate_df), | |
| "fleiss_kappa": fleiss_kappa(candidate_df, PRIMARY_METHODS), | |
| }, | |
| ]) | |
| overall_df.to_csv( | |
| OUT_DIR / "overall_agreement.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| support_distribution = ( | |
| candidate_df["max_support_count"] | |
| .value_counts() | |
| .sort_index() | |
| .rename_axis("max_support_count") | |
| .reset_index(name="candidate_count") | |
| ) | |
| support_distribution.to_csv( | |
| OUT_DIR / "candidate_support_distribution.csv", | |
| index=False, | |
| encoding="utf-8-sig", | |
| ) | |
| plt.figure(figsize=(6, 4)) | |
| plt.bar( | |
| support_distribution["max_support_count"].astype(str), | |
| support_distribution["candidate_count"], | |
| ) | |
| plt.xlabel("Maximum number of methods supporting the same label") | |
| plt.ylabel("Number of candidate herbs") | |
| plt.tight_layout() | |
| plt.savefig(OUT_DIR / "agreement_barplot.png", dpi=300) | |
| plt.close() | |
| print("Common candidate herbs:", len(common_herbs)) | |
| print(pd.DataFrame(coverage_rows).to_string(index=False)) | |
| print("Candidate support distribution:") | |
| print(support_distribution.to_string(index=False)) | |
| print("Saved to:", OUT_DIR) | |