def infer(sentences, **kwargs): config = load_config(FLAGS.config_file) logger = get_logger(FLAGS.log_file) reformed_sentences = [' '.join(sen[1]) for sen in sentences] result = model.evaluate_lines(sess, inputs_from_sentences(reformed_sentences, char_to_id, FLAGS.max_char_length), id_to_tag) ''' result = [ (0.0, ['ARG0', 'ARG3', '-']), (0.0, ['ARG0', 'ARG1', '-']) ] # evaluate_lines 함수는 문장 단위 분석 결과를 내어줍니다. # len(result) : 문장의 갯수, 따라서 위 예제는 두 문장의 결과입니다. # result[0] : 첫번째 문장의 분석 결과, result[1] : 두번째 문장의 분석 결과. # 각 문장의 분석 결과는 다시 (prob, [labels])로 구성됩니다. # prob에 해당하는 자료는 이번 task에서 사용하지 않습니다. 따라서 그 값이 결과에 영향을 미치지 않습니다. # [labels]는 각 어절의 분석 결과를 담고 있습니다. 따라서 다음과 같이 구성됩니다. ## ['첫번째 어절의 분석 결과', '두번째 어절의 분석 결과', ...] # 예를 들면 위 주어진 예제에서 첫번째 문장의 첫번째 어절은 'ARG0'을, 첫번째 문장의 두번째 어절은 'ARG3'을 argument label로 가집니다. ### 주의사항 ### # 모든 어절의 결과를 제출하여야 합니다. # 어절의 순서가 지켜져야 합니다. (첫번째 어절부터 순서대로 list 내에 위치하여야 합니다.) ''' return result
def evaluate_cli(model, context_embeddings_op, elmo_context, elmo_ids): config = load_config(FLAGS.config_file) logger = get_logger(FLAGS.log_file) if FLAGS.task == "NER": with open(FLAGS.necessary, "rb") as f: word_to_id, id_to_word, char_to_id, id_to_char, pumsa_to_id, id_to_pumsa, tag_to_id, id_to_tag, ner_morph_tag = pickle.load( f) komoran = Komoran() results = [] while True: # line = input("문장을 입력하세요.:") line = [ "찬민이의 멘탈이 산산조각났습니다.", "진짜 진짜 진짜 맛있는 진짜 라면", "집에 가고 싶읍니다.", "집", "가 가 가 가 가 가, 가, 가 ,가, 가 가 가 가 가 가, 가, 가 ,가 !!!!! ." ] for idx in range(0, len(line), 5): l = line[idx:idx + 2] results.extend( model.evaluate_lines( sess, context_embeddings_op, elmo_context, elmo_ids, ner_morph_tag, inputs_from_sentences(komoran, l, word_to_id, pumsa_to_id, char_to_id, elmo_dict, FLAGS.max_char_length, ner_morph_tag), id_to_tag)) print(results)
def evaluate_cli(model): config = load_config(FLAGS.config_file) logger = get_logger(FLAGS.log_file) with open(FLAGS.map_file, "rb") as f: char_to_id, id_to_char, tag_to_id, id_to_tag = pickle.load(f) while True: line = input("문장을 입력하세요.:") result = model.evaluate_lines(sess, inputs_from_sentences([line], char_to_id, FLAGS.max_char_length), id_to_tag) print(result)
def evaluate_line(): config = model_utils.load_config(FLAGS.config_file) tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True with open(FLAGS.map_file, "rb") as f: word_to_id, id_to_word, tag_to_id, id_to_tag = pickle.load(f) with tf.Session(config=tf_config) as sess: model = model_utils.create(sess, Model, FLAGS.ckpt_path, config) book = openpyxl.load_workbook(r'输入文件.xlsx') sh = book.active arr = [] for r in list(sh.rows)[1:]: line = r[1].value result = model.evaluate_line( sess, data_utils.input_from_line(line, word_to_id), id_to_tag) arr.append({"id": r[0].value, "data": result}) print(arr) newbook = openpyxl.Workbook() sh = newbook.active headtype = { 'DIS': { "name": '疾病', "num": 20 }, '症状的type': { "name": '症状', "num": 20 }, 'DURG': { "name": '药物', "num": 20 } } harr = ['ID'] for n, t in headtype.items(): t['start'] = len(harr) for i in range(1, t['num'] + 1): harr.append(t['name'] + str(i)) sh.append(harr) for t in arr: larr = [''] * len(harr) larr[0] = t['id'] htc = {k: obj['start'] for k, obj in headtype.items()} for entitie in t['data']['entities']: larr[htc[entitie['type']]] = entitie['word'] htc[entitie['type']] += 1 sh.append(larr) newbook.save(r'输出文件.xlsx')
def evaluate_line(): config = model_utils.load_config(FLAGS.config_file) logger = model_utils.get_logger(FLAGS.log_file) tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True with open(FLAGS.map_file, 'rb') as f: word_to_id, id_to_word, tag_to_id, id_to_tag = pickle.load(f) with tf.Session(config=tf_config) as sess: model = model_utils.create(sess, Model, FLAGS.ckpt_path, load_word2vec, config, id_to_word, logger, FLAGS.train) while True: line = input('请输入测试句子(输入q退出):') if line == 'q': return result = model.evaluate_line( sess, data_utils.input_from_line(line, word_to_id), id_to_tag) print(result)
def infer(sentences, **kwargs): config = load_config(FLAGS.config_file) logger = get_logger(FLAGS.log_file) if config['elmo']: elmo_dict = load_elmo_dict(FLAGS.elmo_dict) else: elmo_dict = None results = [] komoran = Komoran() reformed_sentences = [' '.join(sen[1]) for sen in sentences] for idx in range(0, len(reformed_sentences), 100): reformed_sentence = reformed_sentences[idx:idx + 100] results.extend( model.evaluate_lines( sess, context_embeddings_op, elmo_context, elmo_ids, ner_morph_tag, inputs_from_sentences(komoran, reformed_sentence, word_to_id, pumsa_to_id, char_to_id, elmo_dict, FLAGS.max_char_length, ner_morph_tag), id_to_tag)) # results.extend(model.evaluate_lines(sess, context_embeddings_op, elmo_context, elmo_ids, ner_morph_tag,\ # inputs_from_sentences(komoran, reformed_sentence, word_to_id, pumsa_to_id, char_to_id, elmo_dict, FLAGS.max_char_length, ner_morph_tag), id_to_tag)) ''' result = [ (0.0, ['ARG0', 'ARG3', '-']), (0.0, ['ARG0', 'ARG1', '-']) ] # evaluate_lines 함수는 문장 단위 분석 결과를 내어줍니다. # len(result) : 문장의 갯수, 따라서 위 예제는 두 문장의 결과입니다. # result[0] : 첫번째 문장의 분석 결과, result[1] : 두번째 문장의 분석 결과. # 각 문장의 분석 결과는 다시 (prob, [labels])로 구성됩니다. # prob에 해당하는 자료는 이번 task에서 사용하지 않습니다. 에 영향을 미치지 않습니다. # [labels]는 각 어절의 분석 결과를 담고 있습니다. 따라서 다음과 같이 구성됩따라서 그 값이 결과니다. ## ['첫번째 어절의 분석 결과', '두번째 어절의 분석 결과', ...] # 예를 들면 위 주어진 예제에서 첫번째 문장의 첫번째 어절은 'ARG0'을, 첫번째 문장의 두번째 어절은 'ARG3'을 argument label로 가집니다. ### 주의사항 ### # 모든 어절의 결과를 제출하여야 합니다. # 어절의 순서가 지켜져야 합니다. (첫번째 어절부터 순서대로 list 내에 위치하여야 합니다.) ''' '' # results[1000000000000000000000000] # test return results
def load(dir_path, *args): global char_to_id global id_to_tag config = load_config(FLAGS.config_file) logger = get_logger(FLAGS.log_file) tf.get_variable_scope().reuse_variables() with open(os.path.join(dir_path,FLAGS.map_file), "rb") as f: char_to_id, _, __, id_to_tag = pickle.load(f) saver = tf.train.Saver() ckpt = tf.train.get_checkpoint_state(dir_path) if ckpt and ckpt.model_checkpoint_path: checkpoint = os.path.basename(ckpt.model_checkpoint_path) saver.restore(sess, os.path.join(dir_path, checkpoint)) else: raise NotImplemented('No checkpoint found!') print ('model loaded!')
def train(): # 加载数据集 train_sentences = dl.load_sentences(FLAGS.train_file) dev_sentences = dl.load_sentences(FLAGS.dev_file) test_sentences = dl.load_sentences(FLAGS.test_file) # 转换编码 bio转bioes dl.update_tag_scheme(train_sentences, FLAGS.tag_schema) dl.update_tag_scheme(test_sentences, FLAGS.tag_schema) dl.update_tag_scheme(dev_sentences, FLAGS.tag_schema) # 创建单词映射及标签映射 if not os.path.isfile(FLAGS.map_file): _, word_to_id, id_to_word = dl.word_mapping(train_sentences) _, tag_to_id, id_to_tag = dl.tag_mapping(train_sentences) with open(FLAGS.map_file, 'wb') as f: pickle.dump([word_to_id, id_to_word, tag_to_id, id_to_tag], f) else: with open(FLAGS.map_file, 'rb') as f: unpickler = pickle.Unpickler(f) scores = unpickler.load() word_to_id, id_to_word, tag_to_id, id_to_tag = scores train_data = dl.prapare_dataset(train_sentences, word_to_id, tag_to_id) dev_data = dl.prapare_dataset(train_sentences, word_to_id, tag_to_id) test_data = dl.prapare_dataset(train_sentences, word_to_id, tag_to_id) print('train_data %i, dev_data_num %i, test_data_num %i' % (len(train_data), len(dev_data), len(test_data))) mu.make_path(FLAGS) if os.path.isfile(FLAGS.config_file): config = mu.load_config(FLAGS.config_file) else: config = mu.config_model(FLAGS, word_to_id, tag_to_id) mu.save_config(config, FLAGS.config_file) log_path = os.path.join('log', FLAGS.log_file) logger = mu.get_log(log_path) mu.print_config(config, logger) print('aa')
def evaluate_line(): config = model_utils.load_config(FLAGS.config_file) tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True with open(FLAGS.map_file, "rb") as f: word_to_id, id_to_word, tag_to_id, id_to_tag = pickle.load(f) with tf.Session(config=tf_config) as sess: model = model_utils.create(sess, Model, FLAGS.ckpt_path, config) out = [] df = pd.read_excel(local_file) for line in df['病历']: result = model.evaluate_line( sess, data_utils.input_from_line(line, word_to_id), id_to_tag) out.append(handle(result)) columns = [] for item in types_index: for i in range(1, types_num + 1): columns.append(item + str(i)) df_out = pd.DataFrame(out, columns=columns) df_out.insert(loc=0, column='ID', value=df['ID']) df_out.to_excel(result_file, index=None)
def evaluate_line(): config = model_utils.load_config(FLAGS.config_file) tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True with open(FLAGS.map_file, "rb") as f: word_to_id, id_to_word, tag_to_id, id_to_tag = pickle.load(f) with tf.Session(config=tf_config) as sess: model = model_utils.create(sess, Model, FLAGS.ckpt_path, config) df = pd.read_excel('1.xlsx') for line in df['文本']: result = model.evaluate_line( sess, data_utils.input_from_line(line, word_to_id), id_to_tag) print(result)
def train(): # 加载数据集 train_sentences = data_loader.load_sentences(FLAGS.train_file) dev_sentences = data_loader.load_sentences(FLAGS.dev_file) test_sentences = data_loader.load_sentences(FLAGS.test_file) # 转换编码 data_loader.update_tag_scheme(train_sentences, FLAGS.tag_schema) data_loader.update_tag_scheme(dev_sentences, FLAGS.tag_schema) data_loader.update_tag_scheme(test_sentences, FLAGS.tag_schema) # 创建单词和词典映射 if not os.path.isfile(FLAGS.map_file): if FLAGS.pre_emb: dico_words_train = data_loader.word_mapping(train_sentences)[0] dico_word, word_to_id, id_to_word = data_utils.augment_with_pretrained( dico_words_train.copy(), FLAGS.emb_file, list( itertools.chain.from_iterable([[w[0] for w in s] for s in test_sentences]))) else: _, word_to_id, id_to_word = data_loader.word_mapping( train_sentences) _, tag_to_id, id_to_tag = data_loader.tag_mapping(train_sentences) with open(FLAGS.map_file, 'wb') as f: pickle.dump([word_to_id, id_to_word, tag_to_id, id_to_tag], f) else: with open(FLAGS.map_file, 'rb') as f: word_to_id, id_to_word, tag_to_id, id_to_tag = pickle.load(f) # 准备数据 train_data = data_loader.prepare_dataset(train_sentences, word_to_id, tag_to_id) dev_data = data_loader.prepare_dataset(dev_sentences, word_to_id, tag_to_id) test_data = data_loader.prepare_dataset(test_sentences, word_to_id, tag_to_id) # 将数据分批处理 train_manager = data_utils.BatchManager(train_data, FLAGS.batch_size) dev_manager = data_utils.BatchManager(dev_data, FLAGS.batch_size) test_manager = data_utils.BatchManager(test_data, FLAGS.batch_size) # 创建不存在的文件夹 model_utils.make_path(FLAGS) # 判断配置文件 if os.path.isfile(FLAGS.config_file): config = model_utils.load_config(FLAGS.config_file) else: config = model_utils.config_model(FLAGS, word_to_id, tag_to_id) model_utils.save_config(config, FLAGS.config_file) # 配置印logger log_path = os.path.join('log', FLAGS.log_file) logger = model_utils.get_logger(log_path) model_utils.print_config(config, logger) tf_config = tf.ConfigProto(allow_soft_placement=True) tf_config.gpu_options.allow_growth = True step_per_epoch = train_manager.len_data with tf.Session(config=tf_config) as sess: model = model_utils.create(sess, Model, FLAGS.ckpt_path, load_word2vec, config, id_to_word, logger) logger.info('开始训练') loss = [] start = time.time() for i in range(100): for batch in train_manager.iter_batch(shuffle=True): step, batch_loss = model.run_step(sess, True, batch) loss.append(batch_loss) if step % FLAGS.setps_chech == 0: iteration = step // step_per_epoch + 1 logger.info( "iteration{}: step{}/{}, NER loss:{:>9.6f}".format( iteration, step % step_per_epoch, step_per_epoch, np.mean(loss))) loss = [] best = evaluate(sess, model, 'dev', dev_manager, id_to_tag, logger) if best: model_utils.save_model(sess, model, FLAGS.ckpt_path, logger) evaluate(sess, model, 'test', test_manager, id_to_tag, logger) t = time.time() - start logger.info('cost time: %f' % t)
test_manager = data_utils.BatchManager(test_data, FLAGS.batch_size) print('train_data_num %i, dev_data_num %i, test_data_num %i' % (len(train_data), len(dev_data), len(test_data))) model_utils.make_path(FLAGS) if os.path.isfile(FLAGS.config_file): config = model_utils.load_config(FLAGS.config_file) else: config = model_utils.config_model(FLAGS, word_to_id, tag_to_id) model_utils.save_config(config, FLAGS.config_file) log_path = os.path.join("log", FLAGS.log_file) logger = model_utils.get_logger(log_path) model_utils.print_config(config, logger)
def train(): # 加载数据集 train_sentences = data_loader.load_sentences(FLAGS.train_file) dev_sentences = data_loader.load_sentences(FLAGS.dev_file) test_sentences = data_loader.load_sentences(FLAGS.test_file) # 转换编码 bio转bioes data_loader.update_tag_scheme(train_sentences, FLAGS.tag_schema) data_loader.update_tag_scheme(test_sentences, FLAGS.tag_schema) data_loader.update_tag_scheme(dev_sentences, FLAGS.tag_schema) # 创建单词映射及标签映射 if not os.path.isfile(FLAGS.map_file): if FLAGS.pre_emb: dico_words_train = data_loader.word_mapping(train_sentences)[0] dico_word, word_to_id, id_to_word = data_utils.augment_with_pretrained( dico_words_train.copy(), FLAGS.emb_file, list( itertools.chain.from_iterable( [[w[0] for w in s] for s in test_sentences] ) ) ) else: _, word_to_id, id_to_word = data_loader.word_mapping(train_sentences) _, tag_to_id, id_to_tag = data_loader.tag_mapping(train_sentences) with open(FLAGS.map_file, "wb") as f: pickle.dump([word_to_id, id_to_word, tag_to_id, id_to_tag], f) else: with open(FLAGS.map_file, 'rb') as f: word_to_id, id_to_word, tag_to_id, id_to_tag = pickle.load(f) train_data = data_loader.prepare_dataset( train_sentences, word_to_id, tag_to_id ) dev_data = data_loader.prepare_dataset( dev_sentences, word_to_id, tag_to_id ) test_data = data_loader.prepare_dataset( test_sentences, word_to_id, tag_to_id ) train_manager = data_utils.BatchManager(train_data, FLAGS.batch_size) dev_manager = data_utils.BatchManager(dev_data, FLAGS.batch_size) test_manager = data_utils.BatchManager(test_data, FLAGS.batch_size) print('train_data_num %i, dev_data_num %i, test_data_num %i' % (len(train_data), len(dev_data), len(test_data))) model_utils.make_path(FLAGS) if os.path.isfile(FLAGS.config_file): config = model_utils.load_config(FLAGS.config_file) else: config = model_utils.config_model(FLAGS, word_to_id, tag_to_id) model_utils.save_config(config, FLAGS.config_file) log_path = os.path.join("log", FLAGS.log_file) logger = model_utils.get_logger(log_path) model_utils.print_config(config, logger) tf_config = tf.ConfigProto() tf_config.gpu_options.allow_growth = True steps_per_epoch =train_manager.len_data with tf.Session(config = tf_config) as sess: model = model_utils.create(sess, Model, FLAGS.ckpt_path, load_word2vec, config, id_to_word, logger) logger.info("开始训练") loss = [] for i in range(100): for batch in train_manager.iter_batch(shuffle=True): step, batch_loss = model.run_step(sess, True, batch) loss.append(batch_loss) if step % FLAGS.setps_chech== 0: iterstion = step // steps_per_epoch + 1 logger.info("iteration:{} step{}/{},NER loss:{:>9.6f}".format(iterstion, step%steps_per_epoch, steps_per_epoch, np.mean(loss))) loss = [] best = evaluate(sess,model,"dev", dev_manager, id_to_tag, logger) if best: model_utils.save_model(sess, model, FLAGS.ckpt_path, logger) evaluate(sess, model, "test", test_manager, id_to_tag, logger)