예제 #1
0
  def testSummariesAreFlushedToDisk(self):
    if tf.executing_eagerly():
      # Merging tf.summary.* ops is not compatible with eager execution.
      return
    checkpoint_dir = os.path.join(self.get_temp_dir(), 'summaries_are_flushed')
    logdir = os.path.join(self.get_temp_dir(), 'summaries_are_flushed_eval')
    if tf.io.gfile.exists(logdir):
      tf.io.gfile.rmtree(logdir)

    # Train a Model to completion:
    self._train_model(checkpoint_dir, num_steps=300)

    # Create the model (which can be restored).
    inputs = tf.constant(self._inputs, dtype=tf.float32)
    logistic_classifier(inputs)

    names_to_values = {'bread': 3.4, 'cheese': 4.5, 'tomato': 2.0}

    for k in names_to_values:
      v = names_to_values[k]
      tf.compat.v1.summary.scalar(k, v)

    evaluation.evaluate_repeatedly(
        checkpoint_dir=checkpoint_dir,
        hooks=[
            evaluation.SummaryAtEndHook(log_dir=logdir),
        ],
        max_number_of_evaluations=1)

    self._verify_events(logdir, names_to_values)
예제 #2
0
def evaluate(hparams, run_eval_loop=True):
    """Runs an evaluation loop.

  Args:
    hparams: An HParams instance containing the eval hyperparameters.
    run_eval_loop: Whether to run the full eval loop. Set to False for testing.
  """
    # Fetch and generate images to run through Inception.
    with tf.name_scope('inputs'):
        real_data, _ = data_provider.provide_data('test',
                                                  hparams.num_images_generated,
                                                  shuffle=False)
        generated_data = _get_generated_data(hparams.num_images_generated)

    # Compute Frechet Inception Distance.
    if hparams.eval_frechet_inception_distance:
        fid = util.get_frechet_inception_distance(real_data, generated_data,
                                                  hparams.num_images_generated,
                                                  hparams.num_inception_images)
        tf.summary.scalar('frechet_inception_distance', fid)

    # Compute normal Inception scores.
    if hparams.eval_real_images:
        inc_score = util.get_inception_scores(real_data,
                                              hparams.num_images_generated,
                                              hparams.num_inception_images)
    else:
        inc_score = util.get_inception_scores(generated_data,
                                              hparams.num_images_generated,
                                              hparams.num_inception_images)
    tf.summary.scalar('inception_score', inc_score)

    # Create ops that write images to disk.
    image_write_ops = None
    if hparams.num_images_generated >= 100 and hparams.write_to_disk:
        reshaped_imgs = tfgan.eval.image_reshaper(generated_data[:100],
                                                  num_cols=10)
        uint8_images = data_provider.float_image_to_uint8(reshaped_imgs)
        image_write_ops = tf.io.write_file(
            '%s/%s' % (hparams.eval_dir, 'unconditional_cifar10.png'),
            tf.image.encode_png(uint8_images[0]))

    # For unit testing, use `run_eval_loop=False`.
    if not run_eval_loop: return
    evaluation.evaluate_repeatedly(
        hparams.checkpoint_dir,
        master=hparams.master,
        hooks=[
            evaluation.SummaryAtEndHook(hparams.eval_dir),
            evaluation.StopAfterNEvalsHook(1)
        ],
        eval_ops=image_write_ops,
        max_number_of_evaluations=hparams.max_number_of_evaluations)
