-
Notifications
You must be signed in to change notification settings - Fork 3
/
local_search_contextualized_opinion.py
219 lines (193 loc) · 6.84 KB
/
local_search_contextualized_opinion.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from explanation_generation import (contextualize_candidate_sentences,
get_contextualizer, get_preference)
from sentence_pair_model import TfIdfSentencePair
from util import convert_str_to_list, substitute_word
summary_report = {}
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i",
"--input",
type=str,
default="selected.csv",
help="Selected sentences file path",
)
parser.add_argument(
"-c",
"--corpus",
type=str,
default="data/toy/train.csv",
help="Corpus file path (train.csv)",
)
parser.add_argument(
"-o",
"--out",
type=str,
default="explanations.csv",
help="Output file path",
)
parser.add_argument(
"-p",
"--preference_dir",
type=str,
default="data/toy/efm",
help="EFM/MTER output directory",
)
parser.add_argument(
"-m", "--contextualizer_path", type=str, default="result/model.params"
)
parser.add_argument(
"-k",
"--top_k",
type=int,
default=10,
help="Top k opinions for contextualization",
)
parser.add_argument(
"-s",
"--strategy",
type=str,
choices=[
"greedy-efm",
"ilp-efm",
],
default="greedy-efm",
help="Strategy",
)
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--debug", action="store_true")
parser.add_argument("--debug_path", type=str, default="debug_local_search.pkl")
parser.add_argument("--debug_size", type=int, default=100)
return parser.parse_args()
def compute_representative_cost(sentences, represented_sentences, spm):
all_sentences = sentences + represented_sentences
pairs = [
(i, j)
for i in range(len(sentences))
for j in range(len(sentences), len(all_sentences))
]
costs = spm.compute_cost(all_sentences, pairs)
cost = 0
for j in range(len(sentences), len(all_sentences)):
min_cost = min(costs[: len(sentences), j])
cost += min_cost
return cost
def local_search_contextualize_opinion(
user,
item,
sentences,
aspects,
corpus,
contextualizer,
sentence_pair_model,
top_k=None,
strategy="ilp-efm",
verbose=False,
):
local_searched_sentences = []
if len(sentences) == 0:
return local_searched_sentences
review_idx = "{}-{}".format(user, item)
candidates = corpus[(corpus["asin"] == item) & (corpus["aspect"].isin(aspects))]
candidates = contextualize_candidate_sentences(
candidates, user, contextualizer, top_k=top_k
)
if "contextualized" in strategy:
candidates["instance"] = candidates.apply(
lambda x: "{}-{}-{}".format(x["asin"], x["aspect"], x["sentence"]), axis=1
)
else:
candidates["instance"] = candidates.apply(
lambda x: "{}-{}-{}".format(x["asin"], x["aspect"], x["original sentence"]),
axis=1,
)
candidates["sentence"] = candidates["original sentence"]
candidates.drop_duplicates("instance", inplace=True)
candidates = candidates.set_index(["instance"])
aspect_sentences_map = {}
for aspect, sentence in zip(candidates["aspect"], candidates["sentence"]):
aspect_sentences = aspect_sentences_map.setdefault(aspect, [])
if sentence not in sentences:
aspect_sentences.append(sentence)
solution = {}
for aspect, sentence in zip(aspects, sentences):
aspect_sentences = solution.setdefault(aspect, [])
aspect_sentences.append(sentence)
for aspect, sentence in zip(aspects, sentences):
represented_sentences = aspect_sentences_map.get(aspect)
if len(represented_sentences) > 0:
solution_sentences = solution[aspect].copy()
instance = candidates.loc["{}-{}-{}".format(item, aspect, sentence)]
predicted_opinions = instance["top k opinions"]
opinion_position = instance["opinion_pos"]
# do local search here
best_opinion = sentence.split()[opinion_position] # raw opinion
new_sentence = sentence
best_cost = compute_representative_cost(
solution_sentences, represented_sentences, sentence_pair_model
)
solution_sentences.remove(sentence)
best_idx = -1
for idx, opinion in enumerate(predicted_opinions):
new_sentence = substitute_word(sentence, opinion, opinion_position)
temp_solution_sentences = solution_sentences + [new_sentence]
cost = compute_representative_cost(
temp_solution_sentences, represented_sentences, sentence_pair_model
)
if cost < best_cost:
best_idx = idx
best_cost = cost
best_opinion = opinion
sentence = substitute_word(sentence, best_opinion, opinion_position)
summary_report.setdefault(review_idx, []).append(best_idx)
local_searched_sentences.append(sentence)
return local_searched_sentences
if __name__ == "__main__":
args = parse_arguments()
print("strategy: %s" % args.strategy)
print("load input from %s" % args.input)
df = pd.read_csv(args.input)
df = df[df["selected sentences"].notnull()]
if args.debug:
if args.debug_size > 0:
df = df[: args.debug_size]
df["selected sentences"] = df["selected sentences"].apply(
lambda x: convert_str_to_list(x)
)
print("load corpus from %s" % args.corpus)
corpus = pd.read_csv(args.corpus)
preference = get_preference(args.preference_dir, args.strategy, args.verbose)
contextualizer = get_contextualizer(
args.contextualizer_path, preference, args.strategy, verbose=args.verbose
)
sentence_pair_model = TfIdfSentencePair(
args.verbose,
)
df["backup sentences"] = df["sentences"]
tqdm.pandas(desc="Local search")
df["selected sentences"] = df.progress_apply(
lambda row: local_search_contextualize_opinion(
row["reviewerID"],
row["asin"],
row["selected sentences"],
str(row["aspects"]).split(","),
corpus,
contextualizer,
sentence_pair_model,
top_k=args.top_k,
strategy=args.strategy,
verbose=args.verbose,
),
axis=1,
)
df["sentences"] = df["selected sentences"].apply(lambda x: " . ".join(x))
df.to_csv(args.out, index=False)
if args.debug:
import pickle
with open(args.debug_path, "wb") as f:
pickle.dump(summary_report, f)
print(summary_report)