这是在复现论文"Towards accurate subgraph similarity computation via neural graph pruning"时遇到的报错。

ImportError: cannot import name 'uniform' from 'torch_geometric.nn.pool.topk_pool'
一、报错原因
论文作者使用的是2.1.0版本的torch_geometric。而我安装了2.6.0的torch_geometric。新版中已经去除了uniform和maybe_num_nodes这两个函数,所以自然 无法import。

二、解决思路
找出旧版torch_geometric中的函数源代码,将这两个函数复制到自己项目下py脚本,再from这个脚本import这两个函数。
- step 1 创建一个新的虚拟环境,安装旧版本
新建python虚拟环境。创建环境基础教程可以看之前这一篇【Python环境配置基础】-CSDN博客
安装对应的torch 1.12.1 ,torch_geometric 2.1.0以及其他torch相关包。安装教程可以看之前分享的这一篇跑深度学习模型Ⅲ:正确安装与torch版本对应的其他torch包_requirement skipped by policy constraint: torch>=1-CSDN博客
- step 2 找出函数源代码位置

在刚刚新建的虚拟环境下,执行以上命令,即可得到一个文件路径,如D:\....\try_time\lib\site-packages\torch_geometric\init.py。
报错位置代码,是从torch_geometric.nn.pool.topk_pool去import函数的,所以沿着这个路径去找到topk_pool文件。

访问D:\....\try_time\lib\site-packages\torch_geometric\nn\pool,打开topk_pool.py。

- step 3 复制需要的函数代码
在topk_pool.py中搜索uniform,并找到uniform的函数定义代码,将这个函数代码复制到自己项目中的某个位置。我新建了help.py脚本,里面含uniform和maybe_num_nodes函数。


- step 4 更改from..import 代码
将原来的

改为

再运行论文开源代码的experiment.py就不会报错啦~