You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyGeometric为异构图添加边特征时的异常问题

问题

在ArchLinux虚拟环境中使用PyGeometric的HeteroData类为异构图添加边特征时出现异常,环境版本:

  • Python 3.11.5
  • PyTorch 2.0.1+cu117
  • TorchGeometric 2.3.1

执行代码后节点特征可正常获取,但边特征设置后出现以下问题:

  • data.num_edge_features返回{('author', 'writes', 'paper'): 0}
  • data.edge_attrs()仅输出['edge_index']
  • 尽管edge_stores中存在x属性,但无法被PyG内置方法识别为边特征

代码片段:

import torch
from torch_geometric.data import HeteroData

data = HeteroData()

# Params
num_papers, num_paper_features = 5, 7
num_authors, num_author_features = 4, 10
num_edges = torch.randint(5, num_papers*num_authors, [1]).item()
author_writes_paper_num_features = 4

# Adding features to nodes
data['paper'].x = torch.randn(num_papers, num_paper_features)
data['author'].x = torch.randn(num_authors, num_author_features)

# Creating some random edges
author_edge_index = torch.randint(0, num_authors, [num_edges])
paper_edge_index = torch.randint(0, num_papers, [num_edges])
edge_index = torch.stack((author_edge_index, paper_edge_index))
data['author', 'writes', 'paper'].edge_index = edge_index

data = data.coalesce()

# Adding features to edges
data['author', 'writes', 'paper'].x = torch.randn(author_writes_paper_num_features, data.num_edges)

# Also tried using the transpose edge feature matrix 
# data['author', 'writes', 'paper'].x = torch.randn(data.num_edges, author_writes_paper_num_features)

解决方法

问题核心是PyGeometric的HeteroData中,边特征的约定命名是edge_attr而非x——x是节点特征的标准命名,PyG内置方法仅会识别edge_attr作为边特征字段。

修正步骤

  1. 将边特征的字段名从x改为edge_attr
  2. 确保边特征维度正确:形状应为[num_edges, num_edge_features](行代表边数,列代表特征数)

修正后的边特征设置代码:

# 替换原边特征赋值代码
edge_store = data['author', 'writes', 'paper']
edge_store.edge_attr = torch.randn(edge_store.num_edges, author_writes_paper_num_features)

验证效果

  • 执行data.num_edge_features会返回{('author', 'writes', 'paper'): 4}
  • data.edge_attrs()会输出['edge_attr']
  • 后续可通过data['author', 'writes', 'paper'].edge_attr正常访问边特征

额外注意

调用coalesce()后可能会合并重复边,导致边数变化,直接使用对应边存储的num_edges(而非全局data.num_edges)能避免维度不匹配问题,尤其当图中存在多种边类型时。

内容的提问来源于stack exchange,提问作者Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:50:11