Download Script/kg/train_kg_embedding.py from JX-Lab/YJT: direct link, hf CLI and curl.
- Browser
- Download file 4.72 kB
-
https://huggingface.co/datasets/JX-Lab/YJT/resolve/main/Script/kg/train_kg_embedding.py
- Command line
-
hf download hf://datasets/JX-Lab/YJT/Script/kg/train_kg_embedding.py
-
curl -L -o train_kg_embedding.py https://huggingface.co/datasets/JX-Lab/YJT/resolve/main/Script/kg/train_kg_embedding.py
4.72 kB
| """训练不含药精标签的中药知识图谱嵌入,并导出实体向量与索引。""" | |
| import json | |
| import time | |
| import pandas as pd | |
| import torch | |
| from pathlib import Path | |
| import sys | |
| from pykeen.models import RotatE | |
| from pykeen.triples import TriplesFactory | |
| from pykeen.training import SLCWATrainingLoop | |
| # ========================= | |
| # 文件路径 | |
| # ========================= | |
| ROOT = Path(__file__).resolve().parents[2] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from Script.project_paths import KG_DIR | |
| TRIPLE_FILE = str(KG_DIR / "tcmkg_triples.tsv") | |
| MODEL_DIR = KG_DIR / "kg_model_label_free" | |
| EMBEDDING_FILE = KG_DIR / "entity_embeddings_label_free.pt" | |
| ENTITY_INDEX_FILE = KG_DIR / "entity_embedding_index_label_free.tsv" | |
| AUDIT_FILE = KG_DIR / "kg_training_audit_label_free.json" | |
| EXCLUDED_RELATIONS = {"has_dunhuang_flavor"} | |
| print("Loading triples...") | |
| triples = pd.read_csv( | |
| TRIPLE_FILE, | |
| sep="\t", | |
| header=None, | |
| names=["head", "relation", "tail"], | |
| dtype=str | |
| ) | |
| print("Triples:", len(triples)) | |
| # 兼容历史文件中可能存在的表头行,并严格排除药精标签关系。 | |
| header_mask = ( | |
| (triples["head"] == "head") | |
| & (triples["relation"] == "relation") | |
| & (triples["tail"] == "tail") | |
| ) | |
| header_rows = int(header_mask.sum()) | |
| if header_rows: | |
| triples = triples.loc[~header_mask].copy() | |
| excluded_counts = { | |
| relation: int((triples["relation"] == relation).sum()) | |
| for relation in sorted(EXCLUDED_RELATIONS) | |
| } | |
| triples = triples.loc[~triples["relation"].isin(EXCLUDED_RELATIONS)].copy() | |
| if triples["relation"].isin(EXCLUDED_RELATIONS).any(): | |
| raise RuntimeError("药精标签关系未被完全移除") | |
| print("Removed header rows:", header_rows) | |
| print("Excluded relations:", excluded_counts) | |
| print("Label-free triples:", len(triples)) | |
| # ========================= | |
| # 转换为 PyKEEN triples | |
| # ========================= | |
| triples_array = triples.values | |
| tf = TriplesFactory.from_labeled_triples(triples_array) | |
| # 使用全部无标签关系训练下游表征,不执行链接预测评估。 | |
| training = tf | |
| entity_index = pd.DataFrame( | |
| sorted(training.entity_to_id.items(), key=lambda item: item[1]), | |
| columns=["entity", "embedding_index"], | |
| ) | |
| entity_index.to_csv(ENTITY_INDEX_FILE, sep="\t", index=False) | |
| print("Entity index saved to:", ENTITY_INDEX_FILE) | |
| print("Start training KG embedding...") | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| print("Using device:", device) | |
| # ========================= | |
| # 训练 | |
| # ========================= | |
| torch.manual_seed(42) | |
| torch.cuda.manual_seed_all(42) | |
| model = RotatE( | |
| triples_factory=training, | |
| embedding_dim=200, | |
| random_seed=42, | |
| ).to(device) | |
| optimizer = torch.optim.Adam(model.get_grad_params(), lr=1e-3) | |
| training_loop = SLCWATrainingLoop( | |
| model=model, | |
| triples_factory=training, | |
| optimizer=optimizer, | |
| negative_sampler="basic", | |
| ) | |
| started_at = time.perf_counter() | |
| losses = training_loop.train( | |
| triples_factory=training, | |
| num_epochs=50, | |
| batch_size=4096, | |
| ) | |
| train_seconds = time.perf_counter() - started_at | |
| print("Training finished") | |
| MODEL_DIR.mkdir(parents=True, exist_ok=True) | |
| torch.save(model, MODEL_DIR / "trained_model.pkl") | |
| torch.save(model.state_dict(), MODEL_DIR / "model_state_dict.pt") | |
| (MODEL_DIR / "losses.json").write_text( | |
| json.dumps(losses, ensure_ascii=False, indent=2), | |
| encoding="utf-8", | |
| ) | |
| print("Model saved") | |
| # ========================= | |
| # 保存实体向量 | |
| # ========================= | |
| entity_embeddings = model.entity_representations[0]().detach().cpu() | |
| if len(entity_embeddings) != len(entity_index): | |
| raise RuntimeError( | |
| "实体嵌入数量与PyKEEN实体映射数量不一致:" | |
| f"{len(entity_embeddings)} != {len(entity_index)}" | |
| ) | |
| torch.save( | |
| entity_embeddings, | |
| EMBEDDING_FILE, | |
| ) | |
| audit = { | |
| "source_file": str(TRIPLE_FILE), | |
| "source_rows": int(len(triples) + sum(excluded_counts.values()) + header_rows), | |
| "removed_header_rows": header_rows, | |
| "excluded_relation_counts": excluded_counts, | |
| "label_free_triples": int(len(triples)), | |
| "training_triples": int(training.num_triples), | |
| "testing_triples": 0, | |
| "entities": int(training.num_entities), | |
| "relations": int(training.num_relations), | |
| "model": "RotatE", | |
| "embedding_dim": 200, | |
| "epochs": 50, | |
| "batch_size": 4096, | |
| "learning_rate": 1e-3, | |
| "random_seed": 42, | |
| "device": str(device), | |
| "train_seconds": train_seconds, | |
| "final_loss": float(losses[-1]) if losses else None, | |
| } | |
| AUDIT_FILE.write_text( | |
| json.dumps(audit, ensure_ascii=False, indent=2), | |
| encoding="utf-8", | |
| ) | |
| print("Entity embeddings saved to:", EMBEDDING_FILE) | |
| print("Training audit saved to:", AUDIT_FILE) | |