-
Notifications
You must be signed in to change notification settings - Fork 12
/
test_topics.py
199 lines (165 loc) · 5.65 KB
/
test_topics.py
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
import os
import networkx as nx
import numpy as np
import pytest
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
from nltk.corpus import wordnet as wn
from extra_model._topics import (
aggregate,
filter_aggregates,
get_nodevec,
has_connection,
iterate,
path_to_graph,
traverse_tree,
)
from extra_model._vectorizer import Vectorizer
@pytest.fixture()
def minivec():
# preprocess plain-text test embeddings to proper binary format for vectorizer
glove_file = "tests/resources/test_topics.vec"
tmp_file = "tests/resources/test_topics.tmp"
prepro_file = "tests/resources/test_topics.prepro"
_ = glove2word2vec(glove_file, tmp_file)
model = KeyedVectors.load_word2vec_format(tmp_file)
model.save(prepro_file)
yield Vectorizer(prepro_file)
# cleanup
os.remove(tmp_file)
os.remove(prepro_file)
@pytest.fixture()
def vec():
return Vectorizer("tests/resources/small_embeddings")
@pytest.fixture()
def simple_graph():
# a simple example graph: two leaf nodes (corresponding to text instances), L1 and L2, connected to
# the root of the tree R via two intermidate nodes I1 and I2 which represent higher-level wordnet synsets
# the edges are weighted to test the similarity functionality
graph = nx.DiGraph()
graph.add_nodes_from(["L1", "I1", "L2", "I2", "R"])
graph.add_edges_from([("L1", "I1"), ("L2", "I2"), ("I1", "R"), ("I2", "R")])
graph.nodes["L1"]["seed"] = True
graph.nodes["L2"]["seed"] = True
graph.nodes["I1"]["seed"] = False
graph.nodes["I2"]["seed"] = False
graph.nodes["R"]["seed"] = False
graph["L1"]["I1"]["similarity"] = 1.0
graph["L2"]["I2"]["similarity"] = 1.0
graph["I1"]["R"]["similarity"] = 0.5
graph["I2"]["R"]["similarity"] = 0.5
return graph
def test__path_to_graph():
noun = "zombie"
hypernym_list = wn.synsets(noun, pos=wn.NOUN)[0].hypernym_paths()[0]
graph = path_to_graph(hypernym_list, noun)
print(list(graph.successors(noun)))
print(list(graph.successors("entity.n.01")))
assert (
# entity is the root
len(list(graph.successors("entity.n.01"))) == 0
# initial word is the leaf
and len(nx.dfs_successors(graph, noun)) == graph.order() - 1
# leaf has the seed-flag set
and graph.nodes[noun]["seed"] is True
)
# all the other nodes should not be seeds
for depth, nodes in nx.dfs_successors(graph, noun).items():
for node in nodes:
assert not graph.nodes[node]["seed"]
# all intermediate nodes should have 2 connections, the leaf only one.
for depth, nodes in nx.dfs_predecessors(graph, "entity.n.01").items():
for node in nodes:
if graph.nodes[node]["seed"] is True:
assert graph.degree(node) == 1
else:
assert graph.degree(node) == 2
print(graph.nodes)
def test__get_nodevec(minivec):
assert (get_nodevec("entity.n.01", minivec) == [1.0, 0.0, 0.0, 0.0]).all()
def test__iterate():
transition_matrix = np.array([[0.0, 1.0], [1.0, 0.0]])
original = np.array([0.2, 0.8])
importance = original.copy()
result = iterate(transition_matrix, importance, original, 0.5)
assert result[0] == pytest.approx(0.5)
assert result[1] == pytest.approx(0.5)
def test__has_connection(simple_graph):
assert (
has_connection("L1", "R", simple_graph)
and has_connection("R", "L1", simple_graph)
and not has_connection("L1", "L2", simple_graph)
)
def test__filter_aggregates(simple_graph):
topics = [("L1", 0), ("I1", 0), ("I2", 0), ("L2", 0)]
filtered, removed = filter_aggregates(topics, simple_graph)
assert filtered == [("L1", 0), ("I2", 0)] and removed == {
"I2": ["L2"],
"L1": ["I1"],
}
def test__aggregate(vec):
res, tree = aggregate(
["chair", "Chair", "zombie", "unknown"],
{"chair": 4, "Chair": 2, "zombie": 1, "unknown": 1},
[
wn.synset("chair.n.01"),
wn.synset("chair.n.01"),
wn.synset("zombi.n.01"),
None,
],
vec,
)
nodes, importances = zip(*res)
assert ( # first entry should have highest importance because we put high count to it
importances.index(max(importances)) == 0
)
def test__traverse_tree__down_weighted(simple_graph):
assert (
traverse_tree(
[("R", 1)],
{},
{"L1": 4, "L2": 1},
simple_graph,
weighted=True,
direction="down",
)
== {"L1": 2, "L2": 0.5}
)
def test__traverse_tree__down_unweighted(simple_graph):
assert (
traverse_tree(
[("R", 1)],
{},
{"L1": 4, "L2": 1},
simple_graph,
weighted=False,
direction="down",
)
== {"L1": 4, "L2": 1}
)
def test__traverse_tree__up_weighted(simple_graph):
assert traverse_tree(
[("I1", 1)], {}, {"L1": 4, "L2": 1}, simple_graph, weighted=True, direction="up"
) == {"L1": 4}
def test__traverse_tree__up_unweighted(simple_graph):
assert (
traverse_tree(
[("I1", 1)],
{},
{"L1": 4, "L2": 1},
simple_graph,
weighted=False,
direction="up",
)
== {"L1": 4}
)
@pytest.mark.skip(
reason="This function is hard to test in isolation and is tested as part of the integration test"
)
def test_aspects__get_topics():
pass
@pytest.mark.skip(
reason="This function is hard to test in isolation and is tested as part of the integration test"
)
def test_aspects__collect_topic_info():
pass