Compute a ratio from an observation and a prediction.
171761
def compute(cls, observation, prediction, key=None):
        """"""
        assert isinstance(observation, (dict, float, int, pq.Quantity))
        assert isinstance(prediction, (dict, float, int, pq.Quantity))

        obs, pred = cls.extract_means_or_values(observation, prediction,
                                                key=key)
        value = pred / obs
        value = utils.assert_dimensionless(value)
        return RatioScore(value)
307513
def compute(self):
        """"""
        self._compute_window_size()
        smooth = []
        residual = []

        x, y = self.x, self.y

        # step through x and y data with a window window_size wide.
        self._update_values_in_window()
        self._update_mean_in_window()
        self._update_variance_in_window()
        for i, (xi, yi) in enumerate(zip(x, y)):
            if ((i - self._neighbors_on_each_side) > 0.0 and
                    (i + self._neighbors_on_each_side) < len(x)):
                self._advance_window()
            smooth_here = self._compute_smooth_during_construction(xi)
            residual_here = self._compute_cross_validated_residual_here(xi, yi, smooth_here)
            smooth.append(smooth_here)
            residual.append(residual_here)

        self._store_unsorted_results(smooth, residual)
852397
def ss_reg(self):
        """"""
        return np.sum(np.square(self.predicted - self.ybar), axis=0)
124655
def calculate_priority(ratios=None, **kwargs):
    ""
    if not ratios:
        ratios = PRIORITY_FEATURE_WEIGHTS
    scores = [DEFAULT_PRIORITY_SCORE]
    for key, value in kwargs.items():
        if key not in PRIORITY_FEATURE_WEIGHTS:
            raise KeyError('The following keyword arguments are supported: '
                           '{keys}'.format(keys=PRIORITY_FEATURES))
        if value is True:
            scores.append(PRIORITY_FEATURE_WEIGHTS[key])
    return float(sum(scores)) / len(scores)
98077
def _ge_from_lt(self, other):
    """"""
    op_result = self.__lt__(other)
    if op_result is NotImplemented:
        return NotImplemented
    return not op_result
285064
def computeOutput(self):

    """"""

    # todo: This operation can be sped up by:
    #  1.)  Pre-allocating space for the currentOutput
    #  2.)  Making predictedState and activeState of type 'float32' up front
    #  3.)  Using logical_or(self.predictedState['t'], self.activeState['t'],
    #          self.currentOutput)
    #
    self.currentOutput = \
        logical_or(self.predictedState['t'], self.activeState['t'])

    return self.currentOutput.reshape(-1).astype('float32')
901993
def _compute(self):
        """"""
        self.min_ = self._min or 0
        self.max_ = self._max or 0
        if self.max_ - self.min_ == 0:
            self.min_ -= 1
            self.max_ += 1

        self._box.set_polar_box(0, 1, self.min_, self.max_)
1130269
def predict(self, X, raw_score=False, num_iteration=None,
                pred_leaf=False, pred_contrib=False, **kwargs):
        """"""
        result = self.predict_proba(X, raw_score, num_iteration,
                                    pred_leaf, pred_contrib, **kwargs)
        if raw_score or pred_leaf or pred_contrib:
            return result
        else:
            class_index = np.argmax(result, axis=1)
            return self._le.inverse_transform(class_index)
82691
def _parallel_predict(estimators, estimators_features, X, n_classes, combination, estimators_weight):
    """"""
    n_samples = X.shape[0]
    pred = np.zeros((n_samples, n_classes))
    n_estimators = len(estimators)

    for estimator, features, weight in zip(estimators, estimators_features, estimators_weight):
        # Resort to voting
        predictions = estimator.predict(X[:, features])

        for i in range(n_samples):
            if combination == 'weighted_voting':
                pred[i, int(predictions[i])] += 1 * weight
            else:
                pred[i, int(predictions[i])] += 1

    return pred
334080
def cause_ratio(self, mechanism, purview):
        """"""
        return self._ratio(Direction.CAUSE, mechanism, purview)
402390
def predict(self, x):
        
        if isinstance(x, RDD):
            return x.map(lambda v: self.predict(v))

        x = _convert_to_vector(x)
        margin = self.weights.dot(x) + self.intercept
        if self._threshold is None:
            return margin
        else:
            return 1 if margin > self._threshold else 0
916507
def predict(self, x):
        
        y = np.dot(self.w, x)
        return y
