File size: 4,720 Bytes
58f9a51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""训练不含药精标签的中药知识图谱嵌入,并导出实体向量与索引。"""

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)