예제 #3
0
def evaluate(hparams, run_eval_loop=True):
    """Runs an evaluation loop.

  Args:
    hparams: An HParams instance containing the eval hyperparameters.
    run_eval_loop: Whether to run the full eval loop. Set to False for testing.
  """
    with tf.compat.v1.name_scope('inputs'):
        noise, one_hot_labels = _get_generator_inputs(
            hparams.num_images_per_class, NUM_CLASSES, hparams.noise_dims)

    # Generate images.
    with tf.compat.v1.variable_scope(
            'Generator'):  # Same scope as in train job.
        images = networks.conditional_generator((noise, one_hot_labels),
                                                is_training=False)

    # Visualize images.
    reshaped_img = tfgan.eval.image_reshaper(
        images, num_cols=hparams.num_images_per_class)
    tf.compat.v1.summary.image('generated_images', reshaped_img, max_outputs=1)

    # Calculate evaluation metrics.
    tf.compat.v1.summary.scalar(
        'MNIST_Classifier_score',
        util.mnist_score(images, hparams.classifier_filename))
    tf.compat.v1.summary.scalar(
        'MNIST_Cross_entropy',
        util.mnist_cross_entropy(images, one_hot_labels,
                                 hparams.classifier_filename))

    # Write images to disk.
    image_write_ops = None
    if hparams.write_to_disk:
        image_write_ops = tf.io.write_file(
            '%s/%s' % (hparams.eval_dir, 'conditional_gan.png'),
            tf.image.encode_png(
                data_provider.float_image_to_uint8(reshaped_img[0])))

    # For unit testing, use `run_eval_loop=False`.
    if not run_eval_loop:
        return
    evaluation.evaluate_repeatedly(
        hparams.checkpoint_dir,
        hooks=[
            evaluation.SummaryAtEndHook(hparams.eval_dir),
            evaluation.StopAfterNEvalsHook(1)
        ],
        eval_ops=image_write_ops,
        max_number_of_evaluations=hparams.max_number_of_evaluations)
예제 #4
0
def evaluate(hparams, run_eval_loop=True):
    """Runs an evaluation loop.

  Args:
    hparams: An HParams instance containing the eval hyperparameters.
    run_eval_loop: Whether to run the full eval loop. Set to False for testing.
  """
    # Fetch real images.
    with tf.compat.v1.name_scope('inputs'):
        real_images, _ = data_provider.provide_data(
            'train', hparams.num_images_generated, hparams.dataset_dir)

    image_write_ops = None
    if hparams.eval_real_images:
        tf.compat.v1.summary.scalar(
            'MNIST_Classifier_score',
            util.mnist_score(real_images, hparams.classifier_filename))
    else:
        # In order for variables to load, use the same variable scope as in the
        # train job.
        with tf.compat.v1.variable_scope('Generator'):
            images = networks.unconditional_generator(tf.random.normal(
                [hparams.num_images_generated, hparams.noise_dims]),
                                                      is_training=False)
        tf.compat.v1.summary.scalar(
            'MNIST_Frechet_distance',
            util.mnist_frechet_distance(real_images, images,
                                        hparams.classifier_filename))
        tf.compat.v1.summary.scalar(
            'MNIST_Classifier_score',
            util.mnist_score(images, hparams.classifier_filename))
        if hparams.num_images_generated >= 100 and hparams.write_to_disk:
            reshaped_images = tfgan.eval.image_reshaper(images[:100, ...],
                                                        num_cols=10)
            uint8_images = data_provider.float_image_to_uint8(reshaped_images)
            image_write_ops = tf.io.write_file(
                '%s/%s' % (hparams.eval_dir, 'unconditional_gan.png'),
                tf.image.encode_png(uint8_images[0]))

    # For unit testing, use `run_eval_loop=False`.
    if not run_eval_loop:
        return
    evaluation.evaluate_repeatedly(
        hparams.checkpoint_dir,
        hooks=[
            evaluation.SummaryAtEndHook(hparams.eval_dir),
            evaluation.StopAfterNEvalsHook(1)
        ],
        eval_ops=image_write_ops,
        max_number_of_evaluations=hparams.max_number_of_evaluations)
