Exemple #1
0
def main(unused_argv):

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

        image_id, spatial_features, input_seq, target_seq, indicator = (
            import_mscoco(mode="train",
                          batch_size=BATCH_SIZE,
                          num_epochs=100,
                          is_mini=True))
        visual_sentinel_cell = VisualSentinelCell(300)
        image_captioner = ImageCaptioner(visual_sentinel_cell, vocab,
                                         pretrained_matrix)
        logits, ids = image_captioner(lengths=tf.reduce_sum(indicator, axis=1),
                                      spatial_image_features=spatial_features,
                                      seq_inputs=input_seq)
        tf.losses.sparse_softmax_cross_entropy(target_seq,
                                               logits,
                                               weights=indicator)
        loss = tf.losses.get_total_loss()
        learning_step = tf.train.GradientDescentOptimizer(1.0).minimize(
            loss, var_list=image_captioner.variables)

        captioner_saver = tf.train.Saver(var_list=image_captioner.variables)
        captioner_ckpt, captioner_ckpt_name = get_visual_sentinel_checkpoint()
        with tf.Session() as sess:
            sess.run(tf.variables_initializer(image_captioner.variables))
            if captioner_ckpt is not None:
                captioner_saver.restore(sess, captioner_ckpt)
            captioner_saver.save(sess, captioner_ckpt_name)
            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
                print(
                    PRINT_STRING.format(
                        i, _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)
                    last_save = new_save

            captioner_saver.save(sess, captioner_ckpt_name)
            print("Finishing training.")
Exemple #2
0
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, spatial_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(ShowAttendAndTellCell(300),
                                         vocab,
                                         pretrained_matrix,
                                         trainable=False,
                                         beam_size=FLAGS.beam_size)
        logits, ids = image_captioner(spatial_image_features=spatial_features)
        captioner_saver = tf.train.Saver(
            var_list=remap_decoder_name_scope(image_captioner.variables))
        captioner_ckpt, captioner_ckpt_name = get_show_attend_and_tell_checkpoint(
        )

        with tf.Session() as sess:
Exemple #3
0
def main(unused_argv):

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

        image_id, spatial_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)
        image_captioner = ImageCaptioner(SpatialAttentionCell(300), vocab,
                                         pretrained_matrix)
        logits, ids = image_captioner(lengths=tf.reduce_sum(indicator, axis=1),
                                      spatial_image_features=spatial_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=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_spatial_attention_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(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:
                    _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:
                    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.")
from detailed_captioning.utils import get_train_annotations_file
from detailed_captioning.inputs.spatial_image_features_only import import_mscoco

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, spatial_features, input_seq, target_seq, indicator = (
            import_mscoco(mode="train",
                          batch_size=BATCH_SIZE,
                          num_epochs=1,
                          is_mini=True))
        image_captioner = ImageCaptioner(ShowAttendAndTellCell(300),
                                         vocab,
                                         pretrained_matrix,
                                         trainable=False,
                                         beam_size=BEAM_SIZE)
        logits, ids = image_captioner(spatial_image_features=spatial_features)
        captioner_saver = tf.train.Saver(
            var_list=remap_decoder_name_scope(image_captioner.variables))
        captioner_ckpt, captioner_ckpt_name = get_show_attend_and_tell_checkpoint(
        )

        with tf.Session() as sess:

            assert (captioner_ckpt is not None)
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, spatial_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_attend_and_tell_cell = ShowAttendAndTellCell(300, num_image_features=2048)
        attribute_image_captioner = AttributeImageCaptioner(
            show_attend_and_tell_cell, vocab, pretrained_matrix,
            attribute_map, attribute_embeddings_map)
        attribute_detector = AttributeDetector(1000)
        _, top_k_attributes = attribute_detector(tf.reduce_mean(spatial_features, [1, 2]))
        logits, ids = attribute_image_captioner(top_k_attributes,
            lengths=tf.reduce_sum(indicator, axis=1), 
            spatial_image_features=spatial_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_attend_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.")