在Python中如何计算加权邻接矩阵的拓扑重叠测度?

2024-09-28 22:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算一个邻接矩阵的加权拓扑重叠,但我无法使用numpy来正确计算。{{{{3}的实现是正确的。计算这个的公式(我认为)equation 4中有详细说明,我相信下面正确地复制了这个公式。在

enter image description here

是否有人知道如何正确实现这一点,使其反映WGCNA版本?

是的,我知道rpy2,但如果可能的话,我会尽量轻量级化。在

对于初学者,我的对角线不是1,并且值与原始值没有一致的错误(例如,不是全部由x关闭)。在

当我在R中计算这个值时,我使用了以下方法:

> library(WGCNA, quiet=TRUE)
> df_adj = read.csv("https://pastebin.com/raw/sbAZQsE6", row.names=1, header=TRUE, check.names=FALSE, sep="\t")
> df_tom = TOMsimilarity(as.matrix(df_adj), TOMType="unsigned", TOMDenom="min")
# ..connectivity..
# ..matrix multiplication (system BLAS)..
# ..normalization..
# ..done.
# I've uploaded it to this url: https://pastebin.com/raw/HT2gBaZC

我不知道我的代码哪里不正确。R版本的源代码是here,但它使用的是C后端脚本?这对我来说很难理解。在

以下是我在Python中的实现:

^{pr2}$

有一个名为GTOMhttps://github.com/benmaier/gtom)的包,但它不是用于加权邻接的。The author of GTOM also took a look at this problem(这是一个更加复杂/高效的NumPy实现,但是仍然没有产生预期的结果)。在

有人知道如何复制WGCNA实现吗?

编辑:2019.06.20 我修改了@scleronic和@benmaier中的一些代码,doc字符串中有credits。该函数可在soothsayer中从v2016.06及其上获得。希望这能让人们更容易地在Python中使用拓扑重叠,而不是只会使用R

enter image description here

https://github.com/jolespin/soothsayer/blob/master/soothsayer/networks/networks.py

^{3}$

Tags: 代码https版本comtruedfrawnames
1条回答
网友
1楼 · 发布于 2024-09-28 22:04:07

首先让我们看一下二元邻接矩阵a_ij情况下方程的部分内容:

  • _ij:表示节点i是否连接到节点j
  • k\u i:节点i的邻居计数(连接性)
  • l iu ij:节点i和节点j的公共邻居计数

因此,w逯ij测量有多少具有较低连通性的节点的邻居也是另一个节点的邻居(即w逯ij测量“它们的相对互连性”)。在

我的猜测是他们把A的对角线定义为0而不是1。 根据这个假设,我可以重现WGCNA的值。在

A[np.arange(d), np.arange(d)] = 0  # Assumption
L = A @ A  # Could be done smarter by using the symmetry
K = A.sum(axis=1)

A_tom = np.zeros_like(A)
for i in range(d):
    # I don't iterate over the diagonal elements so it is not 
    # surprising that they are 0 in this case, but even if the start is  
    # at i instead of i+1 the results for the diagonal aren't equal to 1
    for j in range(i+1, d):  
        numerator = L[i, j] + A[i, j]
        denominator = min(K[i], K[j]) + 1 - A[i, j]
        A_tom[i, j] = numerator / denominator

A_tom += A_tom.T
A_tom[np.arange(d), np.arange(d)] = 1  # Set diagonal to 1 by default

A_tom__wgcna = np.array(pd.read_csv("https://pastebin.com/raw/HT2gBaZC", 
                        sep="\t", index_col=0))
print(np.allclose(A_tom, A_tom__wgcna))

对于二进制A的一个简单例子可以看出为什么A的对角线应该是零而不是一:

^{pr2}$

方程式4的给定描述说明:

Note that ωij = 1 if the node with fewer connections satisfies two conditions:

  • (a) all of its neighbors are also neighbors of the other node and

  • (b) it is connected to the other node.

In contrast, ωij = 0 if i and j are un-connected and the two nodes do not share any neighbors.

因此A-D之间的连接w_14应满足该标准,且为1。在

  • 大小写零:
  • 案例一:

现在还缺少的是对角线值不匹配。我默认设置为1。一个节点与自身的互联性是什么?一个不同于1(或0,取决于定义)的值对我来说没有意义。 在简单的例子中,无论是案例0还是案例1都不会导致w_ii=1。 在案例0中,k憰i+1==l憰ii;在案例一中,k憰i==l憰ii+1,这在我看来都是错误的。在

所以我会把邻接矩阵的对角线设置为零,然后使用给定的方程,默认情况下将结果的对角线设置为1。在

相关问题 更多 >