在 networkx 中添加和删除随机边

way*_*217 1 python random graph networkx

我在 python 中使用 NetworkX。给定任何无向和未加权的图,我想遍历所有节点。对于每个节点,我想以概率 p 为该节点添加一条随机边和/或删除现有的随机边。有没有一种简单的方法可以做到这一点?非常感谢!

mic*_*elg 7

在 networkx 中创建一个新的随机边

让我们建立一个测试图:

import networkx as nx
import random
import matplotlib.pyplot as plt

graph = nx.Graph()
graph.add_edges_from([(1,3), (3,5), (2,4)])
nx.draw(graph, with_labels=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)

图1

现在我们可以从图中的非边列表中选择一条随机边。目前还不完全清楚你提到的概率是多少。由于您添加了一条说明您想使用的评论,因此random.choice我会坚持下去。

def random_edge(graph, del_orig=True):
    '''
    Create a new random edge and delete one of its current edge if del_orig is True.
    :param graph: networkx graph
    :param del_orig: bool
    :return: networkx graph
    '''
    edges = list(graph.edges)
    nonedges = list(nx.non_edges(graph))

    # random edge choice
    chosen_edge = random.choice(edges)
    chosen_nonedge = random.choice([x for x in nonedges if chosen_edge[0] == x[0]])

    if del_orig:
        # delete chosen edge
        graph.remove_edge(chosen_edge[0], chosen_edge[1])
    # add new edge
    graph.add_edge(chosen_nonedge[0], chosen_nonedge[1])

    return graph
Run Code Online (Sandbox Code Playgroud)

用法示例:

new_graph = random_edge(graph, del_orig=True)

nx.draw(new_graph, with_labels=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)

图2

random.choice如果需要,我们仍然可以在边缘上添加概率分布(numpy.random.choice()例如使用)。