예제 #1
0
    def train(self, sess, save_file, X_train, y_train, X_val, y_val):
        count = 0
        max_f = -1
        writer = tf.summary.FileWriter('./graphs_ar', sess.graph)
        trainloss = tf.summary.scalar("training_loss", self.ner_model.loss)
        for epoch in range(self.num_epochs): 
            print "current epoch: %d" % (epoch)
            for iteration in range(self.num_iterations):
                print "this iteration is %d"%(iteration)
                X_train_batch, y_train_batch = helper.nextRandomBatch(X_train, y_train, batch_size=self.batch_size)
                transition_batch = helper.getTransition(y_train_batch)
                _, train_loss, loss_train, max_scores, max_scores_pre, length =\
                    sess.run([
                        self.ner_model.optimizer,
                        trainloss,
                        self.ner_model.loss,
                        self.ner_model.max_scores,
                        self.ner_model.max_scores_pre,
                        self.ner_model.length,
                    ],
                    feed_dict={
                        self.ner_model.input_data:X_train_batch,
                        self.ner_model.targets:y_train_batch,
                        self.ner_model.targets_transition:transition_batch
                    })
                print "the loss : %f"%loss_train#, X_train_batch
                writer.add_summary(train_loss, epoch*self.num_iterations+iteration)
                if iteration % 100 == 0:
                  presicion_loc, recall_loc, f_loc, presicion_org, recall_org, f_org, presicion_per, recall_per, f_per = \
                  self.validationBatch(sess, X_val, y_val)
                  print "iteration: %5d, valid , valid precision: LOC %.5f, ORG %.5f, PER %.5f, valid recall: LOC %.5f, ORG %.5f, PER %.5f, valid f1: LOC %.5f, ORG %.5f, PER %.5f" %\
                  (iteration, presicion_loc, presicion_org, presicion_per, recall_loc, recall_org, recall_per, f_loc, f_org, f_per)

                  if f_loc + f_org + f_per >= max_f:
                    max_f = f_loc + f_org + f_per

                    saver = tf.train.Saver()
                    save_path = saver.save(sess, save_file)
                    print "saved the best model with f1: %.5f" % (max_f / 3.0)

                  self.last_f = f_loc + f_org + f_per
예제 #2
0
    def train(self, sess, save_file, X_train, y_train, X_val, y_val):
        saver = tf.train.Saver()

        char2id, id2char = helper.loadMap("char2id")
        label2id, id2label = helper.loadMap("label2id")

        merged = tf.contrib.deprecated.merge_all_summaries()
        summary_writer_train = tf.contrib.summary.SummaryWriter(
            'loss_log/train_loss', sess.graph)
        summary_writer_val = tf.contrib.summary.SummaryWriter(
            'loss_log/val_loss', sess.graph)

        num_iterations = int(math.ceil(1.0 * len(X_train) / self.batch_size))

        cnt = 0
        for epoch in range(self.num_epochs):
            # shuffle train in each epoch
            sh_index = np.arange(len(X_train))
            np.random.shuffle(sh_index)
            X_train = X_train[sh_index]
            y_train = y_train[sh_index]
            print("current epoch: %d" % (epoch))
            for iteration in range(num_iterations):
                # train
                X_train_batch, y_train_batch = helper.nextBatch(
                    X_train,
                    y_train,
                    start_index=iteration * self.batch_size,
                    batch_size=self.batch_size)
                y_train_weight_batch = 1 + np.array(
                    (y_train_batch == label2id['B']) |
                    (y_train_batch == label2id['E']), float)
                transition_batch = helper.getTransition(y_train_batch)

                _, loss_train, max_scores, max_scores_pre, length, train_summary = \
                 sess.run([
                  self.optimizer,
                  self.loss,
                  self.max_scores,
                  self.max_scores_pre,
                  self.length,
                  self.train_summary
                 ],
                  feed_dict={
                   self.targets_transition: transition_batch,
                   self.inputs: X_train_batch,
                   self.targets: y_train_batch,
                   self.targets_weight: y_train_weight_batch
                  })

                predicts_train = self.viterbi(max_scores,
                                              max_scores_pre,
                                              length,
                                              predict_size=self.batch_size)
                if iteration % 10 == 0:
                    cnt += 1
                    precision_train, recall_train, f1_train = self.evaluate(
                        X_train_batch, y_train_batch, predicts_train, id2char,
                        id2label)
                    summary_writer_train.add_summary(train_summary, cnt)
                    print(
                        "iteration: %5d, train loss: %5d, train precision: %.5f, train recall: %.5f, train f1: %.5f"
                        % (iteration, loss_train, precision_train,
                           recall_train, f1_train))

                # validation
                if iteration % 100 == 0:
                    X_val_batch, y_val_batch = helper.nextRandomBatch(
                        X_val, y_val, batch_size=self.batch_size)
                    y_val_weight_batch = 1 + np.array(
                        (y_val_batch == label2id['B']) |
                        (y_val_batch == label2id['E']), float)
                    transition_batch = helper.getTransition(y_val_batch)

                    loss_val, max_scores, max_scores_pre, length, val_summary = \
                     sess.run([
                      self.loss,
                      self.max_scores,
                      self.max_scores_pre,
                      self.length,
                      self.val_summary
                     ],
                      feed_dict={
                       self.targets_transition: transition_batch,
                       self.inputs: X_val_batch,
                       self.targets: y_val_batch,
                       self.targets_weight: y_val_weight_batch
                      })

                    predicts_val = self.viterbi(max_scores,
                                                max_scores_pre,
                                                length,
                                                predict_size=self.batch_size)
                    precision_val, recall_val, f1_val = self.evaluate(
                        X_val_batch, y_val_batch, predicts_val, id2char,
                        id2label)
                    summary_writer_val.add_summary(val_summary, cnt)
                    print(
                        "iteration: %5d, valid loss: %5d, valid precision: %.5f, valid recall: %.5f, valid f1: %.5f"
                        % (iteration, loss_val, precision_val, recall_val,
                           f1_val))

                    if f1_val > self.max_f1:
                        self.max_f1 = f1_val
                        save_path = saver.save(sess, save_file)
                        print("saved the best model with f1: %.5f" %
                              (self.max_f1))
