文档 1.7 版本已不再积极维护,你当前浏览的是一份归档快照。
最新文档请参阅 最新版本。
HugeGraph-ML
HugeGraph-ML 从 HugeGraph 读取图数据并转换为 DGL 图,供节点嵌入、节点分类和图分类等任务使用。模型实现位于 hugegraph-ml/src/hugegraph_ml/models/。
环境要求
- Python 3.10 或更高版本
- HugeGraph Server 1.0 或更高版本,推荐 1.5 及以上版本
uv 0.7 或更高版本
安装
1git clone https://github.com/apache/hugegraph-ai.git
2cd hugegraph-ai
3uv sync --extra ml
4source .venv/bin/activate
5cd hugegraph-ml/src
HugeGraph-ML 是根项目的路径依赖,但不属于 uv workspace members。应在仓库根目录选择 ml extra,不要在子目录建立另一套锁文件。
已实现模型
当前 README 列出的模型如下:
源码中还包含 GIN 图分类实现和供下游分类使用的 MLPClassifier。模型数量会随版本变化,以 src/hugegraph_ml/models/ 为准。
DGI 节点嵌入示例
先把 DGL 的 Cora 数据集导入 HugeGraph:
1from hugegraph_ml.utils.dgl2hugegraph_utils import import_graph_from_dgl
2
3import_graph_from_dgl("cora")
读取图并训练 DGI:
1from hugegraph_ml.data.hugegraph2dgl import HugeGraph2DGL
2from hugegraph_ml.models.dgi import DGI
3from hugegraph_ml.models.mlp import MLPClassifier
4from hugegraph_ml.tasks.node_classify import NodeClassify
5from hugegraph_ml.tasks.node_embed import NodeEmbed
6
7hg2d = HugeGraph2DGL()
8graph = hg2d.convert_graph(
9 vertex_label="CORA_vertex",
10 edge_label="CORA_edge",
11)
12
13embed_model = DGI(n_in_feats=graph.ndata["feat"].shape[1])
14embed_task = NodeEmbed(graph=graph, model=embed_model)
15embedded_graph = embed_task.train_and_embed(
16 add_self_loop=True,
17 n_epochs=300,
18 patience=30,
19)
20
21classifier = MLPClassifier(
22 n_in_feat=embedded_graph.ndata["feat"].shape[1],
23 n_out_feat=embedded_graph.ndata["label"].unique().shape[0],
24)
25classify_task = NodeClassify(graph=embedded_graph, model=classifier)
26classify_task.train(lr=1e-3, n_epochs=400, patience=40)
27print(classify_task.evaluate())
完整脚本是 hugegraph-ml/src/hugegraph_ml/examples/dgi_example.py。
GRAND 节点分类示例
1from hugegraph_ml.data.hugegraph2dgl import HugeGraph2DGL
2from hugegraph_ml.models.grand import GRAND
3from hugegraph_ml.tasks.node_classify import NodeClassify
4
5hg2d = HugeGraph2DGL()
6graph = hg2d.convert_graph(
7 vertex_label="CORA_vertex",
8 edge_label="CORA_edge",
9)
10model = GRAND(
11 n_in_feats=graph.ndata["feat"].shape[1],
12 n_out_feats=graph.ndata["label"].unique().shape[0],
13)
14task = NodeClassify(graph, model)
15task.train(lr=1e-2, weight_decay=5e-4, n_epochs=2000, patience=100)
16print(task.evaluate())
完整脚本是 hugegraph-ml/src/hugegraph_ml/examples/grand_example.py。
排查问题
- 连接失败:检查 HugeGraph Server 地址、端口和认证信息。
- Schema 不匹配:示例默认使用
CORA_vertex 和 CORA_edge,自有数据需要传入实际标签。 - DGL 或 PyTorch 导入失败:回到仓库根目录重新执行
uv sync --extra ml,并确认当前 Python 来自根目录 .venv。