from tensorflow.python.framework import ops

      # - For the unweighted case, this is just the number of rows.
      # - For the weighted case, it's the sum of the weights broadcast across
      #   `average_precision` rows.
      max_var = contrib_variables.local_variable(
          array_ops.zeros([], dtype=dtypes.float64), name=max_scope)
      if weights is None:
        batch_max = math_ops.to_double(
            array_ops.size(average_precision, name='batch_max'))
      else:
        # TODO(ptucker): More efficient way to broadcast?
        broadcast_weights = math_ops.mul(
            weights, array_ops.ones_like(average_precision),
            name='broadcast_weights')
        batch_max = math_ops.reduce_sum(broadcast_weights, name='batch_max')
      max_update = state_ops.assign_add(max_var, batch_max, name='update')
    with ops.name_scope(None, 'total', (average_precision,)) as total_scope:
      total_var = contrib_variables.local_variable(
          array_ops.zeros([], dtype=dtypes.float64), name=total_scope)
      batch_total = math_ops.reduce_sum(average_precision, name='batch_total')
      total_update = state_ops.assign_add(total_var, batch_total, name='update')

    # Divide total by max to get mean, for both vars and the update ops.
    mean_average_precision = _safe_scalar_div(total_var, max_var, name='mean')
    update = _safe_scalar_div(total_update, max_update, name=scope)

    if metrics_collections:
      ops.add_to_collections(metrics_collections, mean_average_precision)
    if updates_collections:
      ops.add_to_collections(updates_collections, update)