695453
def estimator_spec_predict(self, features, use_tpu=False):
    """"""
    decode_hparams = self._decode_hparams
    top_beams = decode_hparams.beam_size if decode_hparams.return_beams else 1
    infer_out = self.infer(
        features,
        beam_size=decode_hparams.beam_size,
        top_beams=top_beams,
        alpha=decode_hparams.alpha,
        decode_length=decode_hparams.extra_length,
        use_tpu=use_tpu)
    if isinstance(infer_out, dict):
      outputs = infer_out["outputs"]
      scores = infer_out["scores"]
    else:
      outputs = infer_out
      scores = None

    inputs = features.get("inputs")
    if inputs is None:
      inputs = features["targets"]

    predictions = {
        "outputs": outputs,
        "scores": scores,
        "inputs": inputs,
        "targets": features.get("infer_targets"),
    }

    # Pass through remaining features
    for name, feature in features.items():
      if name not in list(predictions.keys()) + ["infer_targets"]:
        if name == "decode_loop_step":
          continue
        if not feature.shape.as_list():
          # All features must have a batch dimension
          batch_size = common_layers.shape_list(outputs)[0]
          feature = tf.tile(tf.expand_dims(feature, 0), [batch_size])
        predictions[name] = feature

    _del_dict_non_tensors(predictions)

    export_out = {"outputs": predictions["outputs"]}
    if "scores" in predictions:
      export_out["scores"] = predictions["scores"]

    # Necessary to rejoin examples in the correct order with the Cloud ML Engine
    # batch prediction API.
    if "batch_prediction_key" in predictions:
      export_out["batch_prediction_key"] = predictions["batch_prediction_key"]

    export_outputs = {
        tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:
            tf.estimator.export.PredictOutput(export_out)
    }
    if use_tpu:
      # Note: important to call this before remove_summaries()
      if self.hparams.tpu_enable_host_call:
        host_call = self.create_eval_host_call()
      else:
        host_call = None

      remove_summaries()

      return tf.contrib.tpu.TPUEstimatorSpec(
          tf.estimator.ModeKeys.PREDICT,
          predictions=predictions,
          host_call=host_call,
          export_outputs=export_outputs)
    else:
      return tf.estimator.EstimatorSpec(
          tf.estimator.ModeKeys.PREDICT,
          predictions=predictions,
          export_outputs=export_outputs)
105509
def compute_update_ratio(weight_tensors, before_weights, after_weights):
    """"""
    deltas = [after - before for after,
              before in zip(after_weights, before_weights)]
    delta_norms = [np.linalg.norm(d.ravel()) for d in deltas]
    weight_norms = [np.linalg.norm(w.ravel()) for w in before_weights]
    ratios = [d / w for d, w in zip(delta_norms, weight_norms)]
    all_summaries = [
        tf.Summary.Value(tag='update_ratios/' +
                         tensor.name, simple_value=ratio)
        for tensor, ratio in zip(weight_tensors, ratios)]
    return tf.Summary(value=all_summaries)
524265
def _compute_curve(labels, predictions, num_thresholds, weights=None):
    """"""

    if weights is None:
        weights = 1.0

    # Compute bins of true positives and false positives.
    bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1)))
    float_labels = labels.astype(np.float)
    histogram_range = (0, num_thresholds - 1)
    tp_buckets, _ = np.histogram(
        bucket_indices,
        bins=num_thresholds,
        range=histogram_range,
        weights=float_labels * weights)
    fp_buckets, _ = np.histogram(
        bucket_indices,
        bins=num_thresholds,
        range=histogram_range,
        weights=(1.0 - float_labels) * weights)

    # Obtain the reverse cumulative sum.
    tp = np.cumsum(tp_buckets[::-1])[::-1]
    fp = np.cumsum(fp_buckets[::-1])[::-1]
    tn = fp[0] - fp
    fn = tp[0] - tp
    precision = tp / np.maximum(_MINIMUM_COUNT, tp + fp)
    recall = tp / np.maximum(_MINIMUM_COUNT, tp + fn)
    return np.stack((tp, fp, tn, fn, precision, recall))
822115
def compute(cls, observation, prediction):
        """"""
        assert isinstance(observation, dict)
        assert isinstance(prediction, dict)
        p_mean = prediction['mean']  # Use the prediction's mean.
        p_std = prediction['std']
        o_mean = observation['mean']
        o_std = observation['std']
        try:  # Try to pool taking samples sizes into account.
            p_n = prediction['n']
            o_n = observation['n']
            s = (((p_n-1)*(p_std**2) + (o_n-1)*(o_std**2))/(p_n+o_n-2))**0.5
        except KeyError:  # If sample sizes are not available.
            s = (p_std**2 + o_std**2)**0.5
        value = (p_mean - o_mean)/s
        value = utils.assert_dimensionless(value)
        return CohenDScore(value)
356031
def estimate_row_means(
            self,
            X,
            observed,
            column_means,
            column_scales):
        

        n_rows, n_cols = X.shape

        column_means = np.asarray(column_means)
        if len(column_means) != n_cols:
            raise ValueError("Expected length %d but got shape %s" % (
                n_cols, column_means.shape))
        X = X - column_means.reshape((1, n_cols))
        column_weights = 1.0 / column_scales
        X *= column_weights.reshape((1, n_cols))
        row_means = np.zeros(n_rows, dtype=X.dtype)
        row_residual_sums = np.nansum(X, axis=1)
        for i in range(n_rows):
            row_mask = observed[i, :]
            sum_weights = column_weights[row_mask].sum()
            row_means[i] = row_residual_sums[i] / sum_weights
        return row_means