0

我想实现一个流行特性来在我的项目中对多个句子进行排名。我想知道如何实现一个有向图,每个节点代表一个句子,如果句子之间的余弦相似度超过阈值,则它们之间存在一条边。

4

1 回答 1

1

下面是一段代码,它将绘制具有 n 个节点的图形,其中 n 是列表中提供的字符串的数量。边以 (i,j) 格式提供,其中 i,j 是与字符串列表中的索引相对应的节点编号。在此示例中,(0,2) 将对应于“Some”和“Strings”之间的一条边。

由于您希望根据某个阈值连接节点,因此您的边缘列表将对应于以下内容:您定义的用于检查相似性的函数[[(x,y) for y in range(len(words)) if similarity(words[x],words[y]) < threshold][0] for x in range(len(words))]在哪里。similarity()

from igraph import *

words = ['Some', 'Random', 'Strings','Okay'] #Whatever your strings would be

n_nodes = len(words) #Would be equal to the amount of words you have

g = Graph(directed=True)
layout = g.layout('kk')
edges = [(n,n+1) for n in range(n_nodes-1)] #Connects each node to the next, replace this with your own adjacency tuples

g.add_vertices(n_nodes) #Add the nodes
g.add_edges(edges) #Add the edges

plot(g, bbox=(500,500),margin=30, vertex_label = words)

祝你好运!

于 2017-04-27T07:39:27.567 回答