python - 从networkX中的随机游走中获取节点列表

标签 python graph machine-learning statistics networkx

我是 networkX 的新手。我创建了一个图表,如下所示:

G = nx.read_edgelist(filename,
                     nodetype=int,
                     delimiter=',',
                     data=(('weight', float),))

其中边为正,但总和不等于 1。

是否有一个内置方法可以从某个节点随机游走k步并返回节点列表?如果不是,最简单的方法是什么(节点可以重复)?

伪代码:

node = random
res = [node]
for i in range(0, k)
    read edge weights from this node
    an edge from this node has probability weight / sum_weights
    node = pick an edge from this node 
    res.append(node)

最佳答案

最简单的方法是使用转移矩阵T,然后使用普通马尔可夫随机游走(简而言之,该图可以被视为有限状态马尔可夫链)。

AD分别为图G的邻接矩阵和度矩阵。转移矩阵T定义为T = D^(-1) A
p^(0) 为状态向量(简而言之,第 i 个分量表示位于节点 i 的概率)步行开始时,第一步(步行)可计算为 p^(1) = T p^(0)。
迭代地,第 k 个随机游走步骤可以计算为 p^(k) = T p^ (k-1)。

用简单的 Networkx 术语来说......

import networkx
import numpy
# let's generate a graph G
G = networkx.gnp_random_graph(5, 0.5)
# let networkx return the adjacency matrix A
A = networkx.adj_matrix(G)
A = A.todense()
A = numpy.array(A, dtype = numpy.float64)
# let's evaluate the degree matrix D
D = numpy.diag(numpy.sum(A, axis=0))
# ...and the transition matrix T
T = numpy.dot(numpy.linalg.inv(D),A)
# let's define the random walk length, say 10
walkLength = 10
# define the starting node, say the 0-th
p = numpy.array([1, 0, 0, 0, 0]).reshape(-1,1)
visited = list()
for k in range(walkLength):
    # evaluate the next state vector
    p = numpy.dot(T,p)
    # choose the node with higher probability as the visited node
    visited.append(numpy.argmax(p))

关于python - 从networkX中的随机游走中获取节点列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37311651/

相关文章:

python - 在 python 中写入文件会出现 ascii 错误

c# - 写入 Windows 中正在运行的进程的标准输入

python - QSTK 的 eventprofiler 函数绘制不正确

r - ggplot2 热图,带条件的色标

python - 当为具有多个输出的模型尝试 train_on_batch 时,Keras 中的 sample_weight 出现问题

python - 如何将 pandas DataFrame 转换为特定的带注释的类 csv 格式(内部描述)

python - "Cloning"行或列向量

algorithm - MST相关算法

python - 西亚诺 'Expected an array-like object, but found a Variable' : Using scan & categorical_crossentropy

machine-learning - 寻找文本中相似的模式