예제 #3
0
    def train(self, sess, save_file, train_data, val_data):
        saver = tf.train.Saver(max_to_keep=3)

        #train data
        X_train = train_data['char']
        X_left_train = train_data['left']
        X_right_train = train_data['right']
        X_pos_train = train_data['pos']
        X_lpos_train = train_data['lpos']
        X_rpos_train = train_data['rpos']
        X_rel_train = train_data['rel']
        X_dis_train = train_data['dis']
        y_train = train_data['label']

        #dev data
        X_val = val_data['char']
        X_left_val = val_data['left']
        X_right_val = val_data['right']
        X_pos_val = val_data['pos']
        X_lpos_val = val_data['lpos']
        X_rpos_val = val_data['rpos']
        X_rel_val = val_data['rel']
        X_dis_val = val_data['dis']
        y_val = val_data['label']

        #dictionary
        char2id, id2char = helper.loadMap("char2id")
        pos2id, id2pos = helper.loadMap("pos2id")
        label2id, id2label = helper.loadMap("label2id")

        merged = tf.summary.merge_all()
        summary_writer_train = tf.summary.FileWriter('loss_log/train_loss', sess.graph)  
        summary_writer_val = tf.summary.FileWriter('loss_log/val_loss', sess.graph)     
        
        num_iterations = int(math.ceil(1.0 * len(X_train) / self.batch_size))

        cnt = 0
        for epoch in range(self.num_epochs):
            # shuffle train in each epoch
            sh_index = np.arange(len(X_train))
            np.random.shuffle(sh_index)
            X_train = X_train[sh_index]
            X_left_train = X_left_train[sh_index]
            X_right_train = X_right_train[sh_index]
            X_pos_train = X_pos_train[sh_index]
            X_lpos_train = X_lpos_train[sh_index]
            X_rpos_train = X_rpos_train[sh_index]
            X_rel_train = X_rel_train[sh_index]
            X_dis_train = X_dis_train[sh_index]
            y_train = y_train[sh_index]

            train_data['char'] = X_train
            train_data['left'] = X_left_train
            train_data['right'] = X_right_train
            train_data['pos'] = X_pos_train
            train_data['lpos'] = X_lpos_train
            train_data['rpos'] = X_rpos_train
            train_data['rel'] = X_rel_train
            train_data['dis'] = X_dis_train
            train_data['label'] = y_train

            print "current epoch: %d" % (epoch)
            for iteration in range(num_iterations):
                # train 
                #get batch
                train_batches = helper.nextBatch(train_data, start_index=iteration * self.batch_size, batch_size=self.batch_size)
                X_train_batch = train_batches['char']
                X_left_train_batch = train_batches['left']
                X_right_train_batch = train_batches['right']
                X_pos_train_batch = train_batches['pos']
                X_lpos_train_batch = train_batches['lpos']
                X_rpos_train_batch = train_batches['rpos']
                X_rel_train_batch = train_batches['rel']
                X_dis_train_batch = train_batches['dis']
                y_train_batch = train_batches['label']
                
                # feed batch to model and run
                _, loss_train, length, train_summary, logits, trans_params =\
                    sess.run([
                        self.optimizer, 
                        self.loss, 
                        self.length,
                        self.train_summary,
                        self.logits,
                        self.trans_params,
                    ], 
                    feed_dict={
                        self.inputs:X_train_batch,
                        self.lefts:X_left_train_batch,
                        self.rights:X_right_train_batch,
                        self.poses:X_pos_train_batch,
                        self.lposes:X_lpos_train_batch,
                        self.rposes:X_rpos_train_batch,
                        self.rels:X_rel_train_batch,
                        self.dises:X_dis_train_batch,
                        self.targets:y_train_batch 
                        # self.targets_weight:y_train_weight_batch
                    })
                # print (len(length))

                #get predict f1
                predicts_train = self.viterbi(logits, trans_params, length, predict_size=self.batch_size)
                if iteration > 0 and iteration % 10 == 0:
                    cnt += 1
                    hit_num, pred_num, true_num = self.evaluate(y_train_batch, predicts_train, id2char, id2label)
                    precision_train, recall_train, f1_train = self.caculate(hit_num, pred_num, true_num)
                    summary_writer_train.add_summary(train_summary, cnt)
                    print "iteration: %5d/%5d, train loss: %5d, train precision: %.5f, train recall: %.5f, train f1: %.5f" % (iteration, num_iterations, loss_train, precision_train, recall_train, f1_train)  
                    
                # a batch in validation
                if iteration > 0 and iteration % 100 == 0:
                    val_batches = helper.nextRandomBatch(val_data, batch_size=self.batch_size)
                    
                    X_val_batch = val_batches['char']
                    X_left_val_batch = val_batches['left']
                    X_right_val_batch = val_batches['right']
                    X_pos_val_batch = val_batches['pos']
                    X_lpos_val_batch = val_batches['lpos']
                    X_rpos_val_batch = val_batches['rpos']
                    X_rel_val_batch = val_batches['rel']
                    X_dis_val_batch = val_batches['dis']
                    y_val_batch = val_batches['label']
                    
                    loss_val, length, val_summary, logits, trans_params =\
                        sess.run([
                            self.loss, 
                            self.length,
                            self.val_summary,
                            self.logits,
                            self.trans_params,
                        ], 
                        feed_dict={
                            self.inputs:X_val_batch,
                            self.lefts:X_left_val_batch,
                            self.rights:X_right_val_batch,
                            self.poses:X_pos_val_batch,
                            self.lposes:X_lpos_val_batch,
                            self.rposes:X_rpos_val_batch,
                            self.rels:X_rel_val_batch,
                            self.dises:X_dis_val_batch,
                            self.targets:y_val_batch 
                            # self.targets_weight:y_val_weight_batch
                        })
                    
                    predicts_val = self.viterbi(logits, trans_params, length, predict_size=self.batch_size)
                    hit_num, pred_num, true_num = self.evaluate(y_val_batch, predicts_val, id2char, id2label)
                    precision_val, recall_val, f1_val = self.caculate(hit_num, pred_num, true_num)
                    summary_writer_val.add_summary(val_summary, cnt)
                    print "iteration: %5d, valid loss: %5d, valid precision: %.5f, valid recall: %.5f, valid f1: %.5f" % (iteration, loss_val, precision_val, recall_val, f1_val)

                # calc f1 for the whole dev set
                if epoch > 0 and iteration == num_iterations -1:
                    num_val_iterations = int(math.ceil(1.0 * len(X_val) / self.batch_size))
                    preds_lines = []
                    for val_iteration in range(num_val_iterations):
                        val_batches = helper.nextBatch(val_data, start_index=val_iteration * self.batch_size, batch_size=self.batch_size)
                        X_val_batch = val_batches['char']
                        X_left_val_batch = val_batches['left']
                        X_right_val_batch = val_batches['right']
                        X_pos_val_batch = val_batches['pos']
                        X_lpos_val_batch = val_batches['lpos']
                        X_rpos_val_batch = val_batches['rpos']
                        X_rel_val_batch = val_batches['rel']
                        X_dis_val_batch = val_batches['dis']
                        y_val_batch = val_batches['label']

                        loss_val, length, val_summary, logits, trans_params =\
                            sess.run([
                                self.loss, 
                                self.length,
                                self.val_summary,
                                self.logits,
                                self.trans_params,
                            ], 
                            feed_dict={
                                self.inputs:X_val_batch,
                                self.lefts:X_left_val_batch,
                                self.rights:X_right_val_batch,
                                self.poses:X_pos_val_batch,
                                self.lposes:X_lpos_val_batch,
                                self.rposes:X_rpos_val_batch,
                                self.rels:X_rel_val_batch,
                                self.dises:X_dis_val_batch,
                                self.targets:y_val_batch 
                                # self.targets_weight:y_val_weight_batch
                            })
                    
                        predicts_val = self.viterbi(logits, trans_params, length, predict_size=self.batch_size)
                        preds_lines.extend(predicts_val)
                    preds_lines = preds_lines[:len(y_val)]
                    recall_val, precision_val, f1_val, errors = helper.calc_f1(preds_lines, id2label, 'cpbdev.txt', 'validation.out')
                    if f1_val > self.max_f1:
                        self.max_f1 = f1_val
                        save_path = saver.save(sess, save_file)
                        helper.calc_f1(preds_lines, id2label, 'cpbdev.txt', 'validation.out.best')
                        print "saved the best model with f1: %.5f" % (self.max_f1)
                    print "valid precision: %.5f, valid recall: %.5f, valid f1: %.5f, errors: %5d" % (precision_val, recall_val, f1_val, errors)
    def train(self, sess, save_file, X_train, y_train, X_val, y_val):
        saver = tf.train.Saver()

        char2id, id2char = helper.loadMap("char2id")
        label2id, id2label = helper.loadMap("label2id")

        merged = tf.merge_all_summaries()
        summary_writer_train = tf.train.SummaryWriter('loss_log/train_loss', sess.graph)  
        summary_writer_val = tf.train.SummaryWriter('loss_log/val_loss', sess.graph)     
        
        num_iterations = int(math.ceil(1.0 * len(X_train) / self.batch_size))

        cnt = 0
        for epoch in range(self.num_epochs):
            # shuffle train in each epoch
            sh_index = np.arange(len(X_train))
            np.random.shuffle(sh_index)
            X_train = X_train[sh_index]
            y_train = y_train[sh_index]
            print "current epoch: %d" % (epoch)
            for iteration in range(num_iterations):
                # train
                X_train_batch, y_train_batch = helper.nextBatch(X_train, y_train, start_index=iteration * self.batch_size, batch_size=self.batch_size)
                y_train_weight_batch = 1 + np.array((y_train_batch == label2id['B']) | (y_train_batch == label2id['E']), float)
                transition_batch = helper.getTransition(y_train_batch)
                
                _, loss_train, max_scores, max_scores_pre, length, train_summary =\
                    sess.run([
                        self.optimizer, 
                        self.loss, 
                        self.max_scores, 
                        self.max_scores_pre, 
                        self.length,
                        self.train_summary
                    ], 
                    feed_dict={
                        self.targets_transition:transition_batch, 
                        self.inputs:X_train_batch, 
                        self.targets:y_train_batch, 
                        self.targets_weight:y_train_weight_batch
                    })

                predicts_train = self.viterbi(max_scores, max_scores_pre, length, predict_size=self.batch_size)
                if iteration % 10 == 0:
                    cnt += 1
                    precision_train, recall_train, f1_train = self.evaluate(X_train_batch, y_train_batch, predicts_train, id2char, id2label)
                    summary_writer_train.add_summary(train_summary, cnt)
                    print "iteration: %5d, train loss: %5d, train precision: %.5f, train recall: %.5f, train f1: %.5f" % (iteration, loss_train, precision_train, recall_train, f1_train)  
                    
                # validation
                if iteration % 100 == 0:
                    X_val_batch, y_val_batch = helper.nextRandomBatch(X_val, y_val, batch_size=self.batch_size)
                    y_val_weight_batch = 1 + np.array((y_val_batch == label2id['B']) | (y_val_batch == label2id['E']), float)
                    transition_batch = helper.getTransition(y_val_batch)
                    
                    loss_val, max_scores, max_scores_pre, length, val_summary =\
                        sess.run([
                            self.loss, 
                            self.max_scores, 
                            self.max_scores_pre, 
                            self.length,
                            self.val_summary
                        ], 
                        feed_dict={
                            self.targets_transition:transition_batch, 
                            self.inputs:X_val_batch, 
                            self.targets:y_val_batch, 
                            self.targets_weight:y_val_weight_batch
                        })
                    
                    predicts_val = self.viterbi(max_scores, max_scores_pre, length, predict_size=self.batch_size)
                    precision_val, recall_val, f1_val = self.evaluate(X_val_batch, y_val_batch, predicts_val, id2char, id2label)
                    summary_writer_val.add_summary(val_summary, cnt)
                    print "iteration: %5d, valid loss: %5d, valid precision: %.5f, valid recall: %.5f, valid f1: %.5f" % (iteration, loss_val, precision_val, recall_val, f1_val)

                    if f1_val > self.max_f1:
                        self.max_f1 = f1_val
                        save_path = saver.save(sess, save_file)
                        print "saved the best model with f1: %.5f" % (self.max_f1)
