在度量空间中生成完整的图形

时间:2017-09-21 14:07:40

标签: graph networkx

请给出最简单的方法来生成给定大小为N的完整随机加权无向图,以便权重形成度量空间(服从三角形不等式)。我知道有networkx库但不知道如何做到这一点。

1 个答案:

答案 0 :(得分:1)

虽然@SvenMarnach是正确的,但我想我会提到从networkx中的距离矩阵初始化图表非常容易:

import numpy as np
import networkx as nx

V = 100 # number of nodes
D = 2 # dimensionality

positions = np.random.rand(V, D)
differences = positions[:, None, :] - positions[None, :, :]
distances = np.sqrt(np.sum(differences**2, axis=-1)) # euclidean

# create a weighted, directed graph in networkx
graph = nx.from_numpy_matrix(distances, create_using=nx.DiGraph())