-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
215 lines (172 loc) · 7.77 KB
/
main.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
# encoding: utf-8
"""
@author: gallupliu
@contact: [email protected]
@version: 1.0
@license: Apache Licence
@file: main.py
@time: 2017/12/8 22:06
"""
import os
import sys
import logging
import datetime
import time
import json
import tensorflow as tf
import operator
import argparse
from preprocess.data_helper import load_train_data, load_test_data, load_embedding, batch_iter
from models.bilstm import BiLSTM
from metrics import rank_evaluations
from data.insuranceqazh import data
# ------------------------- define parameter -----------------------------
# Misc Parameters
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement")
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices")
tf.flags.DEFINE_float("gpu_options", 0.9, "use memory rate")
FLAGS = tf.flags.FLAGS
# ----------------------------- define parameter end ----------------------------------
# ----------------------------- define a logger -------------------------------
logger = logging.getLogger("execute")
logger.setLevel(logging.INFO)
fh = logging.FileHandler("./run.log", mode="w")
fh.setLevel(logging.INFO)
fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s"
datefmt = "%a %d %b %Y %H:%M:%S"
formatter = logging.Formatter(fmt, datefmt)
fh.setFormatter(formatter)
logger.addHandler(fh)
# ----------------------------- define a logger end ----------------------------------
# ----------------------------------- execute train model ---------------------------------
def train_step(sess, ori_batch, cand_batch, neg_batch, model, dropout=1.):
start_time = time.time()
feed_dict = {
model.query: ori_batch,
model.input_left: cand_batch,
model.input_right: neg_batch,
model.keep_prob: dropout
}
_, step, ori_cand_score, ori_neg_score, cur_loss, cur_acc = sess.run(
[model.train_op, model.global_step, model.ori_cand, model.ori_neg, model.loss, model.acc], feed_dict)
time_str = datetime.datetime.now().isoformat()
right, wrong, score = [0.0] * 3
for i in range(0, len(ori_batch)):
if ori_cand_score[i] > 0.55 and ori_neg_score[i] < 0.4:
right += 1.0
else:
wrong += 1.0
score += ori_cand_score[i] - ori_neg_score[i]
time_elapsed = time.time() - start_time
logger.info("%s: step %s, loss %s, acc %s, score %s, wrong %s, %6.7f secs/batch" % (
time_str, step, cur_loss, cur_acc, score, wrong, time_elapsed))
return cur_loss, ori_cand_score
# ---------------------------------- execute train model end --------------------------------------
#
# def cal_acc(labels, results, total_ori_cand):
# if len(labels) == len(results) == len(total_ori_cand):
# retdict = {}
# for label, result, ori_cand in zip(labels, results, total_ori_cand):
# if result not in retdict:
# retdict[result] = []
# retdict[result].append((ori_cand, label))
#
# correct = 0
# for key, value in retdict.items():
# value.sort(key=operator.itemgetter(0), reverse=True)
# score, flag = value[0]
# if flag == 1:
# correct += 1
# return 1. * correct / len(retdict)
# else:
# logger.info("data error")
# return 0
# ---------------------------------- execute valid model ------------------------------------------
def valid_step(sess, model, valid_ori_quests, valid_cand_quests, labels,qids,config):
"""
Evaluates model on a dev set
"""
logger.info("start to validate model")
total_ori_cand = []
for ori_valid, cand_valid, neg_valid in batch_iter(valid_ori_quests, valid_cand_quests, config['inputs']['train']['batch_size'], 1,
is_valid=True):
feed_dict = {
model.query: ori_valid,
model.input_left: cand_valid,
model.keep_prob: 1.0
}
step, ori_cand_score = sess.run([model.global_step, model.ori_cand], feed_dict)
total_ori_cand.extend(ori_cand_score)
data_len = len(total_ori_cand)
data = []
for i in range(data_len):
data.append([valid_ori_quests[i], valid_cand_quests[i], labels[i]])
metrics = ["map", "mrr", "p@1", "ndcg@1"]
rank_evaluations.rank_eval(qids,labels,total_ori_cand,metrics)
# ---------------------------------- execute valid model end --------------------------------------
def get_model(config,embedding):
model = None
print(config['model_name'])
try:
if config['model_name'] == "BiLSTM":
model = BiLSTM(config, embedding)
except Exception as e:
logging.error("load model Exception", e)
exit()
return model
def train(config):
logging.info("start load data")
embedding, word2idx, idx2word = load_embedding(config['inputs']['share']['embed_file'], config['inputs']['share']['embed_size'])
logging.info("start train")
with tf.Graph().as_default():
with tf.device("/cpu:0"):
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=FLAGS.gpu_options)
session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.allow_soft_placement,
log_device_placement=FLAGS.log_device_placement, gpu_options=gpu_options)
with tf.Session(config=session_conf).as_default() as sess:
model = get_model(config, embedding)
sess.run(tf.global_variables_initializer())
for epoch in range(config['inputs']['train']['epoches']):
for (_, ori_train, cand_train, neg_train) in data.load_train(config['inputs']['train']['batch_size'],
config['inputs']['share']['text1_maxlen'],
config['inputs']['share']['text1_maxlen']):
train_step(sess, ori_train, cand_train, neg_train, model)
cur_step = tf.train.global_step(sess, model.global_step)
if cur_step % 100 == 0 and cur_step != 0:
test_data = data.load_test(config['inputs']['share']['text1_maxlen'], config['inputs']['share']['text1_maxlen'])
qids, valid_ori_quests, valid_cand_quests, valid_labels =zip(*test_data)
valid_step(sess, model, valid_ori_quests, valid_cand_quests, valid_labels, qids, config)
# ---------------------------------- end train -----------------------------------
def predict(config):
if os.path.exists(config['model']['model_path']):
try:
saver = tf.train.import_meta_graph("Model/model.ckpt.meta")
with tf.Session() as sess:
saver.restore(sess, config['model']['model_path'])
except Exception as e:
logging.info("model not found",e)
def export(config):
pass
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--phase', default='train', help='Phase: Can be train or predict, the default value is train.')
parser.add_argument('--model_file', default='./configs/insurance/bilstm_config', help='Model_file: modelZoo model file for the chosen model.')
args = parser.parse_args()
model_file = args.model_file
with open(model_file, 'r') as f:
config = json.load(f)
# data = QAData(config,config,logger)
# data.setup()
print("args.phase:%s"%args.phase)
# for valid in valid_data:
# print(valid)
if args.phase == 'train':
train(config)
elif args.phase == 'predict':
predict(config)
elif args.phase == "export":
export(config)
else:
print('Phase Error.', end='\n')
if __name__=='__main__':
main(sys.argv)