Create some `fake_pred` with the generator from `input` and compare them to `real_pred` in `self.loss_funcD`.
422466
def critic(self, real_pred, input):
        ""
        fake = self.gan_model.generator(input.requires_grad_(False)).requires_grad_(True)
        fake_pred = self.gan_model.critic(fake)
        return self.loss_funcC(real_pred, fake_pred)
349891
def generator(self, z, is_training, out_shape):
    """"""
    hparams = self.hparams
    height, width, c_dim = out_shape
    batch_size = hparams.batch_size
    with tf.variable_scope(
        "generator",
        initializer=tf.random_normal_initializer(stddev=0.02)):
      net = tf.layers.dense(z, 1024, name="g_fc1")
      net = tf.layers.batch_normalization(net, training=is_training,
                                          momentum=0.999, name="g_bn1")
      net = lrelu(net)
      net = tf.layers.dense(net, 128 * (height // 4) * (width // 4),
                            name="g_fc2")
      net = tf.layers.batch_normalization(net, training=is_training,
                                          momentum=0.999, name="g_bn2")
      net = lrelu(net)
      net = tf.reshape(net, [batch_size, height // 4, width // 4, 128])
      net = deconv2d(net, [batch_size, height // 2, width // 2, 64],
                     4, 4, 2, 2, name="g_dc3")
      net = tf.layers.batch_normalization(net, training=is_training,
                                          momentum=0.999, name="g_bn3")
      net = lrelu(net)
      net = deconv2d(net, [batch_size, height, width, c_dim],
                     4, 4, 2, 2, name="g_dc4")
      out = tf.nn.sigmoid(net)
      return common_layers.convert_real_to_rgb(out)
619579
function generatorToPromise(fn) {
    if (typeof fn !== 'function') {
        throw Error('fn is not a function');
    }
    if (!isGenerator(fn)) {
        // assume it's Promise-based
        return fn;
    }
    return co.wrap(fn);
}
1058509
def create_dummy_vars():
  """"""
  var_names = set([v.name for v in tf.global_variables()])
  if "losses_avg/problem_0/total_loss:0" in var_names:
    return
  with tf.variable_scope("losses_avg"):
    with tf.variable_scope("problem_0"):
      for var_name in ["total", "extra", "training"]:
        tf.get_variable(
            "%s_loss" % var_name, initializer=100.0, trainable=False)
  with tf.variable_scope("train_stats"):
    tf.get_variable("problem_0_steps", initializer=0, trainable=False)
737377
def input(input_id, name, value_class=NumberValue):
        """"""
        def _init():
            return value_class(
                name,
                input_id=input_id,
                is_input=True,
                index=-1
            )
        def _decorator(cls):
            setattr(cls, input_id, _init())
            return cls
        return _decorator
903631
def _gdecorator(generate_func):
        
        def dostuff(self):
            for func in self._pregenerate_functions:
                self.current_params = func(self.current_params)
            res = generate_func(self) # pylint:disable=not-callable
            return self._postgenerate(res)
        return dostuff
33109
def _makes_clone(_func, *args, **kw):
    
    self = args[0]._clone()
    _func(self, *args[1:], **kw)
    return self
622920
def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str:
        """"""
        return f"({self.visit(node.elt)} " \
               f"{' '.join(self.visit(gen) for gen in node.generators)})"
94200
def from_learners(cls, learn_gen:Learner, learn_crit:Learner, switcher:Callback=None,
                      weights_gen:Tuple[float,float]=None, **learn_kwargs):
        ""
        losses = gan_loss_from_func(learn_gen.loss_func, learn_crit.loss_func, weights_gen=weights_gen)
        return cls(learn_gen.data, learn_gen.model, learn_crit.model, *losses, switcher=switcher, **learn_kwargs)
87044
def is_transform_generator(fn):
    """"""
    try:
        if six.PY2:
            fn.func_dict['is_transform_generator'] = True
        else:
            # py3
            return fn.__dict__.get('is_transform_generator', False)
    except AttributeError:
        return False
1339862
def make_preprocessing_fn(output_dir, features, keep_target):
  
  def preprocessing_fn(inputs):
    """Preprocessing function.

    Args:
      inputs: dictionary of raw input tensors

    Returns:
      A dictionary of transformed tensors
    """
    stats = json.loads(
      file_io.read_file_to_string(
          os.path.join(output_dir, STATS_FILE)).decode())

    result = {}
    for name, transform in six.iteritems(features):
      transform_name = transform['transform']
      source_column = transform['source_column']

      if transform_name == KEY_TRANSFORM:
        transform_name = 'identity'
      elif transform_name == TARGET_TRANSFORM:
        if not keep_target:
          continue
        if file_io.file_exists(os.path.join(output_dir, VOCAB_ANALYSIS_FILE % source_column)):
          transform_name = 'one_hot'
        else:
          transform_name = 'identity'

      if transform_name == 'identity':
        result[name] = inputs[source_column]
      elif transform_name == 'scale':
        result[name] = _scale(
            inputs[name],
            min_x_value=stats['column_stats'][source_column]['min'],
            max_x_value=stats['column_stats'][source_column]['max'],
            output_min=transform.get('value', 1) * (-1),
            output_max=transform.get('value', 1))
      elif transform_name in [ONE_HOT_TRANSFORM, EMBEDDING_TRANSFROM, MULTI_HOT_TRANSFORM,
                              TFIDF_TRANSFORM, BOW_TRANSFORM]:
        vocab, ex_count = read_vocab_file(
            os.path.join(output_dir, VOCAB_ANALYSIS_FILE % source_column))

        if transform_name == TFIDF_TRANSFORM:
          separator = transform.get('separator', ' ')
          tokens = tf.string_split(inputs[source_column], separator)
          ids = _string_to_int(tokens, vocab)
          weights = _tfidf(
              x=ids,
              reduced_term_freq=ex_count + [0],
              vocab_size=len(vocab) + 1,
              corpus_size=stats['num_examples'])

          result[name + '_ids'] = ids
          result[name + '_weights'] = weights
        elif transform_name == BOW_TRANSFORM:
          separator = transform.get('separator', ' ')
          tokens = tf.string_split(inputs[source_column], separator)
          ids = _string_to_int(tokens, vocab)
          weights = _bag_of_words(x=ids)

          result[name + '_ids'] = ids
          result[name + '_weights'] = weights
        elif transform_name == MULTI_HOT_TRANSFORM:
          separator = transform.get('separator', ' ')
          tokens = tf.string_split(inputs[source_column], separator)
          result[name] = _string_to_int(tokens, vocab)
        else:
          # ONE_HOT_TRANSFORM: making a dense vector is done at training
          # EMBEDDING_TRANSFROM: embedding vectors have to be done at training
          result[name] = _string_to_int(inputs[source_column], vocab)
      elif transform_name == IMAGE_TRANSFORM:
        make_image_to_vec_fn = _make_image_to_vec_tito(
            name, checkpoint=transform.get('checkpoint', None))
        result[name] = make_image_to_vec_fn(inputs[source_column])
      else:
        raise ValueError('unknown transform %s' % transform_name)
    return result

  return preprocessing_fn
404143
def extract_input(pipe_def=None, pipe_generator=None):
    """"""
    if pipe_def:
        pyinput = gen_input(pipe_def)
    elif pipe_generator:
        pyinput = pipe_generator(Context(describe_input=True))
    else:
        raise Exception('Must supply at least one kwarg!')

    return sorted(list(pyinput))
537855
def generator(self, random, args):
        """"""
        if self.duplicates:
            max_count = [self.capacity // item[0] for item in self.items]
            return [random.randint(0, m) for m in max_count]
        else:
            return [random.choice([0, 1]) for _ in range(len(self.items))]
972265
def _real_re_compile(self, *args, **kwargs):
        """"""
        try:
            return re.compile(*args, **kwargs)
        except re.error as e:
            # raise ValueError instead of re.error as this gives a
            # cleaner message to the user.
            raise ValueError('"' + args[0] + '" ' + str(e))
859888
def do_fake( formatter, *args, **kwargs ):
    
    return Faker.getGenerator().format( formatter, *args, **kwargs )
914999
def from_dict(cls, d):
        
        defect = MontyDecoder().process_decoded( d["defect"])
        uncorrected_energy = d["uncorrected_energy"]
        corrections = d.get("corrections", None)
        parameters = d.get("parameters", None)
        entry_id = d.get("entry_id", None)

        return cls(defect, uncorrected_energy, corrections=corrections,
                   parameters=parameters, entry_id=entry_id)
25996
def learn_generated(self, feature_generator):
        '''
        

        '''
        if isinstance(feature_generator, FeatureGenerator) is False:
            raise TypeError("The type of `feature_generator` must be `FeatureGenerator`.")

        # Pre-learning.
        if self.__pre_learning_epochs > 0:
            self.__encoder_decoder_controller.learn_generated(feature_generator)

        learning_rate = self.__learning_rate

        encoder_best_params_list = []
        decoder_best_params_list = []
        re_encoder_best_params_list = []
        try:
            self.__change_inferencing_mode(False)
            self.__memory_tuple_list = []
            eary_stop_flag = False
            loss_list = []
            min_loss = None
            epoch = 0
            for batch_observed_arr, batch_target_arr, test_batch_observed_arr, test_batch_target_arr in feature_generator.generate():
                epoch += 1
                if ((epoch + 1) % self.__attenuate_epoch == 0):
                    learning_rate = learning_rate / self.__learning_attenuate_rate

                try:
                    _ = self.inference(batch_observed_arr)
                    delta_arr, _, loss = self.compute_retrospective_loss()

                    remember_flag = False
                    if len(loss_list) > 0:
                        if abs(loss - (sum(loss_list)/len(loss_list))) > self.__tld:
                            remember_flag = True

                    if remember_flag is True:
                        self.__remember_best_params(
                            encoder_best_params_list,
                            decoder_best_params_list,
                            re_encoder_best_params_list
                        )
                        # Re-try.
                        _ = self.inference(batch_observed_arr)
                        delta_arr, _, loss = self.compute_retrospective_loss()

                    re_encoder_grads_list, decoder_grads_list, encoder_delta_arr, encoder_grads_list = self.back_propagation(delta_arr)
                    self.optimize(
                        re_encoder_grads_list,
                        decoder_grads_list, 
                        encoder_grads_list, 
                        learning_rate, 
                        epoch
                    )

                    if min_loss is None or min_loss > loss:
                        min_loss = loss
                        
                        encoder_best_params_list = [
                            self.__encoder_decoder_controller.encoder.graph.weights_lstm_hidden_arr,
                            self.__encoder_decoder_controller.encoder.graph.weights_lstm_observed_arr,
                            self.__encoder_decoder_controller.encoder.graph.lstm_bias_arr
                        ]
                        decoder_best_params_list = [
                            self.__encoder_decoder_controller.decoder.graph.weights_lstm_hidden_arr,
                            self.__encoder_decoder_controller.decoder.graph.weights_lstm_observed_arr,
                            self.__encoder_decoder_controller.decoder.graph.lstm_bias_arr
                        ]
                        re_encoder_best_params_list = [
                            self.__retrospective_encoder.graph.weights_lstm_hidden_arr,
                            self.__retrospective_encoder.graph.weights_lstm_observed_arr,
                            self.__retrospective_encoder.graph.lstm_bias_arr
                        ]
                        self.__logger.debug("Best params are updated.")

                    self.__encoder_decoder_controller.encoder.graph.hidden_activity_arr = np.array([])
                    self.__encoder_decoder_controller.encoder.graph.cec_activity_arr = np.array([])
                    self.__encoder_decoder_controller.decoder.graph.hidden_activity_arr = np.array([])
                    self.__encoder_decoder_controller.decoder.graph.cec_activity_arr = np.array([])
                    self.__retrospective_encoder.graph.hidden_activity_arr = np.array([])
                    self.__retrospective_encoder.graph.cec_activity_arr = np.array([])

                except FloatingPointError:
                    if epoch > int(self.__epochs * 0.7):
                        self.__logger.debug(
                            "Underflow occurred when the parameters are being updated. Because of early stopping, this error is catched and the parameter is not updated."
                        )
                        eary_stop_flag = True
                        break
                    else:
                        self.__logger.debug(
                            "Underflow occurred when the parameters are being updated."
                        )
                        raise

                if self.__test_size_rate > 0:
                    self.__change_inferencing_mode(True)
                    _ = self.inference(test_batch_observed_arr)
                    _, _, test_loss = self.compute_retrospective_loss()

                    remember_flag = False
                    if len(loss_list) > 0:
                        if abs(test_loss - (sum(loss_list)/len(loss_list))) > self.__tld:
                            remember_flag = True

                    if remember_flag is True:
                        self.__remember_best_params(
                            encoder_best_params_list, 
                            decoder_best_params_list,
                            re_encoder_best_params_list
                        )
                        # Re-try.
                        _ = self.inference(test_batch_observed_arr)
                        _, _, test_loss = self.compute_retrospective_loss()

                    self.__change_inferencing_mode(False)
                    self.__verificate_retrospective_loss(loss, test_loss)

                self.__encoder_decoder_controller.encoder.graph.hidden_activity_arr = np.array([])
                self.__encoder_decoder_controller.encoder.graph.cec_activity_arr = np.array([])
                self.__encoder_decoder_controller.decoder.graph.hidden_activity_arr = np.array([])
                self.__encoder_decoder_controller.decoder.graph.cec_activity_arr = np.array([])

                if epoch > 1 and abs(loss - loss_list[-1]) < self.__tol:
                    eary_stop_flag = True
                    break
                loss_list.append(loss)

        except KeyboardInterrupt:
            self.__logger.debug("Interrupt.")

        if eary_stop_flag is True:
            self.__logger.debug("Early stopping.")
            eary_stop_flag = False
        
        self.__remember_best_params(
            encoder_best_params_list, 
            decoder_best_params_list,
            re_encoder_best_params_list
        )
        self.__change_inferencing_mode(True)
        self.__logger.debug("end. ")