-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassifier.py
291 lines (235 loc) · 10.9 KB
/
classifier.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# coding=utf-8
# Copyright @akikaaa.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from bert.run_classifier import *
import tensorflow as tf
import numpy as np
from tqdm import tqdm
import time
class MyProcessor(DataProcessor):
def __init__(self):
self.labels = ['anger', 'disgusting', 'happy', 'neutral', 'sad']
def get_test_examples(self, data_dir):
return self.create_examples(
self._read_tsv(os.path.join(data_dir, "test.tsv")), "test")
def get_train_examples(self, data_dir):
"""See base class."""
return self.create_examples(
self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
def get_dev_examples(self, data_dir):
"""See base class."""
return self.create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev")
# def get_dev_examples(self, data_dir):
# """See base class."""
# return self.create_examples(self._read_tsv(os.path.join(data_dir, "eval.tsv")), "dev")
def get_pred_examples(self, data_dir):
return self.create_examples(
self._read_tsv(os.path.join(data_dir, "pred.tsv")), "pred")
def get_labels(self):
"""See base class."""
# return ["-1", "0", "1"]
return self.labels
def create_examples(self, lines, set_type, file_base=True):
"""Creates examples for the training and dev sets. each line is label+\t+text_a+\t+text_b """
examples = []
for (i, line) in tqdm(enumerate(lines)):
# if file_base:
# if i == 0:
# continue
guid = "%s-%s" % (set_type, i)
text = tokenization.convert_to_unicode(line[1])
label = tokenization.convert_to_unicode(line[0])
# if set_type == "test" or set_type == "pred":
# label = "0"
# else:
# label = tokenization.convert_to_unicode(line[0])
examples.append(
InputExample(guid=guid, text_a=text, label=label))
return examples
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"scene_cls": MyProcessor
}
if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict and not FLAGS.do_test:
raise ValueError(
"At least one of `do_train`, `do_eval` or `do_predict' or `do_test` must be True.")
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
bert_config=bert_config,
num_labels=len(label_list),
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_file = os.path.join(FLAGS.output_dir, "train.tf_record")
file_based_convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = file_based_input_fn_builder(
input_file=train_file,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
tensors_to_log = {'train loss': 'loss/Mean:0'}
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=100)
estimator.train(input_fn=train_input_fn, hooks=[logging_hook], max_steps=num_train_steps)
if FLAGS.do_eval:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
num_actual_eval_examples = len(eval_examples)
eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record")
file_based_convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(eval_examples), num_actual_eval_examples,
len(eval_examples) - num_actual_eval_examples)
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
# This tells the estimator to run through the entire set.
eval_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
assert len(eval_examples) % FLAGS.eval_batch_size == 0
eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = file_based_input_fn_builder(
input_file=eval_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_test:
test_examples = processor.get_test_examples(FLAGS.data_dir)
num_actual_test_examples = len(test_examples)
test_file = os.path.join(FLAGS.output_dir, "test.tf_record")
file_based_convert_examples_to_features(
test_examples, label_list, FLAGS.max_seq_length, tokenizer, test_file)
tf.logging.info("***** Running testing *****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(test_examples), num_actual_test_examples,
len(test_examples) - num_actual_test_examples)
tf.logging.info(" Batch size = %d", FLAGS.test_batch_size)
# This tells the estimator to run through the entire set.
test_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
assert len(test_examples) % FLAGS.test_batch_size == 0
test_steps = int(len(test_examples) // FLAGS.test_batch_size)
test_drop_remainder = True if FLAGS.use_tpu else False
test_input_fn = file_based_input_fn_builder(
input_file=test_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=test_drop_remainder)
result = estimator.evaluate(input_fn=test_input_fn, steps=test_steps)
output_test_file = os.path.join(FLAGS.output_dir, "test_results.txt")
with tf.gfile.GFile(output_test_file, "w") as writer:
tf.logging.info("***** Test results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
predict_examples = processor.get_pred_examples(FLAGS.data_dir)
num_actual_predict_examples = len(predict_examples)
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
print(predict_file)
file_based_convert_examples_to_features(predict_examples, label_list,
FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d (%d actual, %d padding)",
len(predict_examples), num_actual_predict_examples,
len(predict_examples) - num_actual_predict_examples)
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_drop_remainder = True if FLAGS.use_tpu else False
predict_input_fn = file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=predict_drop_remainder)
start = time.time()
result = estimator.predict(input_fn=predict_input_fn)
cost = time.time() - start
tf.logging.info('prediction time cost: %8f s' % cost)
output_predict_file = os.path.join(FLAGS.output_dir, "pred_results.tsv")
with tf.gfile.GFile(output_predict_file, "w") as writer:
tf.logging.info("***** Predict results *****")
for prediction in result:
label_index = np.argmax(prediction, -1)
label = label_list[label_index]
output_line = "\t".join(str(class_probability) for class_probability in prediction) + "\t" + label + "\n"
writer.write(output_line)
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
'''
INFO:tensorflow:***** Eval results *****
INFO:tensorflow: eval_accuracy = 0.8647313
INFO:tensorflow: eval_loss = 0.7771957
INFO:tensorflow: global_step = 6072
INFO:tensorflow: loss = 0.77480406
'''