graph_kernels_labeled.py 文件源码

python
阅读 31 收藏 0 点赞 0 评论 0

项目:cnn-graph-classification 作者: giannisnik 项目源码 文件源码
def sp_kernel(g1, g2=None):
    if g2 != None:
        graphs = []
        for g in g1:
            graphs.append(g)
        for g in g2:
            graphs.append(g)
    else:
        graphs = g1

    N = len(graphs)
    all_paths = {}
    sp_counts = {}
    for i in range(N):
        sp_lengths = nx.shortest_path_length(graphs[i])
        sp_counts[i] = {}
        nodes = graphs[i].nodes()
        for v1 in nodes:
            for v2 in nodes:
                if v2 in sp_lengths[v1]:
                    label = tuple(sorted([graphs[i].node[v1]['label'], graphs[i].node[v2]['label']]) + [sp_lengths[v1][v2]])
                    if label in sp_counts[i]:
                        sp_counts[i][label] += 1
                    else:
                        sp_counts[i][label] = 1

                    if label not in all_paths:
                        all_paths[label] = len(all_paths)

    phi = np.zeros((N,len(all_paths)))

    for i in range(N):
        for label in sp_counts[i]:
            phi[i,all_paths[label]] = sp_counts[i][label]

    if g2 != None:
        K = np.dot(phi[:len(g1),:],phi[len(g1):,:].T)
    else:
        K = np.dot(phi,phi.T)

    return K
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号