quality_report.py
8.8 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""图谱质量对比报告:v1 备份 vs 当前 v2。
用数据回答"抽取到底有没有变好",而不是靠感觉。指标都直指 v1 实测到的问题:
- 噪声实体率:`10分钟`/`验证码`/`文件名` 这类非业务实体的占比
- 度=1 叶子占比 / 孤立点:粒度过细、抽出一堆挂不上关系的碎片
- 类型数与类型熵:v1 炸出 41 种类型(含 77 个"未分类"),着色和过滤都失效
- 归一化后重复组:`盯防周期T` vs `盯防周期 T` 这类没被消歧的重复
- 包含式别名候选:`主机厂` vs `主机厂侧`
- 关系长尾占比:只出现 1~2 次的关系类型占比
用法:
python scripts/quality_report.py
python scripts/quality_report.py --old data/v1_backup/graph.json --new data/graph.json
python scripts/quality_report.py --out report.md
"""
from __future__ import annotations
import argparse
import json
import math
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
# Windows 控制台默认是 GBK,直接 print 乱码字符串会抛 UnicodeEncodeError,
# 反而让"修乱码"的脚本自己先挂掉。这里强制 UTF-8 输出。
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
from app.extract.normalize import is_noise_entity # noqa: E402
from app.store.graph_store import canon_key # noqa: E402
def load_graph(path: Path) -> tuple[list[dict], list[dict]]:
data = json.loads(path.read_text(encoding="utf-8"))
return data.get("nodes", []), data.get("links", data.get("edges", []))
def entropy(counts: list[int]) -> float:
total = sum(counts)
if total <= 0:
return 0.0
return -sum((c / total) * math.log2(c / total) for c in counts if c > 0)
def analyze(path: Path) -> dict:
nodes, links = load_graph(path)
n = len(nodes)
ids = [x["id"] for x in nodes]
deg: Counter = Counter()
for l in links:
deg[l["source"]] += 1
deg[l["target"]] += 1
types = Counter((x.get("type") or "未分类") for x in nodes)
rels = Counter((l.get("relation") or "关联") for l in links)
noise = [i for i in ids if is_noise_entity(i)]
by_key: dict[str, list[str]] = defaultdict(list)
for i in ids:
by_key[canon_key(i)].append(i)
dup_groups = {k: v for k, v in by_key.items() if len(v) > 1}
# 包含式别名候选(和探查 v1 时用的是同一套判定)
alias = 0
ordered = sorted(ids, key=len)
for idx, a in enumerate(ordered):
if len(a) < 3:
continue
for b in ordered[idx + 1:]:
if a in b and len(b) - len(a) <= 4:
alias += 1
break
rel_tail = sum(c for c in rels.values() if c <= 2)
aliases_merged = sum(len(x.get("aliases") or []) for x in nodes)
with_desc = sum(1 for x in nodes if (x.get("description") or "").strip())
isolated = sum(1 for i in ids if deg[i] == 0)
leaf = sum(1 for i in ids if deg[i] == 1)
return {
"文件": str(path),
"实体数": n,
"关系数": len(links),
"噪声实体数": len(noise),
"噪声实体率": len(noise) / n if n else 0.0,
"孤立点": isolated,
"孤立点占比": isolated / n if n else 0.0,
"度=1 叶子": leaf,
"叶子占比": leaf / n if n else 0.0,
"平均度": sum(deg.values()) / n if n else 0.0,
"实体类型数": len(types),
"类型熵": entropy(list(types.values())),
"兜底类型占比": (types.get("未分类", 0) + types.get("其他", 0)) / n if n else 0.0,
"关系类型数": len(rels),
"关系长尾占比": rel_tail / len(links) if links else 0.0,
"归一化重复组": len(dup_groups),
"包含式别名候选": alias,
"已合并别名数": aliases_merged,
"有描述实体占比": with_desc / n if n else 0.0,
"_noise_samples": noise[:15],
"_dup_samples": list(dup_groups.values())[:8],
"_types": types.most_common(),
}
# (指标名, 方向, 是否按百分比展示)
# 方向 "lower" = 越小越好,"higher" = 越大越好,
# "neutral" = 只作规模参照、不判优劣。
# 实体数/关系数刻意是 neutral:去噪和消歧本来就会让数量下降,
# 把"变少"判成"变差"会得出完全相反的结论。
METRICS: list[tuple[str, str, bool]] = [
("实体数", "neutral", False),
("关系数", "neutral", False),
("噪声实体数", "lower", False),
("噪声实体率", "lower", True),
("孤立点", "lower", False),
("度=1 叶子", "lower", False),
("叶子占比", "lower", True),
("平均度", "higher", False),
("实体类型数", "lower", False),
("兜底类型占比", "lower", True),
("类型熵", "lower", False),
("关系类型数", "lower", False),
("关系长尾占比", "lower", True),
("归一化重复组", "lower", False),
("包含式别名候选", "lower", False),
("已合并别名数", "higher", False),
("有描述实体占比", "higher", True),
]
def fmt(v: float, pct: bool) -> str:
if pct:
return f"{v * 100:.1f}%"
if isinstance(v, float) and not v.is_integer():
return f"{v:.2f}"
return f"{int(v)}"
def verdict(old: float, new: float, direction: str) -> str:
if abs(old - new) < 1e-9:
return "持平"
delta = new - old
base = abs(old) if abs(old) > 1e-9 else 1.0
pct = abs(delta) / base * 100
arrow = "↑" if delta > 0 else "↓"
if direction == "neutral":
return f"{arrow} {pct:.0f}%"
improved = (new < old) if direction == "lower" else (new > old)
return f"{'改善' if improved else '变差'} {pct:.0f}%"
def render(old: dict | None, new: dict) -> str:
out = ["# 图谱质量对比报告", ""]
out.append(f"- 新版(v2):`{new['文件']}`")
if old:
out.append(f"- 旧版(v1):`{old['文件']}`")
out += ["", "## 指标对比", ""]
if old:
out.append("| 指标 | v1 | v2 | 变化 |")
out.append("| --- | ---: | ---: | --- |")
for name, direction, pct in METRICS:
out.append(f"| {name} | {fmt(old[name], pct)} | {fmt(new[name], pct)} | "
f"{verdict(old[name], new[name], direction)} |")
else:
out.append("| 指标 | v2 |")
out.append("| --- | ---: |")
for name, _direction, pct in METRICS:
out.append(f"| {name} | {fmt(new[name], pct)} |")
out += ["", "## 实体类型分布(v2)", ""]
out.append("| 类型 | 数量 |")
out.append("| --- | ---: |")
for t, c in new["_types"][:25]:
out.append(f"| {t} | {c} |")
if new["_noise_samples"]:
out += ["", "## v2 仍存在的疑似噪声实体(抽样)", "",
"、".join(f"`{x}`" for x in new["_noise_samples"])]
if new["_dup_samples"]:
out += ["", "## v2 仍存在的归一化重复(抽样)", ""]
for g in new["_dup_samples"]:
out.append(f"- {' / '.join(g)}")
if old:
out += ["", "## 结论", ""]
judged = [(n, d) for n, d, _ in METRICS
if d != "neutral" and abs(new[n] - old[n]) > 1e-9]
wins = [n for n, d in judged if ((new[n] < old[n]) if d == "lower" else (new[n] > old[n]))]
losses = [n for n, d in judged if n not in wins]
out.append(f"可判优劣的指标共 {len(judged)} 项,其中 **{len(wins)} 项改善**、"
f"{len(losses)} 项变差。")
if losses:
out += ["", "变差的项(如实列出,不做粉饰):",
*[f"- {n}:{fmt(old[n], False)} → {fmt(new[n], False)}" for n in losses]]
out += ["", "> 实体数与关系数标为中性:去噪过滤和实体消歧本来就会让数量下降,",
"> 数量少 ≠ 质量差,要看噪声率、重复组、类型集中度这些指标。"]
return "\n".join(out)
def main() -> None:
ap = argparse.ArgumentParser(description="图谱质量对比报告")
ap.add_argument("--old", default="data/v1_backup/graph.json")
ap.add_argument("--new", default="data/graph.json")
ap.add_argument("--out", default="")
args = ap.parse_args()
new_path = Path(args.new)
if not new_path.exists():
print(f"找不到当前图谱:{new_path}")
sys.exit(1)
old_path = Path(args.old)
old = analyze(old_path) if old_path.exists() else None
if old is None:
print(f"(没有找到 v1 备份 {old_path},只输出 v2 单版指标)")
new = analyze(new_path)
report = render(old, new)
if args.out:
Path(args.out).write_text(report, encoding="utf-8")
print(f"报告已写入 {args.out}")
print(report)
if __name__ == "__main__":
main()