예제 #5
0
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))

accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    step = 0
    # Keep training until reach max iterations
    while step < training_iters:
        # batch_x, batch_y = mnist.train.next_batch(batch_size)
        batch_x, batch_y = helper.nextRandomBatch(X_train,
                                                  y_train,
                                                  batch_size=125)
        batch_y = batch_y[:, 2]
        tmp_y = []
        for i in range(0, batch_y.shape[0]):
            if batch_y[i] == 2:
                tmp_y.append([0, 1])
            else:
                tmp_y.append([1, 0])
        tmp_y = np.array(tmp_y)
        batch_y = tmp_y
        # Run optimization op (backprop)
        sess.run(optimizer, feed_dict={x1: batch_x, y: batch_y})

        if step % display_step == 0:
            # Calculate batch accuracy
    def train(self, sess, save_file, X_train, y_train, X_val, y_val):

        saver = tf.train.Saver()

        summary_writer_train = tf.summary.FileWriter('loss_log/train_loss',
                                                     sess.graph)
        summary_writer_val = tf.summary.FileWriter('loss_log/val_loss',
                                                   sess.graph)

        num_iterations = int(math.ceil(1.0 * len(X_train) / self.batch_size))

        for epoch in range(self.num_epochs):

            # shuffle train in each epoch
            sh_index = np.arange(len(X_train))
            np.random.shuffle(sh_index)
            X_train = X_train[sh_index]
            y_train = y_train[sh_index]

            print("current epoch: %d" % (epoch))

            for iteration in range(num_iterations):
                # train
                X_train_batch1, X_train_batch2, y_train_batch = helper.nextBatch(
                    X_train, y_train, iteration * self.batch_size,
                    self.batch_size)

                _, train_loss, train_acc, train_summary = sess.run(
                    [
                        self.optimizer,
                        self.loss,
                        # self.predictions,
                        self.accuracy,
                        self.summary_op
                    ],
                    feed_dict={
                        self.input1: X_train_batch1,
                        self.input2: X_train_batch2,
                        self.targets: y_train_batch
                    })

                if iteration % 20 == 0:
                    # train_acc = helper.extractSense(y_train_batch, train_y_hat)
                    summary_writer_train.add_summary(train_summary, iteration)
                    print(
                        "iteration: %5d, train loss: %5d, train precision: %.5f"
                        % (iteration, train_loss, train_acc))

                # validation
                if iteration % 20 == 0:

                    X_val_batch1, X_val_batch2, y_val_batch = helper.nextRandomBatch(
                        X_val, y_val, self.batch_size)
                    dev_loss, dev_acc, val_summary = sess.run(
                        [
                            self.loss,
                            # self.predictions,
                            self.accuracy,
                            self.summary_op
                        ],
                        feed_dict={
                            self.input1: X_val_batch1,
                            self.input2: X_val_batch2,
                            self.targets: y_val_batch
                        })

                    # test_acc = helper.extractSense(y_val_batch, dev_y_hat)
                    summary_writer_val.add_summary(val_summary, iteration)
                    print(
                        "iteration: %5d, dev loss: %5d, dev precision: %.5f" %
                        (iteration, dev_loss, dev_acc))

                    if dev_acc > self.max_acc:
                        self.max_acc = dev_acc
                        saver.save(sess, save_file)
                        print("saved the best model with accuracy: %.5f" %
                              (self.max_acc))