예제 #5
0
  def testSummaryAtEndHookWithoutSummaries(self):
    logdir = os.path.join(self.get_temp_dir(),
                          'summary_at_end_hook_without_summaires')
    if tf.io.gfile.exists(logdir):
      tf.io.gfile.rmtree(logdir)

    with tf.Graph().as_default():
      # Purposefully don't add any summaries. The hook will just dump the
      # GraphDef event.
      hook = evaluation.SummaryAtEndHook(log_dir=logdir)
      hook.begin()
      with self.cached_session() as session:
        hook.after_create_session(session, None)
        hook.end(session)
    self._verify_events(logdir, {})
예제 #6
0
def evaluate(hparams, run_eval_loop=True):
    """Runs an evaluation loop.

  Args:
    hparams: An HParams instance containing the eval hyperparameters.
    run_eval_loop: Whether to run the full eval loop. Set to False for testing.
  """
    with tf.name_scope('inputs'):
        noise_args = (hparams.noise_samples, CAT_SAMPLE_POINTS,
                      CONT_SAMPLE_POINTS, hparams.unstructured_noise_dims,
                      hparams.continuous_noise_dims)
        # Use fixed noise vectors to illustrate the effect of each dimension.
        display_noise1 = util.get_eval_noise_categorical(*noise_args)
        display_noise2 = util.get_eval_noise_continuous_dim1(*noise_args)
        display_noise3 = util.get_eval_noise_continuous_dim2(*noise_args)
        _validate_noises([display_noise1, display_noise2, display_noise3])

    # Visualize the effect of each structured noise dimension on the generated
    # image.
    def generator_fn(inputs):
        return networks.infogan_generator(inputs,
                                          len(CAT_SAMPLE_POINTS),
                                          is_training=False)

    with tf.variable_scope(
            'Generator') as genscope:  # Same scope as in training.
        categorical_images = generator_fn(display_noise1)
    reshaped_categorical_img = tfgan.eval.image_reshaper(
        categorical_images, num_cols=len(CAT_SAMPLE_POINTS))
    tf.summary.image('categorical', reshaped_categorical_img, max_outputs=1)

    with tf.variable_scope(genscope, reuse=True):
        continuous1_images = generator_fn(display_noise2)
    reshaped_continuous1_img = tfgan.eval.image_reshaper(
        continuous1_images, num_cols=len(CONT_SAMPLE_POINTS))
    tf.summary.image('continuous1', reshaped_continuous1_img, max_outputs=1)

    with tf.variable_scope(genscope, reuse=True):
        continuous2_images = generator_fn(display_noise3)
    reshaped_continuous2_img = tfgan.eval.image_reshaper(
        continuous2_images, num_cols=len(CONT_SAMPLE_POINTS))
    tf.summary.image('continuous2', reshaped_continuous2_img, max_outputs=1)

    # Evaluate image quality.
    all_images = tf.concat(
        [categorical_images, continuous1_images, continuous2_images], 0)
    tf.summary.scalar('MNIST_Classifier_score', util.mnist_score(all_images))

    # Write images to disk.
    image_write_ops = []
    if hparams.write_to_disk:
        image_write_ops.append(
            _get_write_image_ops(hparams.eval_dir, 'categorical_infogan.png',
                                 reshaped_categorical_img[0]))
        image_write_ops.append(
            _get_write_image_ops(hparams.eval_dir, 'continuous1_infogan.png',
                                 reshaped_continuous1_img[0]))
        image_write_ops.append(
            _get_write_image_ops(hparams.eval_dir, 'continuous2_infogan.png',
                                 reshaped_continuous2_img[0]))

    # For unit testing, use `run_eval_loop=False`.
    if not run_eval_loop:
        return
    evaluation.evaluate_repeatedly(
        hparams.checkpoint_dir,
        hooks=[
            evaluation.SummaryAtEndHook(hparams.eval_dir),
            evaluation.StopAfterNEvalsHook(1)
        ],
        eval_ops=image_write_ops,
        max_number_of_evaluations=hparams.max_number_of_evaluations)