コード例 #1
0
 def _create_tpu_estimator_spec(
     self, features, mode, logits, labels=None,
     optimizer=None, trainable_variables=None, train_op_fn=None,
     update_ops=None, regularization_losses=None,):
   return model_fn._TPUEstimatorSpec(
       mode=ModeKeys.EVAL,
       loss=constant_op.constant(0.0, dtype=dtypes.float32))
コード例 #2
0
    def _create_tpu_estimator_spec(self,
                                   features,
                                   mode,
                                   logits,
                                   labels=None,
                                   optimizer=None,
                                   trainable_variables=None,
                                   train_op_fn=None,
                                   update_ops=None,
                                   regularization_losses=None):
        """Returns an `model_fn._TPUEstimatorSpec`.

    Args:
      features: Input `dict` of `Tensor` or `SparseTensor` objects.
      mode: Estimator's `ModeKeys`.
      logits: logits `Tensor` with shape `[D0, D1, ... DN, n_classes]`.
        For many applications, the shape is `[batch_size, n_classes]`.
      labels: Labels with shape matching `logits`. Can be multi-hot `Tensor`
        with shape `[D0, D1, ... DN, n_classes]` or `SparseTensor` with
        `dense_shape` `[D0, D1, ... DN, ?]`. `labels` is required argument when
        `mode` equals `TRAIN` or `EVAL`.
      optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the
         loss in TRAIN mode. Namely, sets
        `train_op = optimizer.get_updates(loss, trainable_variables)`,
        which updates variables to minimize `loss`.able_variables)`,
        which updates variables to minimize `loss`.
      trainable_variables: A list or tuple of `Variable` objects to update to
        minimize `loss`. In Tensorflow 1.x, by default these are the list of
        variables collected in the graph under the key
        `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have
        collections and GraphKeys, trainable_variables need to be passed
        explicitly here.
      train_op_fn: Function that takes a scalar loss `Tensor` and returns
        `train_op`. Used if `optimizer` is `None`.
      update_ops: A list or tuple of update ops to be run at training time. For
        example, layers such as BatchNormalization create mean and variance
        update ops that need to be run at training time. In Tensorflow 1.x,
        these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x
        doesn't have collections, update_ops need to be passed explicitly here.
      regularization_losses: A list of additional scalar losses to be added to
        the training loss, such as regularization losses. These losses are
        usually expressed as a batch average, so for best results users need to
        set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to
        avoid scaling errors.
    Returns:
      `model_fn._TPUEstimatorSpec`.
    Raises:
      ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN
        mode, or if both are set.
    """
        with ops.name_scope(self._name, 'head'):
            # Predict.
            pred_keys = prediction_keys.PredictionKeys
            predictions = self.predictions(logits)
            if mode == ModeKeys.PREDICT:
                probabilities = predictions[pred_keys.PROBABILITIES]
                classifier_output = base_head.classification_output(
                    scores=probabilities,
                    n_classes=self._n_classes,
                    label_vocabulary=self._label_vocabulary)
                return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
                    mode=ModeKeys.PREDICT,
                    predictions=predictions,
                    export_outputs={
                        base_head.DEFAULT_SERVING_KEY: classifier_output,
                        base_head.CLASSIFY_SERVING_KEY: classifier_output,
                        base_head.PREDICT_SERVING_KEY: (
                            export_output.PredictOutput(predictions))
                    })

            regularized_training_loss = self.loss(
                logits=logits,
                labels=labels,
                features=features,
                mode=mode,
                regularization_losses=regularization_losses)
            # Eval.
            if mode == ModeKeys.EVAL:
                eval_metrics = self.metrics(
                    regularization_losses=regularization_losses)
                return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
                    mode=ModeKeys.EVAL,
                    predictions=predictions,
                    loss=regularized_training_loss,
                    eval_metrics=base_head.create_eval_metrics_tuple(
                        self.update_metrics, {
                            'eval_metrics': eval_metrics,
                            'features': features,
                            'logits': logits,
                            'labels': labels,
                            'regularization_losses': regularization_losses
                        }))
            # Train.
            train_op = base_head.create_estimator_spec_train_op(
                head_name=self._name,
                optimizer=optimizer,
                train_op_fn=train_op_fn,
                update_ops=update_ops,
                trainable_variables=trainable_variables,
                regularized_training_loss=regularized_training_loss,
                loss_reduction=self._loss_reduction)
        # Create summary.
        base_head.create_estimator_spec_summary(
            regularized_training_loss=regularized_training_loss,
            regularization_losses=regularization_losses,
            summary_key_fn=self._summary_key)
        return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
            mode=ModeKeys.TRAIN,
            predictions=predictions,
            loss=regularized_training_loss,
            train_op=train_op)
