欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Pytorch Geometric(PyG)入门

Pytorch Geometric(PyG)入门

2024/10/24 4:44:06 来源:https://blog.csdn.net/Misnearch/article/details/139864876  浏览:    关键词:Pytorch Geometric(PyG)入门

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

Install PyG

PyG适用于python3.8-3.12
一般使用场景:pip install torch_geometricconda 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,如下所示:

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

可视化网络的函数实现

# 可视化函数
%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()

例如:

from torch_geometric.utils import to_networkxG = to_networkx(data, to_undirected=True)
visualize(G, color=data.y)

如图所示:
在这里插入图片描述

参考:

PyTorch Geometric (PyG) 入门教程

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com