-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathranks.py
More file actions
282 lines (233 loc) · 10.1 KB
/
ranks.py
File metadata and controls
282 lines (233 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import division
from utils import parse_weights_from_file, load_docsXtopics_from_file, set_graph_edges
import numpy as np
from numpy import linalg
from tagger import tag_phrases
import networkx, nltk
from nltk.tokenize import RegexpTokenizer
"""TextRank algorithm : no heuristic selection of candidates on top of POS tagging.
Ref: Mihalcea and Tarau. 2004. Textrank: Bringing order into texts."""
def textrank(text):
# tokenize all words; remove stop words
stop_words = nltk.corpus.stopwords.words('english')
stop_words = set(stop_words)
tokenizer = RegexpTokenizer(r'\w+')
words = tokenizer.tokenize(text)
words_nostopwords = []
for i in range(len(words)):
words[i] = words[i].lower()
if words[i] not in stop_words:
words_nostopwords.append(words[i])
words = words_nostopwords
graph = networkx.Graph()
graph.add_nodes_from(set(words))
set_graph_edges(graph, words, words)
# score nodes using default pagerank algorithm
ranks = networkx.pagerank(graph)
tagged_phrases = tag_phrases(text) # list of lists
tagged_phrases_scores = {}
for p in tagged_phrases:
score = 0
for w in p:
if w in ranks:
score = score + ranks[w]
tagged_phrases_scores[" ".join(p)] = score
if '' in tagged_phrases_scores: # remove empty character as a key
tagged_phrases_scores.pop('')
sorted_phrases = sorted(tagged_phrases_scores.items(), key=lambda x: x[1], reverse=True)
return sorted_phrases
"""Topical Pagerank (TPR) algorithm
Ref: Liu et al. 2010. Automatic keyphrase extraction via topic decomposition."""
def tpr(topics, pt, text, file_ID):
# tokenize all words; remove stop words
stop_words = nltk.corpus.stopwords.words('english')
stop_words = set(stop_words)
tokenizer = RegexpTokenizer(r'\w+')
words = tokenizer.tokenize(text)
words_nostopwords = []
for i in range(len(words)):
words[i] = words[i].lower()
if words[i] not in stop_words:
words_nostopwords.append(words[i])
words = words_nostopwords
graph = networkx.Graph()
graph.add_nodes_from(set(words))
set_graph_edges(graph, words, words)
tagged_phrases = tag_phrases(text) # list of lists
# add personalization to pagerank
topics_nparray = np.ones((len(topics), len(topics[0]))) * 10e-10
for t in range(len(topics)):
count = 0
for el in sorted(topics[t]):
topics_nparray[t, count] = topics_nparray[t, count] + topics[t][el]
count = count + 1
row_sums = topics_nparray.sum(axis=1)
phi = topics_nparray / row_sums[:, np.newaxis] # normalize row-wise: each topic(row) is a distribution
topics_nparray = phi
col_sums = topics_nparray.sum(axis=0)
p_tw = topics_nparray / col_sums[np.newaxis, :] # normalize column-wise: each word (col) is a distribution
# run page rank for each topic
tagged_phrases_scores = {} # keyphrse: list of ranks for each topic
for t in range(len(topics)):
# construct personalization vector and run PR
personalization = {}
idx = 0
for n, _ in list(graph.nodes(data=True)):
if n in sorted(topics[0]):
if n in words:
personalization[n] = p_tw[t, idx]
else:
personalization[n] = 0
else:
personalization[n] = 0
idx = idx + 1
ranks = networkx.pagerank(graph, 0.85, personalization)
# accumulate ranks for candidate keyphrases for each topic
for p in tagged_phrases:
whole_phrase = " ".join(p)
score = 0
for w in p:
if w in ranks:
score = score + ranks[w]
if whole_phrase in tagged_phrases_scores:
tagged_phrases_scores[whole_phrase].append(score)
else:
tagged_phrases_scores[whole_phrase] = [score]
# final rank for each keyphrase: weigh candidate ranks by the document's topic distribution
for p, v in tagged_phrases_scores.items():
tagged_phrases_scores[p] = np.dot(np.array(v), pt[file_ID, :] / sum(pt[file_ID, :]))
sorted_phrases = sorted(tagged_phrases_scores.items(), key=lambda x: x[1], reverse=True)
return sorted_phrases
"""Single Topical PageRank (SingleTPR) algorithm
Ref: Sterckx et al. 2015. Topical word importance for fast keyphrase extraction. """
def singletpr(topics, pt, text, file_ID):
# tokenize all words; remove stop words
stop_words = nltk.corpus.stopwords.words('english')
stop_words = set(stop_words)
tokenizer = RegexpTokenizer(r'\w+')
words = tokenizer.tokenize(text)
words_nostopwords = []
for i in range(len(words)):
words[i] = words[i].lower()
if words[i] not in stop_words:
words_nostopwords.append(words[i])
words = words_nostopwords
# set the graph edges
graph = networkx.Graph()
graph.add_nodes_from(set(words))
set_graph_edges(graph, words, words)
# add personalization to pagerank
topics_nparray = np.ones((len(topics), len(topics[0]))) * 10e-10
for t in range(len(topics)):
count = 0
for el in sorted(topics[t]):
topics_nparray[t, count] = topics_nparray[t, count] + topics[t][el]
count = count + 1
row_sums = topics_nparray.sum(axis=1)
phi = topics_nparray / row_sums[:, np.newaxis] # normalize row-wise: each topic(row) is a distribution
topics_nparray = phi # #topics x #words
pt_new_dim = pt[file_ID, :] / sum(pt[file_ID, :]) # topic distribution for one doc
pt_new_dim = pt_new_dim[None, :]
weights = np.dot(phi.T, pt_new_dim.T)
weights = weights / linalg.norm(pt_new_dim, 'fro') # cos similarity normalization
personalization = {}
count = 0
for n, _ in list(graph.nodes(data=True)):
if n in sorted(topics[0]):
if n in words:
personalization[n] = weights[count] / (linalg.norm(pt_new_dim, 'fro') * linalg.norm(
phi[:, count])) # cos similarity normalization
else:
personalization[n] = 0
else:
personalization[n] = 0
count = count + 1
# score nodes using default pagerank algorithm, sort by score, keep top n_keywords
factor = 1.0 / sum(personalization.values()) # normalize the personalization vec
for k in personalization:
personalization[k] = personalization[k] * factor
ranks = networkx.pagerank(graph, 0.85, personalization)
tagged_phrases = tag_phrases(text) # list of lists
tagged_phrases_scores = {}
for p in tagged_phrases:
score = 0
for w in p:
if w in ranks:
score = score + ranks[w]
tagged_phrases_scores[" ".join(p)] = score
if '' in tagged_phrases_scores: # remove empty character as a key
tagged_phrases_scores.pop('')
sorted_phrases = sorted(tagged_phrases_scores.items(), key=lambda x: x[1], reverse=True)
return sorted_phrases
"""Salience Rank algorithm
Ref: Teneva and Cheng. 2017. Salience Rank: Efficient Keyphrase Extraction with Topic Modeling."""
def saliencerank(topics, pt, text, file_ID, alpha):
# tokenize all words; remove stop words
stop_words = nltk.corpus.stopwords.words('english')
stop_words = set(stop_words)
tokenizer = RegexpTokenizer(r'\w+')
words = tokenizer.tokenize(text)
words_nostopwords = []
for i in range(len(words)):
words[i] = words[i].lower()
if words[i] not in stop_words:
words_nostopwords.append(words[i])
words = words_nostopwords
# set the graph edges
graph = networkx.Graph()
graph.add_nodes_from(set(words))
set_graph_edges(graph, words, words)
# add personalization to pagerank
topics_nparray = np.ones((len(topics), len(topics[0]))) * 10e-10
for t in range(len(topics)):
count = 0
for el in sorted(topics[t]):
topics_nparray[t, count] = topics_nparray[t, count] + topics[t][el]
count = count + 1
row_sums = topics_nparray.sum(axis=1)
phi = topics_nparray / row_sums[:, np.newaxis] # normalize row-wise: each topic(row) is a distribution
topics_nparray = phi
col_sums = topics_nparray.sum(axis=0)
pw = col_sums / np.sum(col_sums)
p_tw = topics_nparray / col_sums[np.newaxis, :] # normalize column-wise: each word (col) is a distribution
pt_new_dim = pt[file_ID, :] / sum(pt[file_ID, :])
pt_new_dim = pt_new_dim[None, :]
p_tw_by_pt = np.divide(p_tw, pt_new_dim.T) # divide each column by the vector pt elementwise
kernel = np.multiply(p_tw, np.log(p_tw_by_pt))
distinct = kernel.sum(axis=0)
distinct = (distinct - np.min(distinct)) / (np.max(distinct) - np.min(distinct)) # normalize
personalization = {}
count = 0
for n, _ in list(graph.nodes(data=True)):
if n in sorted(topics[0]):
if n in words:
personalization[n] = (1.0 - alpha) * sum(phi[:, count]) + alpha * distinct[count]
else:
personalization[n] = 0
else:
personalization[n] = 0
count = count + 1
# score nodes using default pagerank algorithm, sort by score, keep top n_keywords
ranks = networkx.pagerank(graph, 0.85, personalization)
# Paper: https://aclanthology.org/P17-2084/
# ranks = networkx.pagerank(graph, 0.95, None, 1, 5.0e-1)
# scores = {}
# lamb = 0.7
# assert len(ranks) == len(personalization)
# for key, value in ranks.items():
# scores[key] = lamb * ranks[key] + (1 - lamb) * personalization[key]
# ranks = scores
tagged_phrases = tag_phrases(text) # list of lists
tagged_phrases_scores = {}
for p in tagged_phrases:
score = 0
for w in p:
if w in ranks:
score = score + ranks[w]
tagged_phrases_scores[" ".join(p)] = score
if '' in tagged_phrases_scores: # remove empty character as a key
tagged_phrases_scores.pop('')
sorted_phrases = sorted(tagged_phrases_scores.items(), key=lambda x: x[1], reverse=True)
return sorted_phrases