コード例 #3
0
    def _create_tpu_estimator_spec(self,
                                   features,
                                   mode,
                                   logits,
                                   labels=None,
                                   optimizer=None,
                                   trainable_variables=None,
                                   train_op_fn=None,
                                   update_ops=None,
                                   regularization_losses=None):
        """See superclass for description."""

        with tf.compat.v1.name_scope(self._name, 'head'):
            # Predict.
            pred_keys = prediction_keys.PredictionKeys
            predictions = self.predictions(logits)
            if mode == ModeKeys.PREDICT:
                probabilities = predictions[pred_keys.PROBABILITIES]
                logistic = predictions[pred_keys.LOGISTIC]
                classifier_output = base_head.classification_output(
                    scores=probabilities,
                    n_classes=2,
                    label_vocabulary=self._label_vocabulary)
                return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
                    mode=ModeKeys.PREDICT,
                    predictions=predictions,
                    export_outputs={
                        base_head.DEFAULT_SERVING_KEY: classifier_output,
                        base_head.CLASSIFY_SERVING_KEY: classifier_output,
                        base_head.REGRESS_SERVING_KEY:
                            export_output.RegressionOutput(value=logistic),
                        base_head.PREDICT_SERVING_KEY:
                            export_output.PredictOutput(predictions)
                    })
            regularized_training_loss = self.loss(
                logits=logits,
                labels=labels,
                features=features,
                mode=mode,
                regularization_losses=regularization_losses)
            scalar_loss = tf.reduce_mean(regularized_training_loss)
            # Eval.
            if mode == ModeKeys.EVAL:
                eval_metrics = self.metrics(
                    regularization_losses=regularization_losses)
                return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
                    mode=ModeKeys.EVAL,
                    predictions=predictions,
                    loss=scalar_loss,
                    eval_metrics=base_head.create_eval_metrics_tuple(
                        self.update_metrics, {
                            'eval_metrics': eval_metrics,
                            'features': features,
                            'logits': logits,
                            'labels': labels,
                            'regularization_losses': regularization_losses
                        }))
            # Train.
            train_op = base_head.create_estimator_spec_train_op(
                head_name=self._name,
                optimizer=optimizer,
                train_op_fn=train_op_fn,
                update_ops=update_ops,
                trainable_variables=trainable_variables,
                regularized_training_loss=regularized_training_loss,
                loss_reduction=self._loss_reduction)
        # Create summary.
        base_head.create_estimator_spec_summary(
            regularized_training_loss=scalar_loss,
            regularization_losses=regularization_losses,
            summary_key_fn=self._summary_key)
        return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
            mode=ModeKeys.TRAIN,
            predictions=predictions,
            loss=scalar_loss,
            train_op=train_op)
