torch_cluster.random_walk()函数

torch_cluster链接

作用:Samples random walks of length walk_length from all node indices in start in the graph given by (row, col).

1、 以官网给出的例子生成有向图

import matplotlib.pyplot as plt
import networkx as nx
row = [0, 1, 1, 1, 2, 2, 3, 3, 4, 4]
col = [1, 0, 2, 3, 1, 4, 1, 4, 2, 3]
g = nx.DiGraph()
g.add_edges_from(list(zip(row, col)))
nx.draw(g, with_labels=True) 
plt.show()

xxx

2、在图上进行随机游走

import torch
from torch_cluster import random_walk

row = torch.tensor([0, 1, 1, 1, 2, 2, 3, 3, 4, 4])
col = torch.tensor([1, 0, 2, 3, 1, 4, 1, 4, 2, 3])
start = torch.tensor([0, 1, 2, 3, 4])

walk = random_walk(row, col, start, walk_length=3)
print(walk)

返回列表:shape(节点个数, 长度+1)

tensor([[0, 1, 2, 4],
        [1, 3, 4, 2],
        [2, 4, 2, 1],
        [3, 4, 2, 4],
        [4, 3, 1, 0]])

每次运行结果都有随机性, 大家可以自己验证一下
在这里插入图片描述
在这里插入图片描述

### 安装 `torch_geometric` 和其子模块 为了成功安装并使用 `torch_geometric.nn` 模块,需要遵循特定的步骤来确保所有依赖项正确配置。以下是详细的说明: #### 1. 环境准备 确保 Python 版本兼容(推荐使用 Python 3.8 或更高版本)。此外,确认已安装 CUDA 驱动程序以及相应的 cuDNN 库(如果计划在 GPU 上运行模型),或者可以仅基于 CPU 进行开发。 #### 2. 安装 PyTorch PyTorch 是 `torch_geometric` 的基础库,因此需先安装合适的 PyTorch 版本。可以通过以下命令完成安装: ```bash pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 ``` 上述命令适用于 NVIDIA CUDA 11.8 的环境。如果没有 GPU 支持,则可移除 `--index-url` 参数以安装纯 CPU 版本[^1]。 #### 3. 安装 `torch-geometric` 由于 `torch_geometric` 对应的具体版本与其依赖项紧密关联,建议按照官方文档中的方法进行安装。例如,对于指定版本的安装,可以执行如下命令: ```bash pip install torch-scatter torch-sparse torch-cluster torch-spline-conv torch-geometric -f https://data.pyg.org/whl/torch-2.0.0+cu118.html ``` 此 URL 中包含了针对 PyTorch 2.0.0 和 CUDA 11.8 的预编译二进制文件。如果使用的 PyTorch 版本不同,请调整链接地址至匹配的版本号[^2]。 #### 4. 解决常见错误 当尝试导入 `torch_geometric` 而未预先安装必要的扩展包时,可能会触发类似以下的错误提示: ``` ModuleNotFoundError: No module named 'torch_geometric.utils.to_dense_adj' ``` 这是因为在某些情况下,核心功能依赖于额外的组件如 `torch_sparse`、`torch_cluster` 等。这些工具必须单独引入才能正常工作[^3]。 #### 5. 使用 `torch_geometric.nn` 一旦完成了以上准备工作,就可以顺利调用 `torch_geometric.nn` 提供的各种神经网络层定义及其辅助函数。下面是一个简单的例子展示如何构建 GNN 模型结构: ```python from torch_geometric.datasets import Planetoid import torch_geometric.transforms as T from torch_geometric.nn import GCNConv dataset = Planetoid(root='/tmp/Cora', name='Cora', transform=T.NormalizeFeatures()) model = GCNConv(dataset.num_node_features, dataset.num_classes) print(model) ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值