Ejemplo n.º 1
0
def main(unused_argv):
    
    vocab, pretrained_matrix = load_glove(vocab_size=100000, embedding_size=300)
    with tf.Graph().as_default():

        image_id, image_features, indicator, word_ids, pointer_ids = import_mscoco(
            mode="train", batch_size=FLAGS.batch_size, num_epochs=FLAGS.num_epochs, is_mini=FLAGS.is_mini)
        lengths = tf.reduce_sum(indicator, [1])
        show_and_tell_cell = ShowAndTellCell(300)
        best_first_image_captioner = BestFirstImageCaptioner(show_and_tell_cell, vocab, pretrained_matrix)
        word_logits, wids, pointer_logits, pids, ids, _lengths = best_first_image_captioner(
            mean_image_features=image_features,
            word_ids=word_ids, pointer_ids=pointer_ids, lengths=lengths)
        tf.losses.sparse_softmax_cross_entropy(pointer_ids, pointer_logits)
        tf.losses.sparse_softmax_cross_entropy(word_ids, word_logits)
        loss = tf.losses.get_total_loss()
        
        global_step = tf.train.get_or_create_global_step()
        optimizer = tf.train.AdamOptimizer()
        learning_step = optimizer.minimize(loss, var_list=best_first_image_captioner.variables, 
            global_step=global_step)

        captioner_saver = tf.train.Saver(var_list=best_first_image_captioner.variables + [global_step])
        captioner_ckpt, captioner_ckpt_name = get_best_first_checkpoint()
        with tf.Session() as sess:
            
            sess.run(tf.variables_initializer(optimizer.variables()))
            if captioner_ckpt is not None:
                captioner_saver.restore(sess, captioner_ckpt)
            else:
                sess.run(tf.variables_initializer(best_first_image_captioner.variables + [global_step]))
            captioner_saver.save(sess, captioner_ckpt_name, global_step=global_step)
            last_save = time.time()
            
            for i in itertools.count():
                
                time_start = time.time()
                try:
                    twids, tpids, _ids, _lengths, _loss, _learning_step = sess.run([
                        word_ids, pointer_ids, ids, lengths, loss, learning_step])
                except:
                    break
                    
                iteration = sess.run(global_step)
                
                insertion_sequence = insertion_sequence_to_array(twids, tpids, _lengths, vocab)
                    
                print(PRINT_STRING.format(
                    iteration, _loss, 
                    list_of_ids_to_string(insertion_sequence[0], vocab), 
                    list_of_ids_to_string(twids[0, :].tolist(), vocab), 
                    FLAGS.batch_size / (time.time() - time_start)))
                
                new_save = time.time()
                if new_save - last_save > 3600: # save the model every hour
                    captioner_saver.save(sess, captioner_ckpt_name, global_step=global_step)
                    last_save = new_save
                    
            captioner_saver.save(sess, captioner_ckpt_name, global_step=global_step)
            print("Finishing training.")
PRINT_STRING = """({3:.2f} img/sec) iteration: {0:05d}\n    caption: {1}\n    label: {2}"""
BATCH_SIZE = 10
BEAM_SIZE = 16

if __name__ == "__main__":

    vocab, pretrained_matrix = load_glove(vocab_size=100000,
                                          embedding_size=300)
    with tf.Graph().as_default():

        image_id, mean_features, input_seq, target_seq, indicator = (
            import_mscoco(mode="train",
                          batch_size=BATCH_SIZE,
                          num_epochs=1,
                          is_mini=True))
        image_captioner = ImageCaptioner(ShowAndTellCell(300),
                                         vocab,
                                         pretrained_matrix,
                                         trainable=False,
                                         beam_size=BEAM_SIZE)
        logits, ids = image_captioner(mean_image_features=mean_features)
        captioner_saver = tf.train.Saver(
            var_list=remap_decoder_name_scope(image_captioner.variables))
        captioner_ckpt, captioner_ckpt_name = get_show_and_tell_checkpoint()

        with tf.Session() as sess:

            assert (captioner_ckpt is not None)
            captioner_saver.restore(sess, captioner_ckpt)
            used_ids = set()
            json_dump = []