コード例 #4
0
    def _create_tpu_estimator_spec(self,
                                   features,
                                   mode,
                                   logits,
                                   labels=None,
                                   optimizer=None,
                                   train_op_fn=None,
                                   regularization_losses=None):
        """Returns an `model_fn._TPUEstimatorSpec`.

    Args:
      features: Input `dict` of `Tensor` or `SparseTensor` objects.
      mode: Estimator's `ModeKeys`.
      logits: logits `Tensor` with shape `[D0, D1, ... DN, n_classes]`.
        For many applications, the shape is `[batch_size, n_classes]`.
      labels: Labels with shape matching `logits`. Can be multi-hot `Tensor`
        with shape `[D0, D1, ... DN, n_classes]` or `SparseTensor` with
        `dense_shape` `[D0, D1, ... DN, ?]`. `labels` is required argument when
        `mode` equals `TRAIN` or `EVAL`.
      optimizer: `Optimizer` instance to optimize the loss in TRAIN mode.
        Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which
        updates variables and increments `global_step`.
      train_op_fn: Function that takes a scalar loss `Tensor` and returns
        `train_op`. Used if `optimizer` is `None`.
      regularization_losses: A list of additional scalar losses to be added to
        the training loss, such as regularization losses. These losses are
        usually expressed as a batch average, so for best results users need to
        set `loss_reduction=SUM_OVER_BATCH_SIZE` or
        `loss_reduction=SUM_OVER_NONZERO_WEIGHTS` when creating the head to
        avoid scaling errors.
    Returns:
      `model_fn._TPUEstimatorSpec`.
    Raises:
      ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN
        mode, or if both are set.
    """
        with ops.name_scope(self._name, 'head'):
            # Predict.
            pred_keys = prediction_keys.PredictionKeys
            predictions = self.predictions(logits)
            if mode == model_fn.ModeKeys.PREDICT:
                probabilities = predictions[pred_keys.PROBABILITIES]
                classifier_output = base_head.classification_output(
                    scores=probabilities,
                    n_classes=self._n_classes,
                    label_vocabulary=self._label_vocabulary)
                return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
                    mode=model_fn.ModeKeys.PREDICT,
                    predictions=predictions,
                    export_outputs={
                        base_head.DEFAULT_SERVING_KEY: classifier_output,
                        base_head.CLASSIFY_SERVING_KEY: classifier_output,
                        base_head.PREDICT_SERVING_KEY: (
                            export_output.PredictOutput(predictions))
                    })

            regularized_training_loss = self.loss(
                logits=logits,
                labels=labels,
                features=features,
                mode=mode,
                regularization_losses=regularization_losses)
            # Eval.
            if mode == model_fn.ModeKeys.EVAL:
                eval_metrics = self.metrics(
                    regularization_losses=regularization_losses)
                return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
                    mode=model_fn.ModeKeys.EVAL,
                    predictions=predictions,
                    loss=regularized_training_loss,
                    eval_metrics=base_head.create_eval_metrics_tuple(
                        self.update_metrics, {
                            'eval_metrics': eval_metrics,
                            'features': features,
                            'logits': logits,
                            'labels': labels,
                            'regularization_losses': regularization_losses
                        }))
            # Train.
            train_op = base_head.create_estimator_spec_train_op(
                self._name, optimizer, train_op_fn, regularized_training_loss)
        # Create summary.
        base_head.create_estimator_spec_summary(regularized_training_loss,
                                                regularization_losses,
                                                self._summary_key)
        return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
            mode=model_fn.ModeKeys.TRAIN,
            predictions=predictions,
            loss=regularized_training_loss,
            train_op=train_op)
コード例 #5
0
    def _create_tpu_estimator_spec(self,
                                   features,
                                   mode,
                                   logits,
                                   labels=None,
                                   optimizer=None,
                                   trainable_variables=None,
                                   train_op_fn=None,
                                   update_ops=None,
                                   regularization_losses=None):
        """Returns an `model_fn._TPUEstimatorSpec`.

    Args:
      features: Input `dict` of `Tensor` or `SparseTensor` objects.
      mode: Estimator's `ModeKeys`.
      logits: estimated obs. value, [batch, time_len, num_obs] tensor.
      labels: ground truth observation, feature dict with obs. and interv. codes
        as keys, values tensor with shape [batch_size, context_window_size].
      optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the
        loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss,
        trainable_variables)`, which updates variables to minimize `loss`.
      trainable_variables: A list or tuple of `Variable` objects to update to
        minimize `loss`. In Tensorflow 1.x, by default these are the list of
        variables collected in the graph under the key
        `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have
        collections and GraphKeys, trainable_variables need to be passed
        explicitly here.
      train_op_fn: Function that takes a scalar loss `Tensor` and returns
        `train_op`. Used if `optimizer` is `None`.
      update_ops: A list or tuple of update ops to be run at training time. For
        example, layers such as BatchNormalization create mean and variance
        update ops that need to be run at training time. In Tensorflow 1.x,
        these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x
        doesn't have collections, update_ops need to be passed explicitly here.
      regularization_losses: A list of additional scalar losses to be added to
        the training loss, such as regularization losses. These losses are
        usually expressed as a batch average, so for best results users need to
        set `loss_reduction=SUM_OVER_BATCH_SIZE` or
        `loss_reduction=SUM_OVER_NONZERO_WEIGHTS` when creating the head to
        avoid scaling errors.

    Returns:
      `model_fn._TPUEstimatorSpec`.
    Raises:
      ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN
        mode, or if both are set.
    """
        with ops.name_scope(self._name, 'sequence_head'):
            # Predict.
            predictions = self.predictions(logits)
            if mode == model_fn.ModeKeys.PREDICT:
                return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
                    mode=model_fn.ModeKeys.PREDICT,
                    predictions=predictions,
                    export_outputs={
                        base_head.DEFAULT_SERVING_KEY:
                            export_output.PredictOutput(predictions),
                        base_head.PREDICT_SERVING_KEY: (
                            export_output.PredictOutput(predictions))
                    })

            regularized_training_loss = self.loss(
                logits=logits,
                labels=labels,
                features=features,
                mode=mode,
                regularization_losses=regularization_losses)
            # Eval.
            if mode == model_fn.ModeKeys.EVAL:
                eval_metrics = self.metrics(
                    regularization_losses=regularization_losses)
                return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
                    mode=model_fn.ModeKeys.EVAL,
                    predictions=predictions,
                    loss=regularized_training_loss,
                    eval_metrics=base_head.create_eval_metrics_tuple(
                        self.update_metrics, {
                            'eval_metrics': eval_metrics,
                            'features': features,
                            'logits': logits,
                            'labels': labels,
                            'regularization_losses': regularization_losses
                        }))
            # Train.
            train_op = base_head.create_estimator_spec_train_op(
                self._name,
                optimizer=optimizer,
                trainable_variables=trainable_variables,
                train_op_fn=train_op_fn,
                update_ops=update_ops,
                regularized_training_loss=regularized_training_loss)
        # Create summary.
        base_head.create_estimator_spec_summary(regularized_training_loss,
                                                regularization_losses,
                                                self._summary_key)
        return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
            mode=model_fn.ModeKeys.TRAIN,
            predictions=predictions,
            loss=regularized_training_loss,
            train_op=train_op)
