gpt4 book ai didi

python - NetworkX DiGraph() 到 Graph() 的边权重未求和,如何求和?

转载 作者:行者123 更新时间:2023-12-01 05:02:31 24 4
gpt4 key购买 nike

我有一些关系数据想要加载到 NetworkX 中,并最终将其转换为加权图。

本质上,关系边是有向和加权的,我想在转换图形时保留权重属性。使用以下代码,我能够将关系边从字典加载到 MultiDiGraph():

MG = nx.MultiDiGraph([(i['source'],i['target']) for i in edges ])

然后,我将 MultiDiGraph() 转换为 DiGraph(),并将重复的边压缩为一条,并更新每条边的边权重:

G = nx.DiGraph()
for (u,v) in MG.edges():
G.add_edge(u, v, weight=len(MG[u][v]))

从这里开始,我想将DiGraph()转换为Graph(),并再次保留并压缩边权重:

g = G.to_undirected()

但我遇到的问题是,它似乎保留了 'a' -> 'b''b' -> 'a'< 找到的第一个边缘权重.

我想要的是在到达无向边时将这些边的总和保持为权重。

下面是我正在使用的示例:

# relational directed edge data containing duplicate edges 
edges = [{'source': 'a', 'target': 'b'},
{'source': 'a', 'target': 'b'},
{'source': 'a', 'target': 'b'},
{'source': 'b', 'target': 'a'},
{'source': 'a', 'target': 'c'},
{'source': 'c', 'target': 'a'},
{'source': 'c', 'target': 'd'},
{'source': 'c', 'target': 'd'},
{'source': 'd', 'target': 'c'}]

# load edges into a MultiDiGraph to maintain direction and duplicate edges
MG = nx.MultiDiGraph([(i['source'],i['target']) for i in edges ])

MG.edges(data=True) = [('a', 'c', {}),
('a', 'b', {}),
('a', 'b', {}),
('a', 'b', {}),
('c', 'a', {}),
('c', 'd', {}),
('c', 'd', {}),
('b', 'a', {}),
('d', 'c', {})]

# convert MultiDiGraph to a DiGraph and update edge weight
G = nx.DiGraph()
for (u,v) in MG.edges():
G.add_edge(u, v, weight=len(MG[u][v]))

G.edges(data=True) = [('a', 'c', {'weight': 1}),
('a', 'b', {'weight': 3}),
('c', 'a', {'weight': 1}),
('c', 'd', {'weight': 2}),
('b', 'a', {'weight': 1}),
('d', 'c', {'weight': 1})]

# convert DiGraph to a Graph, but edge weight not updated as sum, but first value
g = G.to_undirected()

g.edges(data=True) = [('a', 'c', {'weight': 1}),
('a', 'b', {'weight': 1}),
('c', 'd', {'weight': 1})]

最终,我希望无向图中的边权重如下,但我无法弄清楚这是否是 G.to_undirected 的选项或如何执行此操作:

g.edges(data=True) = [('a', 'c', {'weight': 2}),
('a', 'b', {'weight': 4}),
('c', 'd', {'weight': 3})]

最佳答案

G.to_undirected() 不能用于控制无向边获取哪些数据,参见 networkx docs

您可以执行以下操作:

import networkx as nx

G = nx.DiGraph()
G.add_edges_from([('a', 'c', {'weight': 1}),
('a', 'b', {'weight': 3}),
('c', 'a', {'weight': 1}),
('c', 'd', {'weight': 2}),
('b', 'a', {'weight': 1}),
('d', 'c', {'weight': 1})])

print G.edges(data=True)

g = nx.Graph()
g.add_edges_from(G.edges_iter(), weight=0)

print g.edges(data=True)

for u, v, d in G.edges_iter(data=True):
g[u][v]['weight'] += d['weight']

print g.edges(data=True)

基本上,您创建一个新的无向图 g 并用有向图 G 中的所有边填充它。此时,您还将边的权重初始化为 0。最后,您只需将权重添加到无向图 G 中的每条边图形。请注意,在无向图中,边 (u, v) 与 (v, u) 相同。

关于python - NetworkX DiGraph() 到 Graph() 的边权重未求和,如何求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25778137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com