Ejemplo n.º 3
0
def main(unused_argv):

    vocab, pretrained_matrix = load_glove(vocab_size=100000,
                                          embedding_size=300)
    with tf.Graph().as_default():

        image_id, mean_features, input_seq, target_seq, indicator = (
            import_mscoco(mode="train",
                          batch_size=BATCH_SIZE,
                          num_epochs=100,
                          is_mini=True))
        show_and_tell_cell = ShowAndTellCell(300)
        image_captioner = ImageCaptioner(show_and_tell_cell, vocab,
                                         pretrained_matrix)
        logits, ids = image_captioner(lengths=tf.reduce_sum(indicator, axis=1),
                                      mean_image_features=mean_features,
                                      seq_inputs=input_seq)
        tf.losses.sparse_softmax_cross_entropy(target_seq,
                                               logits,
                                               weights=indicator)
        loss = tf.losses.get_total_loss()

        global_step = tf.train.get_or_create_global_step()
        learning_rate = tf.train.exponential_decay(
            INITIAL_LEARNING_RATE,
            global_step, (TRAINING_EXAMPLES // BATCH_SIZE) * EPOCHS_PER_DECAY,
            DECAY_RATE,
            staircase=True)
        learning_step = tf.train.GradientDescentOptimizer(
            learning_rate).minimize(loss,
                                    var_list=image_captioner.variables,
                                    global_step=global_step)

        captioner_saver = tf.train.Saver(var_list=image_captioner.variables +
                                         [global_step])
        captioner_ckpt, captioner_ckpt_name = get_show_and_tell_checkpoint()
        with tf.Session() as sess:

            if captioner_ckpt is not None:
                captioner_saver.restore(sess, captioner_ckpt)
            else:
                sess.run(
                    tf.variables_initializer(image_captioner.variables +
                                             [global_step]))
            captioner_saver.save(sess,
                                 captioner_ckpt_name,
                                 global_step=global_step)
            last_save = time.time()

            for i in itertools.count():

                time_start = time.time()
                try:
                    _ids, _loss, _learning_step = sess.run(
                        [ids, loss, learning_step])
                except:
                    break

                iteration = sess.run(global_step)

                print(
                    PRINT_STRING.format(
                        iteration, _loss,
                        list_of_ids_to_string(_ids[0, :].tolist(), vocab),
                        BATCH_SIZE / (time.time() - time_start)))

                new_save = time.time()
                if new_save - last_save > 3600:  # save the model every hour
                    captioner_saver.save(sess,
                                         captioner_ckpt_name,
                                         global_step=global_step)
                    last_save = new_save

            captioner_saver.save(sess,
                                 captioner_ckpt_name,
                                 global_step=global_step)
            print("Finishing training.")
tf.flags.DEFINE_boolean("is_mini", False, "")
tf.flags.DEFINE_string("mode", "eval", "")
FLAGS = tf.flags.FLAGS

if __name__ == "__main__":

    vocab, pretrained_matrix = load_glove(vocab_size=100000,
                                          embedding_size=300)
    with tf.Graph().as_default():

        image_id, image_features, indicator, word_ids, pointer_ids = import_mscoco(
            mode=FLAGS.mode,
            batch_size=FLAGS.batch_size,
            num_epochs=1,
            is_mini=FLAGS.is_mini)
        image_captioner = BestFirstImageCaptioner(ShowAndTellCell(300),
                                                  vocab,
                                                  pretrained_matrix,
                                                  trainable=False,
                                                  beam_size=FLAGS.beam_size)
        word_logits, wids, pointer_logits, pids, ids, _lengths = image_captioner(
            mean_image_features=image_features)
        captioner_saver = tf.train.Saver(
            var_list=remap_decoder_name_scope(image_captioner.variables))
        captioner_ckpt, captioner_ckpt_name = get_best_first_checkpoint()

        with tf.Session() as sess:

            assert (captioner_ckpt is not None)
            captioner_saver.restore(sess, captioner_ckpt)
            used_ids = set()
def main(unused_argv):

    vocab, pretrained_matrix = load_glove(vocab_size=100000,
                                          embedding_size=300)
    attribute_map, attribute_embeddings_map = get_visual_attributes(
    ), np.random.normal(0, 0.1, [1000, 2048])
    with tf.Graph().as_default():

        image_id, mean_features, input_seq, target_seq, indicator = import_mscoco(
            mode="train",
            batch_size=FLAGS.batch_size,
            num_epochs=FLAGS.num_epochs,
            is_mini=FLAGS.is_mini)
        show_and_tell_cell = ShowAndTellCell(300, num_image_features=4096)
        attribute_image_captioner = AttributeImageCaptioner(
            show_and_tell_cell, vocab, pretrained_matrix, attribute_map,
            attribute_embeddings_map)
        attribute_detector = AttributeDetector(1000)
        _, top_k_attributes = attribute_detector(mean_features)
        logits, ids = attribute_image_captioner(
            top_k_attributes,
            lengths=tf.reduce_sum(indicator, axis=1),
            mean_image_features=mean_features,
            seq_inputs=input_seq)
        tf.losses.sparse_softmax_cross_entropy(target_seq,
                                               logits,
                                               weights=indicator)
        loss = tf.losses.get_total_loss()

        global_step = tf.train.get_or_create_global_step()
        optimizer = tf.train.AdamOptimizer()
        learning_step = optimizer.minimize(
            loss,
            var_list=attribute_image_captioner.variables,
            global_step=global_step)

        captioner_saver = tf.train.Saver(
            var_list=attribute_image_captioner.variables + [global_step])
        attribute_detector_saver = tf.train.Saver(
            var_list=attribute_detector.variables)
        captioner_ckpt, captioner_ckpt_name = get_show_and_tell_attribute_checkpoint(
        )
        attribute_detector_ckpt, attribute_detector_ckpt_name = get_attribute_detector_checkpoint(
        )
        with tf.Session() as sess:

            sess.run(tf.variables_initializer(optimizer.variables()))
            if captioner_ckpt is not None:
                captioner_saver.restore(sess, captioner_ckpt)
            else:
                sess.run(
                    tf.variables_initializer(
                        attribute_image_captioner.variables + [global_step]))
            if attribute_detector_ckpt is not None:
                attribute_detector_saver.restore(sess, attribute_detector_ckpt)
            else:
                sess.run(tf.variables_initializer(
                    attribute_detector.variables))
            captioner_saver.save(sess,
                                 captioner_ckpt_name,
                                 global_step=global_step)
            last_save = time.time()

            for i in itertools.count():

                time_start = time.time()
                try:
                    _target, _ids, _loss, _learning_step = sess.run(
                        [target_seq, ids, loss, learning_step])
                except:
                    break

                iteration = sess.run(global_step)

                print(
                    PRINT_STRING.format(
                        iteration, _loss,
                        list_of_ids_to_string(_ids[0, :].tolist(), vocab),
                        list_of_ids_to_string(_target[0, :].tolist(), vocab),
                        FLAGS.batch_size / (time.time() - time_start)))

                new_save = time.time()
                if new_save - last_save > 3600:  # save the model every hour
                    captioner_saver.save(sess,
                                         captioner_ckpt_name,
                                         global_step=global_step)
                    last_save = new_save

            captioner_saver.save(sess,
                                 captioner_ckpt_name,
                                 global_step=global_step)
            print("Finishing training.")
tf.logging.set_verbosity(tf.logging.INFO)
tf.flags.DEFINE_integer("batch_size", 1, "")
tf.flags.DEFINE_integer("beam_size", 3, "")
tf.flags.DEFINE_boolean("is_mini", False, "")
tf.flags.DEFINE_string("mode", "eval", "")
FLAGS = tf.flags.FLAGS


if __name__ == "__main__":
    
    vocab, pretrained_matrix = load_glove(vocab_size=100000, embedding_size=300)
    with tf.Graph().as_default():

        image_id, mean_features, input_seq, target_seq, indicator = import_mscoco(
            mode=FLAGS.mode, batch_size=FLAGS.batch_size, num_epochs=1, is_mini=FLAGS.is_mini)
        image_captioner = ImageCaptioner(ShowAndTellCell(300), vocab, pretrained_matrix, 
            trainable=False, beam_size=FLAGS.beam_size)
        logits, ids = image_captioner(mean_image_features=mean_features)
        captioner_saver = tf.train.Saver(var_list=remap_decoder_name_scope(image_captioner.variables))
        captioner_ckpt, captioner_ckpt_name = get_show_and_tell_checkpoint()

        with tf.Session() as sess:

            assert(captioner_ckpt is not None)
            captioner_saver.restore(sess, captioner_ckpt)
            used_ids = set()
            json_dump = []

            for i in itertools.count():
                time_start = time.time()
                try:
FLAGS = tf.flags.FLAGS

if __name__ == "__main__":

    vocab, pretrained_matrix = load_glove(vocab_size=100000,
                                          embedding_size=300)
    attribute_map, attribute_embeddings_map = get_visual_attributes(
    ), np.random.normal(0, 0.1, [1000, 2048])
    with tf.Graph().as_default():

        image_id, mean_features, input_seq, target_seq, indicator = import_mscoco(
            mode=FLAGS.mode,
            batch_size=FLAGS.batch_size,
            num_epochs=1,
            is_mini=FLAGS.is_mini)
        show_and_tell_cell = ShowAndTellCell(300, num_image_features=4096)
        attribute_image_captioner = AttributeImageCaptioner(
            show_and_tell_cell, vocab, pretrained_matrix, attribute_map,
            attribute_embeddings_map)
        attribute_detector = AttributeDetector(1000)
        _, top_k_attributes = attribute_detector(mean_features)
        logits, ids = attribute_image_captioner(
            top_k_attributes, mean_image_features=mean_features)

        captioner_saver = tf.train.Saver(var_list=remap_decoder_name_scope(
            attribute_image_captioner.variables))
        attribute_detector_saver = tf.train.Saver(
            var_list=attribute_detector.variables)
        captioner_ckpt, captioner_ckpt_name = get_show_and_tell_attribute_checkpoint(
        )
        attribute_detector_ckpt, attribute_detector_ckpt_name = get_attribute_detector_checkpoint(