コード例 #6
0
    def _create_tpu_estimator_spec(self,
                                   features,
                                   mode,
                                   logits,
                                   labels=None,
                                   optimizer=None,
                                   train_op_fn=None,
                                   regularization_losses=None):
        """Returns an `EstimatorSpec`.

    Args:
      features: Input `dict` mapping string feature names to `Tensor` or
        `SparseTensor` objects containing the values for that feature in a
        minibatch. Often to be used to fetch example-weight tensor.
      mode: Estimator's `ModeKeys`.
      logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`.
        For many applications, the shape is `[batch_size, logits_dimension]`.
      labels: Labels `Tensor` with shape matching `logits`, namely
        `[D0, D1, ... DN, logits_dimension]`. When `logits_dimension=1`, shape
        `[D0, D1, ... DN]` is also supported. `labels` is a required argument
        when `mode` equals `TRAIN` or `EVAL`.
      optimizer: `Optimizer` instance to optimize the loss in TRAIN mode.
        Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which
        updates variables and increments `global_step`.
      train_op_fn: Function that takes a scalar loss `Tensor` and returns
        `train_op`. Used if `optimizer` is `None`.
      regularization_losses: A list of additional scalar losses to be added to
        the training loss, such as regularization losses. These losses are
        usually expressed as a batch average, so for best results users need to
        set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to
        avoid scaling errors.

    Returns:
      A `model_fn._TPUEstimatorSpec` instance.

    Raises:
      ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN
        mode, or if both are set.
    """
        with ops.name_scope(self._name, 'head'):
            # Predict.
            predictions = self.predictions(logits)
            if mode == model_fn.ModeKeys.PREDICT:
                keys = prediction_keys.PredictionKeys
                regression_output = export_output.RegressionOutput(
                    value=predictions[keys.PREDICTIONS])
                return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
                    mode=model_fn.ModeKeys.PREDICT,
                    predictions=predictions,
                    export_outputs={
                        base_head.DEFAULT_SERVING_KEY: regression_output,
                        base_head.REGRESS_SERVING_KEY: regression_output,
                        base_head.PREDICT_SERVING_KEY: export_output.PredictOutput(
                            predictions)
                    })
            regularized_training_loss = self.loss(
                logits=logits,
                labels=labels,
                features=features,
                mode=mode,
                regularization_losses=regularization_losses)
            # Eval.
            if mode == model_fn.ModeKeys.EVAL:
                eval_metrics = self.metrics(
                    regularization_losses=regularization_losses)
                return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
                    mode=model_fn.ModeKeys.EVAL,
                    predictions=predictions,
                    loss=regularized_training_loss,
                    eval_metrics=base_head.create_eval_metrics_tuple(
                        self.update_metrics, {
                            'eval_metrics': eval_metrics,
                            'features': features,
                            'logits': logits,
                            'labels': labels,
                            'regularization_losses': regularization_losses
                        }))
            # Train.
            train_op = base_head.create_estimator_spec_train_op(
                head_name=self._name,
                optimizer=optimizer,
                train_op_fn=train_op_fn,
                update_ops=self._update_ops,
                regularized_training_loss=regularized_training_loss)
        # Create summary.
        base_head.create_estimator_spec_summary(
            regularized_training_loss=regularized_training_loss,
            regularization_losses=regularization_losses,
            summary_key_fn=self._summary_key)
        return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
            mode=model_fn.ModeKeys.TRAIN,
            predictions=predictions,
            loss=regularized_training_loss,
            train_op=train_op)
