Pytorch Geometric(PyG)入门

PyG (PyTorch Geometric) 是建立在 PyTorch 基础上的一个库,用于轻松编写和训练图形神经网络 (GNN),适用于与结构化数据相关的各种应用。官方文档

Install PyG

PyG适用于python3.8-3.12

一般使用场景:pip install torch_geometric 或conda install pyg -c pyg

Get Started

PyG 具有以下主要功能:

  • Data Handling of Graphs
  • Common Benchmark Datasets
  • Mini-batches
  • Data Transforms
  • Learning Methods on Graphs
  • Exercises

Data Handling of Graphs

PyG 中的单个图由 torch_geometric.data.Data 的一个实例描述,默认情况下该实例拥有以下属性:

  • data.x: Node feature matrix with shape num_nodes, num_node_features
  • data.edge_index: Graph connectivity in COO format with shape 2, num_edges and type torch.long
  • data.edge_attr: Edge feature matrix with shape num_edges, num_edge_features
  • data.y: Target to train against (may have arbitrary shape), e.g., node-level targets of shape num_nodes, \* or graph-level targets of shape 1, \*
  • data.pos: Node position matrix with shape num_nodes, num_dimensions

Colab Notebooks and Video Tutorials

官方文档
Pytroch Geometric Tutorials

Tutorials 1

理解一个节点出发的计算图,理解多次计算图后可能节点信息就包含整个图数据信息了,反而没有用。
对应whl地址

安装torch版本对应的pyg,如下所示:

python 复制代码
import os
import torch
os.environ['TORCH'] = torch.__version__
print(torch.__version__)

!pip install -q torch-scatter -f https://data.pyg.org/whl/torch-${TORCH}.html
!pip install -q torch-sparse -f https://data.pyg.org/whl/torch-${TORCH}.html
!pip install -q git+https://github.com/pyg-team/pytorch_geometric.git

可视化网络的函数实现

python 复制代码
# 可视化函数
%matplotlib inline
import torch
import networkx as nx
import matplotlib.pyplot as plt

# visualization function for NX graph or Pytorch tensor
def visualize(h, color, epoch=None, loss=None):
  plt.figure(figsize=(7,7))
  plt.xticks([])
  plt.yticks([])
  if torch.is_tensor(h):
    # 可视化神经网络运行中间结果
    h = h.detach().cpu().numpy()
    plt.scatter(h[:, 0], h[:, 1], s=140, c=color, cmap="Set2")
    if epoch is not None and loss is not None:
      plt.xlabel(f'Epoch:{epoch}, Loss:{loss.item():.4f}', fontsize=16)
  else:
    nx.draw_networkx(G, pos=nx.spring_layout(G, seed=42), with_labels=False, node_color=color, cmap="Set2")
  plt.show()

例如:

python 复制代码
from torch_geometric.utils import to_networkx

G = to_networkx(data, to_undirected=True)
visualize(G, color=data.y)

如图所示:

参考:

PyTorch Geometric (PyG) 入门教程

相关推荐
vivo互联网技术2 分钟前
AI Agent 技术全景解析 —— 从提示词工程到高级智能体构建
人工智能·agent
武子康6 分钟前
H3-World 的动作能按时发生,为何还不能据此判断实时互动?
人工智能·深度学习·agent
师夷长技以自愈8 分钟前
手搓 AI Agent 第 4 篇:后厨扩招——AI 从此能读、能写、能改、能跑
人工智能
Dawson Zhu35 分钟前
【LLM推理与Serving⑨】业务模型推理引擎开发:以BEV自动驾驶为例的专用推理实践
人工智能·语言模型·架构·aigc·agi
袁俪1 小时前
数字孪生协同
人工智能
海拥✘1 小时前
让 AI 修 AI 平台自己的 Bug:我用 SoduWork 给 SoduWork 提了一个 PR
人工智能·bug
挖掘狂人1 小时前
AI 把代码写得飞快,然后呢?聊聊我验收生成代码的一套流程
人工智能·程序员·ai编程
汤姆宝库1 小时前
推理服务器的调度器:连续批处理与请求生命周期
人工智能
Rocky Ding*2 小时前
【三年面试五年模拟】2026-11-05_月之暗面大模型算法岗一面、二面面经全解析
论文阅读·人工智能·深度学习·机器学习·aigc·强化学习·ai-native
Mirawork2 小时前
Mirawork v0.32.0 更新体验:会话引用、任务分享与音频转写怎么用
人工智能·音视频