首页 > 解决方案 > ImportError:无法导入名称'treewidth'

问题描述

我一直在尝试从 NetworkX 库中导入必要的模块,但它不断抛出 ImportError 或 AttributeError。

我在最后一年的项目中使用 NetworkX 库,我想使用这个函数来计算给定图的树宽分解,我需要其他函数的值。

我尝试了以下事情:

  1. 最初我尝试导入文档中建议的方式
import networkx as nx 
from networkx.algorithms import approximation

G = nx.barbell_graph(5, 1)

decom = approximation.treewidth_min_fill_in(G)

但这只会给我以下错误:

AttributeError: module 'networkx.algorithms.approximation' has no attribute 'treewidth_min_fill_in'
  1. 我还尝试使用以下方法直接导入它:
import networkx as nx

G = nx.barbell_graph(5, 1)

decom = nx.algorithms.approximation.treewidth.treewidth_min_fill_in(G) 

但这只会给我以下错误:

AttributeError: module 'networkx.algorithms.approximation' has no attribute 'treewidth'
  1. 然后我在这里找到了一个可能的解决方案,它仅在派系的情况下有效,但在尝试导入“treewidth”时无效。
import networkx as nx 
from networkx.algorithms.approximation import treewidth

G = nx.barbell_graph(5, 1)

decom = treewidth.treewidth_min_fill_in(G)

但这只会给我以下错误:

ImportError: cannot import name 'treewidth'

我没有成功找到解决方案。任何帮助表示赞赏!

注意:这是我关于 SO 的第一个问题,因此请就这个问题的格式提供任何额外的反馈。

标签: pythonnetworkx

解决方案


你使用哪个版本的 networkx 包,你是如何安装它的?

我尝试pip install networkx使用 Python 3.7 执行然后执行您的代码:

import networkx as nx 
from networkx.algorithms import approximation

G = nx.barbell_graph(5, 1)

decom = approximation.treewidth_min_fill_in(G)
print(decom)

输出是:

(4, <networkx.classes.graph.Graph object at 0x1070d4ef0>)

您可以尝试使用以下方法查看模块的版本:

import networkx
print(networkx.__version__)

以及使用了哪些方法:

import networkx
from networkx.algorithms import approximation

print(dir(approximation))

推荐阅读