コード例 #7
0
ファイル: head.py プロジェクト: yueyedeai/estimator
    def _create_tpu_estimator_spec(self,
                                   features,
                                   mode,
                                   logits,
                                   labels=None,
                                   optimizer=None,
                                   train_op_fn=None,
                                   regularization_losses=None):
        """Returns an `model_fn._TPUEstimatorSpec`.

    Args:
      features: Input `dict` of `Tensor` or `SparseTensor` objects.
      mode: Estimator's `ModeKeys`.
      logits: logits `Tensor` with shape `[D0, D1, ... DN, n_classes]`.
        For many applications, the shape is `[batch_size, n_classes]`.
      labels: Labels with shape matching `logits`. Can be multi-hot `Tensor`
        with shape `[D0, D1, ... DN, n_classes]` or `SparseTensor` with
        `dense_shape` `[D0, D1, ... DN, ?]`. `labels` is required argument when
        `mode` equals `TRAIN` or `EVAL`.
      optimizer: `Optimizer` instance to optimize the loss in TRAIN mode.
        Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which
        updates variables and increments `global_step`.
      train_op_fn: Function that takes a scalar loss `Tensor` and returns
        `train_op`. Used if `optimizer` is `None`.
      regularization_losses: A list of additional scalar losses to be added to
        the training loss, such as regularization losses. These losses are
        usually expressed as a batch average, so for best results users need to
        set `loss_reduction=SUM_OVER_BATCH_SIZE` or
        `loss_reduction=SUM_OVER_NONZERO_WEIGHTS` when creating the head to
        avoid scaling errors.
    Returns:
      `model_fn._TPUEstimatorSpec`.
    Raises:
      ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN
        mode, or if both are set.
    """
        with ops.name_scope(self._name, 'head'):
            logits = head_lib._check_logits_final_dim(logits,
                                                      self.logits_dimension)  # pylint:disable=protected-access

            # Predict.
            pred_keys = prediction_keys.PredictionKeys
            with ops.name_scope(None, 'predictions', (logits, )):
                probabilities = math_ops.sigmoid(logits,
                                                 name=pred_keys.PROBABILITIES)
                predictions = {
                    pred_keys.LOGITS: logits,
                    pred_keys.PROBABILITIES: probabilities,
                }
            if mode == model_fn.ModeKeys.PREDICT:
                classifier_output = head_lib._classification_output(  # pylint:disable=protected-access
                    scores=probabilities,
                    n_classes=self._n_classes,
                    label_vocabulary=self._label_vocabulary)
                return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
                    mode=model_fn.ModeKeys.PREDICT,
                    predictions=predictions,
                    export_outputs={
                        _DEFAULT_SERVING_KEY: classifier_output,
                        head_lib._CLASSIFY_SERVING_KEY: classifier_output,  # pylint:disable=protected-access
                        head_lib._PREDICT_SERVING_KEY: (  # pylint:disable=protected-access
                            export_output.PredictOutput(predictions))
                    })

            (training_loss, unreduced_loss, weights,
             processed_labels) = self.create_loss(features=features,
                                                  mode=mode,
                                                  logits=logits,
                                                  labels=labels)
            if regularization_losses:
                regularization_loss = math_ops.add_n(regularization_losses)
                regularized_training_loss = math_ops.add_n(
                    [training_loss, regularization_loss])
            else:
                regularization_loss = None
                regularized_training_loss = training_loss

            # Eval.
            if mode == model_fn.ModeKeys.EVAL:
                return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
                    mode=model_fn.ModeKeys.EVAL,
                    predictions=predictions,
                    loss=regularized_training_loss,
                    eval_metrics=head_lib._create_eval_metrics_tuple(  # pylint:disable=protected-access
                        self._eval_metric_ops, {
                            'labels': processed_labels,
                            'probabilities': probabilities,
                            'weights': weights,
                            'unreduced_loss': unreduced_loss,
                            'regularization_loss': regularization_loss,
                        }))

            # Train.
            if optimizer is not None:
                if train_op_fn is not None:
                    raise ValueError(
                        'train_op_fn and optimizer cannot both be set.')
                train_op = optimizer.minimize(
                    regularized_training_loss,
                    global_step=training_util.get_global_step())
            elif train_op_fn is not None:
                train_op = train_op_fn(regularized_training_loss)
            else:
                raise ValueError(
                    'train_op_fn and optimizer cannot both be None.')
            train_op = head_lib._append_update_ops(train_op)  # pylint:disable=protected-access
            # Only summarize mean_loss for SUM reduction to preserve backwards
            # compatibility. Otherwise skip it to avoid unnecessary computation.
            if self._loss_reduction == losses.Reduction.SUM:
                example_weight_sum = math_ops.reduce_sum(
                    weights * array_ops.ones_like(unreduced_loss))
                mean_loss = training_loss / example_weight_sum
            else:
                mean_loss = None
        with ops.name_scope(''):
            keys = metric_keys.MetricKeys
            summary.scalar(
                head_lib._summary_key(self._name, keys.LOSS),  # pylint:disable=protected-access
                regularized_training_loss)
            if mean_loss is not None:
                summary.scalar(
                    head_lib._summary_key(self._name, keys.LOSS_MEAN),  # pylint:disable=protected-access
                    mean_loss)
            if regularization_loss is not None:
                summary.scalar(
                    head_lib._summary_key(self._name,
                                          keys.LOSS_REGULARIZATION),  # pylint:disable=protected-access
                    regularization_loss)
        return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
            mode=model_fn.ModeKeys.TRAIN,
            predictions=predictions,
            loss=regularized_training_loss,
            train_op=train_op)
