derank 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- derank/__init__.py +8 -0
- derank/_api.py +229 -0
- derank/_core.py +111 -0
- derank-0.1.2.dist-info/METADATA +128 -0
- derank-0.1.2.dist-info/RECORD +7 -0
- derank-0.1.2.dist-info/WHEEL +4 -0
- derank-0.1.2.dist-info/licenses/LICENSE +21 -0
derank/__init__.py
ADDED
derank/_api.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Public inputs and result types for DERank."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from numbers import Integral, Real
|
|
6
|
+
import math
|
|
7
|
+
import unicodedata
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import regex
|
|
12
|
+
from scipy.sparse import csr_matrix
|
|
13
|
+
|
|
14
|
+
from ._core import communities, connection_entropy, derank_walk, order_terms, term_graph
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
_SENTENCE_BREAK = regex.compile(r"[.!?]+[\p{Pe}\p{Pf}\"']*(?=\s|$)|[。!?]+|\R+")
|
|
18
|
+
_TERM = regex.compile(r"[\p{L}\p{N}][\p{L}\p{M}\p{N}]*")
|
|
19
|
+
_KEYWORD_COLUMNS = ("term", "score", "rank", "keyword")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(eq=False, slots=True)
|
|
23
|
+
class DocumentResult:
|
|
24
|
+
"""Keyword table, term diagnostics, and optional matrices for one document."""
|
|
25
|
+
|
|
26
|
+
keywords: pd.DataFrame
|
|
27
|
+
scores: pd.DataFrame
|
|
28
|
+
iterations: int
|
|
29
|
+
residual: float
|
|
30
|
+
dangling_terms: tuple[str, ...]
|
|
31
|
+
terms: tuple[str, ...]
|
|
32
|
+
tfidf: csr_matrix | None = None
|
|
33
|
+
weight: csr_matrix | None = None
|
|
34
|
+
transition: np.ndarray | None = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(eq=False, slots=True)
|
|
38
|
+
class BatchResult:
|
|
39
|
+
"""Combined keywords, document statuses, and results in input order."""
|
|
40
|
+
|
|
41
|
+
keywords: pd.DataFrame
|
|
42
|
+
documents: pd.DataFrame
|
|
43
|
+
results: tuple[DocumentResult | None, ...]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def derank(sentences, top_n=10, *, stems=None, details=False, tie_tol=1e-14,
|
|
47
|
+
text_col=None, id_col=None, vector_mode="documents") -> DocumentResult | BatchResult:
|
|
48
|
+
"""Rank keywords in a document or a collection of documents.
|
|
49
|
+
|
|
50
|
+
A string is one document. With the default ``vector_mode="documents"``,
|
|
51
|
+
a sequence of strings contains separate documents, including a sequence
|
|
52
|
+
of length one. ``"sentences"`` interprets each string as one sentence of
|
|
53
|
+
the same document. ``"tokens"`` takes a single preprocessed sentence.
|
|
54
|
+
A nested sequence specifies preprocessed tokens for each sentence.
|
|
55
|
+
DataFrames provide one document per row, using ``text_col`` (or ``text``)
|
|
56
|
+
and optionally unique ``id_col`` values.
|
|
57
|
+
|
|
58
|
+
``top_n`` is the maximum number of distinct keywords per document. Set
|
|
59
|
+
it to ``None`` or positive infinity to return all keywords. ``stems``
|
|
60
|
+
optionally maps graph terms to evaluation stems. ``details=True`` returns
|
|
61
|
+
sparse TF-IDF and graph matrices and the dense completed transition matrix.
|
|
62
|
+
``tie_tol`` defines ties relative to the highest remaining rank score.
|
|
63
|
+
"""
|
|
64
|
+
top_n = _keyword_limit(top_n)
|
|
65
|
+
if not isinstance(details, (bool, np.bool_)):
|
|
66
|
+
raise ValueError("details must be boolean.")
|
|
67
|
+
if (isinstance(tie_tol, (bool, np.bool_)) or not isinstance(tie_tol, Real)
|
|
68
|
+
or not math.isfinite(tie_tol) or tie_tol < 0):
|
|
69
|
+
raise ValueError("tie_tol must be a finite nonnegative number.")
|
|
70
|
+
if vector_mode not in ("documents", "sentences", "tokens"):
|
|
71
|
+
raise ValueError("vector_mode must be 'documents', 'sentences', or 'tokens'.")
|
|
72
|
+
if stems is not None and (not isinstance(stems, Mapping) or
|
|
73
|
+
not all(_is_token(k) and _is_token(v) for k, v in stems.items())):
|
|
74
|
+
raise ValueError("stems must map nonempty terms to nonempty stem strings.")
|
|
75
|
+
|
|
76
|
+
if isinstance(sentences, pd.DataFrame):
|
|
77
|
+
if vector_mode != "documents":
|
|
78
|
+
raise ValueError("A DataFrame requires vector_mode='documents'.")
|
|
79
|
+
text = _select_column(sentences, "text" if text_col is None else text_col, "text_col")
|
|
80
|
+
ids = None if id_col is None else _select_column(sentences, id_col, "id_col")
|
|
81
|
+
return _rank_documents(text, top_n, stems, details, tie_tol, ids)
|
|
82
|
+
if text_col is not None or id_col is not None:
|
|
83
|
+
raise ValueError("text_col and id_col require a pandas DataFrame.")
|
|
84
|
+
if isinstance(sentences, str):
|
|
85
|
+
if vector_mode != "documents":
|
|
86
|
+
raise ValueError("Supply a sequence of strings for 'sentences' or 'tokens'.")
|
|
87
|
+
return _rank_sentences(_tokenize_document(sentences), top_n, stems, details, tie_tol)
|
|
88
|
+
|
|
89
|
+
values = _as_sequence(sentences)
|
|
90
|
+
if vector_mode == "tokens":
|
|
91
|
+
return _rank_sentences([_validate_tokens(values)], top_n, stems, details, tie_tol)
|
|
92
|
+
if vector_mode == "sentences":
|
|
93
|
+
if not all(isinstance(value, str) for value in values):
|
|
94
|
+
raise ValueError("Sentence input must be a sequence of nonmissing strings.")
|
|
95
|
+
return _rank_sentences([_tokenize_sentence(value) for value in values],
|
|
96
|
+
top_n, stems, details, tie_tol)
|
|
97
|
+
if all(isinstance(value, str) or _is_missing(value) for value in values):
|
|
98
|
+
return _rank_documents(values, top_n, stems, details, tie_tol)
|
|
99
|
+
token_sentences = [_validate_tokens(_as_sequence(value)) for value in values]
|
|
100
|
+
return _rank_sentences(token_sentences, top_n, stems, details, tie_tol)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _keyword_limit(value):
|
|
104
|
+
if value is None:
|
|
105
|
+
return None
|
|
106
|
+
if not isinstance(value, (bool, np.bool_)) and isinstance(value, Real) and value >= 1:
|
|
107
|
+
if value == math.inf:
|
|
108
|
+
return None
|
|
109
|
+
if isinstance(value, Integral) or int(value) == value:
|
|
110
|
+
return int(value)
|
|
111
|
+
raise ValueError("top_n must be a positive integer, None, or positive infinity.")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _as_sequence(value):
|
|
115
|
+
if isinstance(value, (np.ndarray, pd.Series, pd.Index)) and value.ndim == 1:
|
|
116
|
+
return list(value)
|
|
117
|
+
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
|
|
118
|
+
return list(value)
|
|
119
|
+
raise TypeError("Supply text, a sequence of strings or sentence token lists, or a DataFrame.")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _is_missing(value):
|
|
123
|
+
return pd.api.types.is_scalar(value) and bool(pd.isna(value))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _is_token(value):
|
|
127
|
+
return isinstance(value, str) and bool(value) and not any(c.isspace() for c in value)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _validate_tokens(values):
|
|
131
|
+
if not all(_is_token(value) for value in values):
|
|
132
|
+
raise ValueError("Preprocessed tokens must be nonempty strings without whitespace.")
|
|
133
|
+
return values
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _select_column(frame, column, option):
|
|
137
|
+
if not isinstance(column, str) or not column:
|
|
138
|
+
raise ValueError(f"{option} must be a column name.")
|
|
139
|
+
positions = [i for i, name in enumerate(frame.columns) if isinstance(name, str) and name == column]
|
|
140
|
+
if len(positions) != 1:
|
|
141
|
+
raise ValueError(f"{option} must match exactly one DataFrame column: {column!r}.")
|
|
142
|
+
return frame.iloc[:, positions[0]].tolist()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _tokenize_sentence(text):
|
|
146
|
+
return _TERM.findall(unicodedata.normalize("NFC", text.lower()))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _tokenize_document(text):
|
|
150
|
+
tokens = [_tokenize_sentence(part) for part in _SENTENCE_BREAK.split(text)]
|
|
151
|
+
return [sentence for sentence in tokens if sentence]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _validate_ids(ids):
|
|
155
|
+
def valid(value):
|
|
156
|
+
if isinstance(value, str):
|
|
157
|
+
return bool(value.strip())
|
|
158
|
+
return (not isinstance(value, (bool, np.bool_)) and isinstance(value, Real)
|
|
159
|
+
and (isinstance(value, Integral) or math.isfinite(value)))
|
|
160
|
+
|
|
161
|
+
if not all(valid(value) for value in ids) or len(set(ids)) != len(ids):
|
|
162
|
+
raise ValueError("id_col must contain unique, nonmissing text or numeric IDs.")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _rank_documents(text, top_n, stems, details, tie_tol, ids=None):
|
|
166
|
+
if ids is not None:
|
|
167
|
+
_validate_ids(ids)
|
|
168
|
+
keywords, documents, results = [], [], []
|
|
169
|
+
for i, document in enumerate(text, 1):
|
|
170
|
+
fit = None
|
|
171
|
+
if _is_missing(document):
|
|
172
|
+
status = "missing"
|
|
173
|
+
elif not isinstance(document, str):
|
|
174
|
+
raise TypeError(f"Document {i}: expected a string or missing value.")
|
|
175
|
+
else:
|
|
176
|
+
token_sentences = _tokenize_document(document)
|
|
177
|
+
status = "ok" if token_sentences else "no_tokens"
|
|
178
|
+
if token_sentences:
|
|
179
|
+
try:
|
|
180
|
+
fit = _rank_sentences(token_sentences, top_n, stems, details, tie_tol)
|
|
181
|
+
except (ValueError, ArithmeticError) as exc:
|
|
182
|
+
raise type(exc)(f"Document {i}: {exc}") from exc
|
|
183
|
+
for row in fit.keywords.itertuples(index=False, name=None):
|
|
184
|
+
keywords.append((i, *row))
|
|
185
|
+
results.append(fit)
|
|
186
|
+
documents.append((i, status, len(fit.keywords) if fit is not None else 0))
|
|
187
|
+
keyword_table = pd.DataFrame(keywords, columns=("document", *_KEYWORD_COLUMNS))
|
|
188
|
+
document_table = pd.DataFrame(documents, columns=("document", "status", "n_keywords"))
|
|
189
|
+
if ids is not None:
|
|
190
|
+
keyword_table["doc_id"] = [ids[i - 1] for i in keyword_table["document"]]
|
|
191
|
+
document_table["doc_id"] = ids
|
|
192
|
+
return BatchResult(keyword_table, document_table, tuple(results))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _rank_sentences(sentences, top_n, stems, details, tie_tol):
|
|
196
|
+
positions = {}
|
|
197
|
+
for position, token in enumerate((t for s in sentences for t in s), start=1):
|
|
198
|
+
positions.setdefault(token, position)
|
|
199
|
+
if not positions:
|
|
200
|
+
raise ValueError("The document must contain at least one token.")
|
|
201
|
+
terms = tuple(sorted(positions))
|
|
202
|
+
if stems is not None:
|
|
203
|
+
absent = [term for term in terms if term not in stems]
|
|
204
|
+
if absent:
|
|
205
|
+
raise ValueError(f"stems is missing graph terms, including {absent[0]!r}.")
|
|
206
|
+
tfidf, weight = term_graph(sentences, terms)
|
|
207
|
+
membership = communities(weight)
|
|
208
|
+
h_int, h_ext = connection_entropy(weight, membership)
|
|
209
|
+
degree = np.asarray(weight.sum(axis=1)).ravel()
|
|
210
|
+
theta = degree * (h_int + h_ext)
|
|
211
|
+
score, iterations, residual, dangling, transition = derank_walk(weight, theta, details)
|
|
212
|
+
first = np.array([positions[term] for term in terms])
|
|
213
|
+
order = order_terms(score, first, tie_tol)
|
|
214
|
+
ranked_terms = [terms[index] for index in order]
|
|
215
|
+
scores = pd.DataFrame(dict(term=ranked_terms, score=score[order],
|
|
216
|
+
rank=range(1, len(terms) + 1), first_position=first[order],
|
|
217
|
+
degree=degree[order], community=membership[order],
|
|
218
|
+
h_int=h_int[order], h_ext=h_ext[order], theta=theta[order]))
|
|
219
|
+
key = [stems[term] for term in ranked_terms] if stems is not None else ranked_terms
|
|
220
|
+
keywords = scores[["term", "score", "rank"]].copy()
|
|
221
|
+
keywords["keyword"] = key
|
|
222
|
+
keywords = keywords.drop_duplicates("keyword").reset_index(drop=True)
|
|
223
|
+
if top_n is not None:
|
|
224
|
+
keywords = keywords.iloc[:min(top_n, len(keywords))].copy()
|
|
225
|
+
keywords["rank"] = range(1, len(keywords) + 1)
|
|
226
|
+
return DocumentResult(keywords, scores, iterations, residual,
|
|
227
|
+
tuple(term for term, missing in zip(terms, dangling) if missing),
|
|
228
|
+
terms, tfidf if details else None, weight if details else None,
|
|
229
|
+
transition)
|
derank/_core.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Sentence TF-IDF, graph features and the original DERank random walk."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
|
|
5
|
+
import igraph as ig
|
|
6
|
+
import numpy as np
|
|
7
|
+
from scipy import sparse
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def term_graph(sentences, terms):
|
|
11
|
+
columns = {term: index for index, term in enumerate(terms)}
|
|
12
|
+
lengths = [len(sentence) for sentence in sentences]
|
|
13
|
+
term_indices = [columns[token] for sentence in sentences for token in sentence]
|
|
14
|
+
row_indices = np.repeat(np.arange(len(sentences)), lengths)
|
|
15
|
+
counts = sparse.csr_matrix(
|
|
16
|
+
(np.ones(len(term_indices)), (row_indices, term_indices)),
|
|
17
|
+
shape=(len(sentences), len(terms)),
|
|
18
|
+
)
|
|
19
|
+
sentence_frequency = counts.getnnz(axis=0)
|
|
20
|
+
idf = np.log((1 + len(sentences)) / (1 + sentence_frequency)) + 1
|
|
21
|
+
tfidf = counts.multiply(idf).tocsr()
|
|
22
|
+
norms = np.sqrt(np.asarray(tfidf.power(2).sum(axis=1)).ravel())
|
|
23
|
+
scales = np.divide(1.0, norms, out=np.zeros_like(norms), where=norms > 0)
|
|
24
|
+
tfidf = tfidf.multiply(scales[:, None]).tocsr()
|
|
25
|
+
weight = (tfidf.T @ tfidf).tocsr()
|
|
26
|
+
weight.setdiag(0)
|
|
27
|
+
weight.eliminate_zeros()
|
|
28
|
+
weight.sort_indices()
|
|
29
|
+
return tfidf, weight
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def communities(weight):
|
|
33
|
+
upper = sparse.triu(weight, k=1, format="csr")
|
|
34
|
+
rows, cols = upper.nonzero()
|
|
35
|
+
n = weight.shape[0]
|
|
36
|
+
if not rows.size:
|
|
37
|
+
return np.ones(n, dtype=int)
|
|
38
|
+
graph = ig.Graph(n=n, edges=list(zip(rows.tolist(), cols.tolist())), directed=False)
|
|
39
|
+
# as_clustering chooses the fewest groups at an exactly tied modularity.
|
|
40
|
+
raw = graph.community_walktrap(steps=3).as_clustering().membership
|
|
41
|
+
labels = {}
|
|
42
|
+
return np.array([labels.setdefault(group, len(labels) + 1) for group in raw])
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def shannon(weights):
|
|
46
|
+
if len(weights) < 2:
|
|
47
|
+
return 0.0
|
|
48
|
+
mass = np.asarray(weights, dtype=float)
|
|
49
|
+
p = mass / mass.sum()
|
|
50
|
+
return float(-np.dot(p, np.log(p)))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def connection_entropy(weight, membership):
|
|
54
|
+
n = weight.shape[0]
|
|
55
|
+
internal = np.zeros(n)
|
|
56
|
+
external = np.zeros(n)
|
|
57
|
+
for row in range(n):
|
|
58
|
+
start, end = weight.indptr[row:row + 2]
|
|
59
|
+
neighbor_groups = membership[weight.indices[start:end]]
|
|
60
|
+
edge_weights = weight.data[start:end]
|
|
61
|
+
same = neighbor_groups == membership[row]
|
|
62
|
+
internal[row] = shannon(edge_weights[same])
|
|
63
|
+
external_mass = defaultdict(float)
|
|
64
|
+
for community, value in zip(neighbor_groups[~same], edge_weights[~same]):
|
|
65
|
+
external_mass[community] += value
|
|
66
|
+
external[row] = shannon(list(external_mass.values()))
|
|
67
|
+
return internal, external
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def derank_walk(weight, theta, details):
|
|
71
|
+
n = len(theta)
|
|
72
|
+
weighted = weight.multiply(theta)
|
|
73
|
+
row_mass = np.asarray(weighted.sum(axis=1)).ravel()
|
|
74
|
+
usable = row_mass > 1e-9
|
|
75
|
+
scale = np.divide(1.0, row_mass, out=np.zeros_like(row_mass), where=usable)
|
|
76
|
+
transition = weighted.multiply(scale[:, None]).tocsr()
|
|
77
|
+
incoming = transition.T.tocsr()
|
|
78
|
+
uniform = np.full(n, 1 / n)
|
|
79
|
+
|
|
80
|
+
def advance(score):
|
|
81
|
+
return 0.85 * (incoming @ score + np.sum(score[~usable]) * uniform) + 0.15 * uniform
|
|
82
|
+
|
|
83
|
+
score = uniform
|
|
84
|
+
for iteration in range(1, 101):
|
|
85
|
+
updated = advance(score)
|
|
86
|
+
delta = np.abs(updated - score).sum()
|
|
87
|
+
score = updated
|
|
88
|
+
if delta < 1e-8:
|
|
89
|
+
break
|
|
90
|
+
else:
|
|
91
|
+
raise ArithmeticError("DERank did not converge within 100 iterations.")
|
|
92
|
+
residual = float(np.abs(advance(score) - score).sum())
|
|
93
|
+
completed = None
|
|
94
|
+
if details:
|
|
95
|
+
completed = transition.toarray()
|
|
96
|
+
completed[~usable, :] = 1 / n
|
|
97
|
+
return score, iteration, residual, ~usable, completed
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def order_terms(scores, positions, tolerance):
|
|
101
|
+
sorted_indices = sorted(range(len(scores)), key=lambda i: (-scores[i], positions[i]))
|
|
102
|
+
result = []
|
|
103
|
+
start = 0
|
|
104
|
+
while start < len(sorted_indices):
|
|
105
|
+
high = scores[sorted_indices[start]]
|
|
106
|
+
end = start + 1
|
|
107
|
+
while end < len(sorted_indices) and high - scores[sorted_indices[end]] <= tolerance:
|
|
108
|
+
end += 1
|
|
109
|
+
result.extend(sorted(sorted_indices[start:end], key=positions.__getitem__))
|
|
110
|
+
start = end
|
|
111
|
+
return result
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: derank
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Dual-entropy keyword ranking on sentence-level term graphs
|
|
5
|
+
Author: Lee Yeon Dong
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: community detection,entropy,graphs,keyword extraction,keywords
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
13
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: igraph<2,>=0.11.8
|
|
16
|
+
Requires-Dist: numpy>=1.24
|
|
17
|
+
Requires-Dist: pandas>=2.2.2
|
|
18
|
+
Requires-Dist: regex>=2024.5.15
|
|
19
|
+
Requires-Dist: scipy>=1.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# derank
|
|
23
|
+
|
|
24
|
+
`derank` ranks keywords in individual documents using Dual-Entropy Ranking
|
|
25
|
+
(DERank), the method introduced in Lee Yeon Dong's 2026 doctoral dissertation.
|
|
26
|
+
It accepts raw text, pretokenized sentences, and pandas DataFrames. It returns
|
|
27
|
+
ranked terms together with each term's community, weighted degree, internal
|
|
28
|
+
entropy, and external entropy.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
Python 3.10 or newer is required.
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
python -m pip install derank
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Rank one document
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from derank import derank
|
|
42
|
+
|
|
43
|
+
result = derank(
|
|
44
|
+
"Graph ranking extracts keywords. Keyword extraction uses graph structure.",
|
|
45
|
+
top_n=5,
|
|
46
|
+
)
|
|
47
|
+
print(result.keywords)
|
|
48
|
+
print(result.scores[["term", "community", "degree", "h_int", "h_ext"]])
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Raw text is split on sentence-ending punctuation and line breaks, lowercased,
|
|
52
|
+
normalized to NFC, and tokenized into sequences of Unicode letters and numbers
|
|
53
|
+
with combining marks. No stopword removal, part-of-speech filtering, or
|
|
54
|
+
stemming is applied automatically. Use pretokenized input when these choices
|
|
55
|
+
are part of an experimental pipeline.
|
|
56
|
+
|
|
57
|
+
## Rank multiple documents
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import pandas as pd
|
|
61
|
+
from derank import derank
|
|
62
|
+
|
|
63
|
+
batch = derank(["Community detection uses random walks.", "Graphs connect terms."])
|
|
64
|
+
print(batch.keywords)
|
|
65
|
+
|
|
66
|
+
frame = pd.DataFrame({
|
|
67
|
+
"paper_id": ["A01", "A02"],
|
|
68
|
+
"abstract": ["Entropy measures diversity.", "Term graphs support ranking."],
|
|
69
|
+
})
|
|
70
|
+
batch = derank(frame, text_col="abstract", id_col="paper_id", top_n=3)
|
|
71
|
+
print(batch.keywords)
|
|
72
|
+
print(batch.documents)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
A string represents one document. By default, a flat list or one-dimensional
|
|
76
|
+
array of strings represents a batch, even if it has one element. Set
|
|
77
|
+
`vector_mode="sentences"` for a list of sentence strings in one document.
|
|
78
|
+
Set `vector_mode="tokens"` for a list of preprocessed tokens in one sentence.
|
|
79
|
+
A DataFrame defaults to the column named `text` when `text_col` is omitted.
|
|
80
|
+
The optional ID column must contain unique nonmissing string or numeric IDs.
|
|
81
|
+
Missing or tokenless texts in a batch are reported in `batch.documents`, with
|
|
82
|
+
the corresponding entry in `batch.results` set to `None`.
|
|
83
|
+
|
|
84
|
+
## Supply preprocessed sentences
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from derank import derank
|
|
88
|
+
|
|
89
|
+
result = derank(
|
|
90
|
+
[["term", "graph", "ranking"], ["keywords", "term", "entropy"]],
|
|
91
|
+
top_n=None,
|
|
92
|
+
stems={"term": "term", "graph": "graph", "ranking": "rank",
|
|
93
|
+
"keywords": "keyword", "entropy": "entropi"},
|
|
94
|
+
details=True,
|
|
95
|
+
)
|
|
96
|
+
print(result.keywords)
|
|
97
|
+
print(result.weight.toarray())
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Pretokenized inputs preserve token spelling and sentence boundaries. When a
|
|
101
|
+
stem map is supplied, the graph still uses the input terms. The returned
|
|
102
|
+
keyword table keeps the highest-ranked term for each distinct stem. The
|
|
103
|
+
`term` field retains the original graph term, and `keyword` contains the
|
|
104
|
+
stem. The score table retains all terms. `top_n=None` returns all distinct
|
|
105
|
+
keywords. With `details=True`, the TF-IDF and adjacency matrices are sparse
|
|
106
|
+
and the completed transition matrix is dense. Their term axes follow
|
|
107
|
+
`result.terms`.
|
|
108
|
+
|
|
109
|
+
## Method
|
|
110
|
+
|
|
111
|
+
1. Build a sentence-by-term TF-IDF matrix using token counts, smoothed
|
|
112
|
+
sentence-frequency IDF, and row L2 normalization. Multiply its transpose by
|
|
113
|
+
the matrix and set the diagonal to zero.
|
|
114
|
+
2. Identify communities using unweighted Walktrap with three walk steps.
|
|
115
|
+
Compute degree as the sum of incident edge weights. Compute internal
|
|
116
|
+
Shannon entropy over same-community neighbors, and external Shannon entropy
|
|
117
|
+
over edge mass aggregated by outside community. The logarithm is natural.
|
|
118
|
+
3. Weight each directed transition by the adjacency weight times the
|
|
119
|
+
destination's degree multiplied by the sum of its two entropies. Normalize
|
|
120
|
+
each row and use a uniform distribution for rows whose total is at most
|
|
121
|
+
`1e-9`. Run the walk with damping 0.85 and uniform restart. The
|
|
122
|
+
L1 change threshold is `1e-8`, with a maximum of 100 iterations.
|
|
123
|
+
4. Rank by stationary scores. The default absolute tie tolerance is `1e-14`
|
|
124
|
+
against the highest remaining score in each tie group. Tied terms appear
|
|
125
|
+
in first-occurrence order.
|
|
126
|
+
|
|
127
|
+
See [CITATION.cff](CITATION.cff) for the recommended thesis citation. The
|
|
128
|
+
package is distributed under the [MIT license](LICENSE).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
derank/__init__.py,sha256=1boCxUonPeLeFOJK_HiZYQpKqwOJ16r42WsVWD31t1Q,248
|
|
2
|
+
derank/_api.py,sha256=bQMMELbqpSVVYlH_MfzhQHyMq3vKE6WEHYI4qJK-xUE,10476
|
|
3
|
+
derank/_core.py,sha256=qpnIgS7tgJaRQR-AmmRLQJfPL_ffD0PdOp9F80fk0oU,4055
|
|
4
|
+
derank-0.1.2.dist-info/METADATA,sha256=ECcqy5R-O_CER5gVLP1f_DsueJIVxcqSt6CsC_wxpnc,4908
|
|
5
|
+
derank-0.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
derank-0.1.2.dist-info/licenses/LICENSE,sha256=2WUzJXIm2BvGR6K5g6FKKr6zc9smNXezr85cLkUA6ZY,1070
|
|
7
|
+
derank-0.1.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lee Yeon Dong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|