2017-04-27 7 views
0

私のプロジェクトで複数の文をランキングする人気機能を実装したいと思います。 私は知っておきたいどのように有向グラフを実装し、各ノードが文を表し、その文の間のコサイン類似度が閾値を超えている場合には、その間にエッジが存在する。文章をノードとして使用した指向グラフPython

答えて

1

以下は、n個のノードを持つグラフをプロットするコードです(nはリストに含まれる文字列の量です)。エッジは、(i、j)の形式で提供されます。ここで、i、jは、ストリングリスト内のインデックスに対応するノード番号です。この例では、(0,2)は 'Some'と 'Strings'の間のエッジに対応します。

ノードをある閾値に基づいて接続しようとしているので、edgelistは[[(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) 

幸運!

関連する問題