コード例 #8
0
ファイル: head.py プロジェクト: vanessa920/aws-workshop
    def _create_tpu_estimator_spec(self,
                                   features,
                                   mode,
                                   logits,
                                   labels=None,
                                   optimizer=None,
                                   train_op_fn=None,
                                   regularization_losses=None):
        """Returns a `model_fn._TPUEstimatorSpec`.

    Args:
      features: Input `dict` of `Tensor` or `SparseTensor` objects.
      mode: Estimator's `ModeKeys`.
      logits: logits `Tensor` with shape `[D0, D1, ... DN, logits_dimension]`.
        For many applications, the shape is `[batch_size, logits_dimension]`.
      labels: Labels integer or string `Tensor` with shape matching `logits`,
        namely `[D0, D1, ... DN, 1]` or `[D0, D1, ... DN]`. `labels` is required
        argument when `mode` equals `TRAIN` or `EVAL`.
      optimizer: `Optimizer` instance to optimize the loss in TRAIN mode.
        Namely, sets `train_op = optimizer.minimize(loss, global_step)`, which
        updates variables and increments `global_step`.
      train_op_fn: Function that takes a scalar loss `Tensor` and returns
        `train_op`. Used if `optimizer` is `None`.
      regularization_losses: A list of additional scalar losses to be added to
        the training loss, such as regularization losses. These losses are
        usually expressed as a batch average, so for best results users need to
        set `loss_reduction=SUM_OVER_BATCH_SIZE` when creating the head to avoid
        scaling errors.

    Returns:
      A `model_fn._TPUEstimatorSpec` instance.
    Raises:
      ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN
        mode, or if both are set.
    """
        with tf.compat.v1.name_scope(self._name, 'head'):
            logits = _check_logits_final_dim(logits, self.logits_dimension)

            # Predict.
            pred_keys = prediction_keys.PredictionKeys
            with tf.compat.v1.name_scope(None, 'predictions', (logits, )):
                all_class_ids = _all_class_ids(logits, self._n_classes)
                all_classes = _all_classes(
                    logits,
                    self._n_classes,
                    label_vocabulary=self._label_vocabulary)
                # class_ids's shape is [D0, D1, ... DN].
                class_ids = tf.compat.v1.math.argmax(logits,
                                                     axis=-1,
                                                     name=pred_keys.CLASS_IDS)
                class_ids = tf.compat.v1.expand_dims(class_ids, axis=-1)
                if self._label_vocabulary:
                    table = lookup_ops.index_to_string_table_from_tensor(
                        vocabulary_list=self._label_vocabulary,
                        name='class_string_lookup')
                    classes = table.lookup(class_ids)
                else:
                    classes = tf.strings.as_string(class_ids,
                                                   name='str_classes')

                probabilities = tf.compat.v1.nn.softmax(
                    logits, name=pred_keys.PROBABILITIES)
                predictions = {
                    pred_keys.LOGITS: logits,
                    pred_keys.PROBABILITIES: probabilities,
                    # Expand to [batch_size, 1]
                    pred_keys.CLASS_IDS: class_ids,
                    pred_keys.CLASSES: classes,
                    pred_keys.ALL_CLASS_IDS: all_class_ids,
                    pred_keys.ALL_CLASSES: all_classes,
                }
            if mode == ModeKeys.PREDICT:
                classifier_output = _classification_output(
                    scores=probabilities,
                    n_classes=self._n_classes,
                    label_vocabulary=self._label_vocabulary)
                return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
                    mode=ModeKeys.PREDICT,
                    predictions=predictions,
                    export_outputs={
                        _DEFAULT_SERVING_KEY: classifier_output,
                        _CLASSIFY_SERVING_KEY: classifier_output,
                        _PREDICT_SERVING_KEY: export_output.PredictOutput(predictions)
                    })

            training_loss, unreduced_loss, weights, label_ids = self.create_loss(
                features=features, mode=mode, logits=logits, labels=labels)
            if regularization_losses:
                regularization_loss = tf.math.add_n(regularization_losses)
                regularized_training_loss = tf.math.add_n(
                    [training_loss, regularization_loss])
            else:
                regularization_loss = None
                regularized_training_loss = training_loss

            if self._loss_reduction == tf.compat.v1.losses.Reduction.NONE:
                scalar_loss = tf.reduce_mean(regularized_training_loss)
            else:
                scalar_loss = regularized_training_loss

            # Eval.
            if mode == ModeKeys.EVAL:
                return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
                    mode=ModeKeys.EVAL,
                    predictions=predictions,
                    loss=scalar_loss,
                    eval_metrics=_create_eval_metrics_tuple(
                        self._eval_metric_ops, {
                            'labels': label_ids,
                            'class_ids': class_ids,
                            'weights': weights,
                            'unreduced_loss': unreduced_loss,
                            'regularization_loss': regularization_loss
                        }))

            # Train.
            if optimizer is not None:
                if train_op_fn is not None:
                    raise ValueError(
                        'train_op_fn and optimizer cannot both be set.')
                train_op = optimizer.minimize(
                    regularized_training_loss,
                    global_step=tf.compat.v1.train.get_global_step())
            elif train_op_fn is not None:
                train_op = train_op_fn(regularized_training_loss)
            else:
                raise ValueError(
                    'train_op_fn and optimizer cannot both be None.')
            train_op = _append_update_ops(train_op)
            # Only summarize mean_loss for SUM reduction to preserve backwards
            # compatibility. Otherwise skip it to avoid unnecessary computation.
            if self._loss_reduction == tf.compat.v1.losses.Reduction.SUM:
                example_weight_sum = tf.math.reduce_sum(
                    weights * tf.compat.v1.ones_like(unreduced_loss))
                mean_loss = training_loss / example_weight_sum
            else:
                mean_loss = None
        with tf.compat.v1.name_scope(''):
            keys = metric_keys.MetricKeys
            tf.compat.v1.summary.scalar(_summary_key(self._name, keys.LOSS),
                                        scalar_loss)
            if mean_loss is not None:
                tf.compat.v1.summary.scalar(
                    _summary_key(self._name, keys.LOSS_MEAN), mean_loss)
            if regularization_loss is not None:
                tf.compat.v1.summary.scalar(
                    _summary_key(self._name, keys.LOSS_REGULARIZATION),
                    regularization_loss)
        return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
            mode=ModeKeys.TRAIN,
            predictions=predictions,
            loss=scalar_loss,
            train_op=train_op)
