【问题标题】:Finding the complete adjacency matrix in R在R中找到完整的邻接矩阵
【发布时间】:2016-02-24 13:21:11
【问题描述】:

我有一个使用函数 amat 的“bnlearn”包中的邻接矩阵(该矩阵是非循环的)。例如:

    +---+-------------------------------+               
    |   |   1     2     3     4     5   |               
    +---+-------------------------------+               
    | 1 |   0     1     0     0     0   |               
    | 2 |   0     0     1     0     0   |               
    | 3 |   0     0     0     1     0   |               
    | 4 |   0     0     0     0     1   |               
    | 5 |   0     0     0     0     0   |               
    +---+-------------------------------+           

我需要从中找到完整的依赖矩阵。 对于一个滞后依赖矩阵,我可以使用:

New_matrix<- if(old_matrix+old_matrix*old_matrix)>0 then 1 else 0

对于两个滞后依赖矩阵,我可以使用:

New_matrix_2<- if(new_matrix+new_matrix*old_matrix)>0 then 1 else 0

问题是我不知道邻接在哪里完成,即我要运行多少次迭代才能得到包含所有相互依赖关系的最终矩阵?

    +---+-------------------------------+               
    |   |   1     2     3     4     5   |               
    +---+-------------------------------+               
    | 1 |   0     1     1     1     1   |               
    | 2 |   0     0     1     1     1   |               
    | 3 |   0     0     0     1     1   |               
    | 4 |   0     0     0     0     1   |               
    | 5 |   0     0     0     0     0   |               
    +---+-------------------------------+ 

为此,答案是 3 次迭代。但是我需要解决这个问题的矩阵是 500x500。 有没有直接的方法可以得到完整的邻接矩阵?

【问题讨论】:

    标签: r adjacency-matrix


    【解决方案1】:

    要查找所有节点的路径,使用igraph 包可能更容易。

    用你的例子,

    library(bnlearn)
    library(igraph)
    
    # Create BN in your example
    g <- empty.graph(LETTERS[1:5])
    amat(g) <- rbind(cbind(0, diag(4)),0)
    amat(g)
    #   A B C D E
    # A 0 1 0 0 0
    # B 0 0 1 0 0
    # C 0 0 0 1 0
    # D 0 0 0 0 1
    # E 0 0 0 0 0
    

    # Convert to igraph object using BN adj. matrix as input
    g1 <- graph_from_adjacency_matrix(amat(g))
    
    # You can find all ancestors for each node by using 
    # the mode="in" argument, and order to specify the depth of the search
    neighborhood(g1, order=nrow(amat(g)), mode="in")
    
    # Similarly, you can get the full connected graph 
    # using the same options
    ances <- connect(g1, order=nrow(amat(g)), mode="in" )
    get.adjacency(ances, sparse=FALSE)
    #   A B C D E
    # A 0 1 1 1 1
    # B 0 0 1 1 1
    # C 0 0 0 1 1
    # D 0 0 0 0 1
    # E 0 0 0 0 0 
    

    或者,您可以使用矩阵指数

    m <- amat(g)
    1* as.matrix((Matrix::expm(m) - diag(ncol(m))) > 0)
    

    【讨论】:

    • 像魅力一样工作!非常感谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2015-05-20
    • 2015-05-31
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多