forked from joongbo/tta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_unsupervisedstsb.py
266 lines (206 loc) · 8.79 KB
/
run_unsupervisedstsb.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
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
# coding=utf-8
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Calculate pseudo-perplexity of a sentence using TTA."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import collections
import modeling
import tensorflow as tf
import tokenization
import numpy as np
import scipy as sp
import csv
from sklearn.metrics.pairwise import cosine_similarity
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string("config_file", "",
"The config json file corresponding to the trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("model_checkpoint", "",
"checkpoint")
flags.DEFINE_string("vocab_file", "",
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_integer("max_seq_length", 128, "The length of maximum sequence.")
class TestingInstance(object):
"""A single test instance (sentence pair)."""
def __init__(self, tokens):
self.tokens = tokens
self.input_tokens = tokens
self.target_tokens = tokens
def __str__(self):
s = ""
s += "tokens: %s\n" % (" ".join(
[tokenization.printable_text(x) for x in self.tokens]))
s += "\n"
return s
def __repr__(self):
return self.__str__()
def create_testing_instances(sentence, tokenizer, max_seq_length=128):
"""Create `TestInstance`s from raw text."""
max_token_num = max_seq_length - 2
tokens = tokenizer.tokenize(sentence)
if len(tokens) > max_token_num:
tokens = tokens[:max_token_num]
if tokens[0] is not "[SOS]":
tokens.insert(0, "[SOS]")
if tokens[-1] is not "[EOS]":
tokens.append("[EOS]")
instances = []
instances.append(create_instances_from_tokens(tokens))
return instances
def create_instances_from_tokens(tokens):
"""Creates `TestInstance`s for a single sentence."""
instance = TestingInstance(tokens)
return instance
# load tokenizer
tokenizer = tokenization.FullTokenizer(
vocab_file = FLAGS.vocab_file,
do_lower_case=True)
word_to_id = tokenizer.vocab
# load trained model
config = modeling.BertConfig.from_json_file(FLAGS.config_file)
tf.reset_default_graph()
session_config = tf.ConfigProto()
session_config.gpu_options.allow_growth = True
sess = tf.Session(config=session_config)
input_ids = tf.placeholder(dtype=tf.int32, shape=[None, None])
input_mask = tf.placeholder(dtype=tf.int32, shape=[None, None])
model = modeling.BertModel(
config=config,
is_training=False,
input_ids=input_ids,
input_mask=input_mask,
use_one_hot_embeddings=False)
input_tensor = model.get_sequence_output()
input_embeddings = model.get_embedding_output()
input_shape = modeling.get_shape_list(input_tensor, expected_rank=3)
input_tensor = tf.reshape(input_tensor, [input_shape[0]*input_shape[1], input_shape[2]])
saver = tf.train.Saver()
saver.restore(sess, FLAGS.model_checkpoint)
print()
# load STSb-dev-set
labels = []
refs = []
hyps = []
with open('data/stsbenchmark/sts-dev.csv') as f:
reader = csv.reader(f, delimiter='\n')
dev_list = []
for line in reader:
dev = line[0].split('\t')
labels.append(float(dev[4]))
refs.append(dev[5])
hyps.append(dev[6])
# calculate correlation
print('Get scores on STSb-dev. Processing ..')
similarity_scores_representation = []
# similarity_scores_embeddings = []
for cnt, (ref, hyp) in enumerate(zip(refs, hyps)):
if (cnt+1) % 200 == 0:
print(cnt+1, end=', ')
instances = create_testing_instances(ref, tokenizer,
FLAGS.max_seq_length)
batch_input_ids = []
batch_input_mask = []
for _instance in instances:
_input_ids = [word_to_id[_token] for _token in _instance.input_tokens]
_input_mask = [1] * len(_input_ids)
batch_input_ids.append(_input_ids)
batch_input_mask.append(_input_mask)
feed_dict = {input_ids : batch_input_ids,
input_mask : batch_input_mask,
}
[representations_ref, embeddings_ref] = sess.run([input_tensor, input_embeddings], feed_dict=feed_dict)
instances = create_testing_instances(hyp, tokenizer,
FLAGS.max_seq_length)
batch_input_ids = []
batch_input_mask = []
for _instance in instances:
_input_ids = [word_to_id[_token] for _token in _instance.input_tokens]
_input_mask = [1] * len(_input_ids)
batch_input_ids.append(_input_ids)
batch_input_mask.append(_input_mask)
feed_dict = {input_ids : batch_input_ids,
input_mask : batch_input_mask,
}
[representations_hyp, embeddings_hyp] = sess.run([input_tensor, input_embeddings], feed_dict=feed_dict)
sentence_representation_mean_ref = np.mean(representations_ref[1:-1], axis=0)
sentence_representation_mean_hyp = np.mean(representations_hyp[1:-1], axis=0)
score = cosine_similarity([sentence_representation_mean_ref], [sentence_representation_mean_hyp])
similarity_scores_representation.append(score[0][0])
# sentence_embeddings_mean_ref = np.mean(embeddings_ref[0][1:-1], axis=0)
# sentence_embeddings_mean_hyp = np.mean(embeddings_hyp[0][1:-1], axis=0)
# score = cosine_similarity([sentence_embeddings_mean_ref], [sentence_embeddings_mean_hyp])
# similarity_scores_embeddings.append(score[0][0])
print('')
print('STSb-dev (context):', sp.stats.pearsonr(labels, similarity_scores_representation)[0])
# print('STSb-dev (embed) :', sp.stats.pearsonr(labels, similarity_scores_embeddings)[0])
# load STSb-test-set
labels = []
refs = []
hyps = []
with open('data/stsbenchmark/sts-test.csv') as f:
reader = csv.reader(f, delimiter='\n')
test_list = []
for line in reader:
test = line[0].split('\t')
labels.append(float(test[4]))
refs.append(test[5])
hyps.append(test[6])
# calculate correlation
print('Get scores on STSb-test. Processing ..')
similarity_scores_representation = []
# similarity_scores_embeddings = []
for cnt, (ref, hyp) in enumerate(zip(refs, hyps)):
if (cnt+1) % 200 == 0:
print(cnt+1, end=', ')
instances = create_testing_instances(ref, tokenizer,
FLAGS.max_seq_length)
batch_input_ids = []
batch_input_mask = []
for _instance in instances:
_input_ids = [word_to_id[_token] for _token in _instance.input_tokens]
_input_mask = [1] * len(_input_ids)
batch_input_ids.append(_input_ids)
batch_input_mask.append(_input_mask)
feed_dict = {input_ids : batch_input_ids,
input_mask : batch_input_mask,
}
[representations_ref, embeddings_ref] = sess.run([input_tensor, input_embeddings], feed_dict=feed_dict)
instances = create_testing_instances(hyp, tokenizer,
FLAGS.max_seq_length)
batch_input_ids = []
batch_input_mask = []
for _instance in instances:
_input_ids = [word_to_id[_token] for _token in _instance.input_tokens]
_input_mask = [1] * len(_input_ids)
batch_input_ids.append(_input_ids)
batch_input_mask.append(_input_mask)
feed_dict = {input_ids : batch_input_ids,
input_mask : batch_input_mask,
}
[representations_hyp, embeddings_hyp] = sess.run([input_tensor, input_embeddings], feed_dict=feed_dict)
sentence_representation_mean_ref = np.mean(representations_ref[1:-1], axis=0)
sentence_representation_mean_hyp = np.mean(representations_hyp[1:-1], axis=0)
score = cosine_similarity([sentence_representation_mean_ref], [sentence_representation_mean_hyp])
similarity_scores_representation.append(score[0][0])
# sentence_embeddings_mean_ref = np.mean(embeddings_ref[0][1:-1], axis=0)
# sentence_embeddings_mean_hyp = np.mean(embeddings_hyp[0][1:-1], axis=0)
# score = cosine_similarity([sentence_embeddings_mean_ref], [sentence_embeddings_mean_hyp])
# similarity_scores_embeddings.append(score[0][0])
print('')
print('STSb-test (context):', sp.stats.pearsonr(labels, similarity_scores_representation)[0])
# print('STSb-test (embed) :', sp.stats.pearsonr(labels, similarity_scores_embeddings)[0])