コード例 #9
0
  def _create_tpu_estimator_spec(self,
                                 features,
                                 mode,
                                 logits,
                                 labels=None,
                                 optimizer=None,
                                 trainable_variables=None,
                                 train_op_fn=None,
                                 update_ops=None,
                                 regularization_losses=None):
    """Returns an `model_fn._TPUEstimatorSpec`.

    Args:
      features: Input `dict` of `Tensor` or `SparseTensor` objects.
      mode: Estimator's `ModeKeys`.
      logits: for single event, indepdent event, logits is a tensor of shape
        [batch_size, 1], for correlated event, a dict with event_name as key,
        value as tensor of shape [batch_size, 1].
      labels: dict keyed by 'event_name' and 'event_name.time_of_event' with
        value as tensors of shape [batch_size] or [batch_size, 1]. For
        correlated events, labels for all events are provided. Otherwise, only
        the event associated with this head is provided.
        Here is one example label:
        {u'respiration_failure.time_to_event':
         <tf.Tensor 'Cast:0' shape=(32,) dtype=float32>,
         u'respiration_failure':
        <tf.Tensor 'Batch/batch:110' shape=(32,) dtype=int64>} `labels` is
          required argument when `mode` equals `TRAIN` or `EVAL`.
      optimizer: An `tf.keras.optimizers.Optimizer` instance to optimize the
        loss in TRAIN mode. Namely, sets `train_op = optimizer.get_updates(loss,
        trainable_variables)`, which updates variables to minimize `loss`.
      trainable_variables: A list or tuple of `Variable` objects to update to
        minimize `loss`. In Tensorflow 1.x, by default these are the list of
        variables collected in the graph under the key
        `GraphKeys.TRAINABLE_VARIABLES`. As Tensorflow 2.x doesn't have
        collections and GraphKeys, trainable_variables need to be passed
        explicitly here.
      train_op_fn: Function that takes a scalar loss `Tensor` and returns
        `train_op`. Used if `optimizer` is `None`.
      update_ops: A list or tuple of update ops to be run at training time. For
        example, layers such as BatchNormalization create mean and variance
        update ops that need to be run at training time. In Tensorflow 1.x,
        these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x
        doesn't have collections, update_ops need to be passed explicitly here.
      regularization_losses: A list of additional scalar losses to be added to
        the training loss, such as regularization losses. These losses are
        usually expressed as a batch average, so for best results users need to
        set `loss_reduction=SUM_OVER_BATCH_SIZE` or
        `loss_reduction=SUM_OVER_NONZERO_WEIGHTS` when creating the head to
        avoid scaling errors.

    Returns:
      `model_fn._TPUEstimatorSpec`.
    Raises:
      ValueError: If both `train_op_fn` and `optimizer` are `None` in TRAIN
        mode, or if both are set.
    """
    tf.logging.info(mode)

    with ops.name_scope(self._name, 'survival_head'):
      # Predict.
      predictions = self.predictions(logits)
      # hazard_rates = self.hazard_rates(logits)

      if mode == model_fn.ModeKeys.PREDICT:
        # survival_output = SurvivalOutput(value=hazard_rates)

        return model_fn._TPUEstimatorSpec(  # pylint:disable=protected-access
            mode=model_fn.ModeKeys.PREDICT,
            predictions=predictions,
            export_outputs={
                base_head.DEFAULT_SERVING_KEY: (
                    export_output.PredictOutput(predictions)),
                base_head.PREDICT_SERVING_KEY: (
                    export_output.PredictOutput(predictions))
            })

      regularized_training_loss = self.loss(
          logits=logits,
          labels=labels,
          features=features,
          mode=mode,
          regularization_losses=regularization_losses)
      # Eval.
      if mode == model_fn.ModeKeys.EVAL:
        eval_metrics = self.metrics(regularization_losses=regularization_losses)
        return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
            mode=model_fn.ModeKeys.EVAL,
            predictions=predictions,
            loss=regularized_training_loss,
            eval_metrics=base_head.create_eval_metrics_tuple(
                self.update_metrics, {
                    'eval_metrics': eval_metrics,
                    'features': features,
                    'logits': logits,
                    'labels': labels,
                    'regularization_losses': regularization_losses
                }))
      # Train.
      train_op = base_head.create_estimator_spec_train_op(
          self._name,
          optimizer=optimizer,
          trainable_variables=trainable_variables,
          train_op_fn=train_op_fn,
          update_ops=update_ops,
          regularized_training_loss=regularized_training_loss)
    # Create summary.
    base_head.create_estimator_spec_summary(
        regularized_training_loss, regularization_losses, self._summary_key)
    return model_fn._TPUEstimatorSpec(  # pylint: disable=protected-access
        mode=model_fn.ModeKeys.TRAIN,
        predictions=predictions,
        loss=regularized_training_loss,
        train_op=train_op)