graph_kernels_labeled.py 文件源码

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

项目:TextAsGraphClassification 作者: NightmareNyx 项目源码 文件源码
def sp_kernel(g1, g2=None):
    with Timer("SP kernel"):
        if g2 is not None:
            graphs = []
            for g in g1:
                graphs.append(g)
            for g in g2:
                graphs.append(g)
        else:
            graphs = g1

        sp_lengths = []

        for graph in graphs:
            sp_lengths.append(nx.shortest_path_length(graph))

        N = len(graphs)
        all_paths = {}
        sp_counts = {}
        for i in range(N):
            sp_counts[i] = {}
            nodes = graphs[i].nodes()
            for v1 in nodes:
                for v2 in nodes:
                    if v2 in sp_lengths[i][v1]:
                        label = tuple(
                            sorted([graphs[i].node[v1]['label'], graphs[i].node[v2]['label']]) + [
                                sp_lengths[i][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 = lil_matrix((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 is not None:
            K = np.dot(phi[:len(g1), :], phi[len(g1):, :].T)
        else:
            K = np.dot(phi, phi.T)

    return K.todense()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号