class_docstr: Computes squared pearson correlation (r^2) metric.
class_docstr_tok: ["Computes","squared","pearson","correlation","(","r^2",")","metric","."]
code: def extract_output(
      self, accumulator: _SquaredPearsonCorrelationAccumulator
  ) -> Dict[metric_types.MetricKey, float]:
      result = float("nan")
  
      if accumulator.total_weighted_examples > 0.0:
          # See https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
          # r^2 = Cov(X, Y)^2 / VAR(X) * VAR(Y)
          #     = (E[XY] - E[X]E[Y])^2 / (E[X^2] - E[X]^2) * (E[Y^2] - E[Y]^2)
          #     = [SUM(xy) - n*mean(x)*mean(y)]^2 /
          #         [SUM(x^2) - n*mean(x)^2 * SUM(y^2) - n*mean(y)^2]
          # n = total_weighted_examples
          # SUM(x) = total_weighted_labels
          # SUM(y) = total_weighted_predictions
          # SUM(xy) = total_weighted_labels_times_predictions
          # SUM(x^2) = total_weighted_squared_labels
          # SUM(y^2) = total_weighted_squared_predictions
  
          # numerator = [SUM(xy) - n*mean(x)*mean(y)]^2
          #           = [SUM(xy) - n*SUM(x)/n*SUM(y)/n]^2
          #           = [SUM(xy) - SUM(x)*SUM(y)/n]^2
          numerator = (
              accumulator.total_weighted_labels_times_predictions
              - accumulator.total_weighted_labels
              * accumulator.total_weighted_predictions
              / accumulator.total_weighted_examples
          ) ** 2
          # denominator_y = SUM(y^2) - n*mean(y)^2
          #               = SUM(y^2) - n*(SUM(y)/n)^2
          #               = SUM(y^2) - SUM(y)^2/n
          denominator_y = (
              accumulator.total_weighted_squared_predictions
              - accumulator.total_weighted_predictions**2
              / accumulator.total_weighted_examples
          )
  
          # denominator_x = SUM(x^2) - n*mean(x)^2
          #               = SUM(x^2) - n*(SUM(x)/n)^2
          #               = SUM(x^2) - SUM(x)^2/n
          denominator_x = (
              accumulator.total_weighted_squared_labels
              - accumulator.total_weighted_labels**2
              / accumulator.total_weighted_examples
          )
          denominator = denominator_x * denominator_y
          if denominator > 0.0:
              result = numerator / denominator
  
      return {self._key: result}
  
file_path: model-analysis/tensorflow_model_analysis/metrics/squared_pearson_correlation.py
imports: from typing import Dict, Iterable, Optional
  import apache_beam
  from tensorflow_model_analysis.metrics import metric_types
  from tensorflow_model_analysis.metrics import metric_util
  from tensorflow_model_analysis.proto import config_pb2
label_desc: Use image node_id 5 for calling the _SquaredPearsonCorrelationCombiner obj's underlying member method code with example usage: obj.extract_output(accumulator) and returns: dict