You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

147 lines
6.0 KiB

6 years ago
  1. # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Tensorflow ops to calibrate class predictions and background class."""
  16. import tensorflow as tf
  17. from object_detection.utils import shape_utils
  18. def _find_interval_containing_new_value(x, new_value):
  19. """Find the index of x (ascending-ordered) after which new_value occurs."""
  20. new_value_shape = shape_utils.combined_static_and_dynamic_shape(new_value)[0]
  21. x_shape = shape_utils.combined_static_and_dynamic_shape(x)[0]
  22. compare = tf.cast(tf.reshape(new_value, shape=(new_value_shape, 1)) >=
  23. tf.reshape(x, shape=(1, x_shape)),
  24. dtype=tf.int32)
  25. diff = compare[:, 1:] - compare[:, :-1]
  26. interval_idx = tf.argmin(diff, axis=1)
  27. return interval_idx
  28. def _tf_linear_interp1d(x_to_interpolate, fn_x, fn_y):
  29. """Tensorflow implementation of 1d linear interpolation.
  30. Args:
  31. x_to_interpolate: tf.float32 Tensor of shape (num_examples,) over which 1d
  32. linear interpolation is performed.
  33. fn_x: Monotonically-increasing, non-repeating tf.float32 Tensor of shape
  34. (length,) used as the domain to approximate a function.
  35. fn_y: tf.float32 Tensor of shape (length,) used as the range to approximate
  36. a function.
  37. Returns:
  38. tf.float32 Tensor of shape (num_examples,)
  39. """
  40. x_pad = tf.concat([fn_x[:1] - 1, fn_x, fn_x[-1:] + 1], axis=0)
  41. y_pad = tf.concat([fn_y[:1], fn_y, fn_y[-1:]], axis=0)
  42. interval_idx = _find_interval_containing_new_value(x_pad, x_to_interpolate)
  43. # Interpolate
  44. alpha = (
  45. (x_to_interpolate - tf.gather(x_pad, interval_idx)) /
  46. (tf.gather(x_pad, interval_idx + 1) - tf.gather(x_pad, interval_idx)))
  47. interpolation = ((1 - alpha) * tf.gather(y_pad, interval_idx) +
  48. alpha * tf.gather(y_pad, interval_idx + 1))
  49. return interpolation
  50. def _function_approximation_proto_to_tf_tensors(x_y_pairs_message):
  51. """Extracts (x,y) pairs from a XYPairs message.
  52. Args:
  53. x_y_pairs_message: calibration_pb2..XYPairs proto
  54. Returns:
  55. tf_x: tf.float32 tensor of shape (number_xy_pairs,) for function domain.
  56. tf_y: tf.float32 tensor of shape (number_xy_pairs,) for function range.
  57. """
  58. tf_x = tf.convert_to_tensor([x_y_pair.x
  59. for x_y_pair
  60. in x_y_pairs_message.x_y_pair],
  61. dtype=tf.float32)
  62. tf_y = tf.convert_to_tensor([x_y_pair.y
  63. for x_y_pair
  64. in x_y_pairs_message.x_y_pair],
  65. dtype=tf.float32)
  66. return tf_x, tf_y
  67. def build(calibration_config):
  68. """Returns a function that calibrates Tensorflow model scores.
  69. All returned functions are expected to apply positive monotonic
  70. transformations to inputs (i.e. score ordering is strictly preserved or
  71. adjacent scores are mapped to the same score, but an input of lower value
  72. should never be exceed an input of higher value after transformation). For
  73. class-agnostic calibration, positive monotonicity should hold across all
  74. scores. In class-specific cases, positive monotonicity should hold within each
  75. class.
  76. Args:
  77. calibration_config: calibration_pb2.CalibrationConfig proto.
  78. Returns:
  79. Function that that accepts class_predictions_with_background and calibrates
  80. the output based on calibration_config's parameters.
  81. Raises:
  82. ValueError: No calibration builder defined for "Oneof" in
  83. calibration_config.
  84. """
  85. # Linear Interpolation (usually used as a result of calibration via
  86. # isotonic regression).
  87. if calibration_config.WhichOneof('calibrator') == 'function_approximation':
  88. def calibration_fn(class_predictions_with_background):
  89. """Calibrate predictions via 1-d linear interpolation.
  90. Predictions scores are linearly interpolated based on class-agnostic
  91. function approximations. Note that the 0-indexed background class may
  92. also transformed.
  93. Args:
  94. class_predictions_with_background: tf.float32 tensor of shape
  95. [batch_size, num_anchors, num_classes + 1] containing scores on the
  96. interval [0,1]. This is usually produced by a sigmoid or softmax layer
  97. and the result of calling the `predict` method of a detection model.
  98. Returns:
  99. tf.float32 tensor of shape [batch_size, num_anchors, num_classes] if
  100. background class is not present (else shape is
  101. [batch_size, num_anchors, num_classes + 1]) on the interval [0, 1].
  102. """
  103. # Flattening Tensors and then reshaping at the end.
  104. flat_class_predictions_with_background = tf.reshape(
  105. class_predictions_with_background, shape=[-1])
  106. fn_x, fn_y = _function_approximation_proto_to_tf_tensors(
  107. calibration_config.function_approximation.x_y_pairs)
  108. updated_scores = _tf_linear_interp1d(
  109. flat_class_predictions_with_background, fn_x, fn_y)
  110. # Un-flatten the scores
  111. original_detections_shape = shape_utils.combined_static_and_dynamic_shape(
  112. class_predictions_with_background)
  113. calibrated_class_predictions_with_background = tf.reshape(
  114. updated_scores,
  115. shape=original_detections_shape,
  116. name='calibrate_scores')
  117. return calibrated_class_predictions_with_background
  118. # TODO(zbeaver): Add sigmoid calibration and per-class isotonic regression.
  119. else:
  120. raise ValueError('No calibration builder defined for "Oneof" in '
  121. 'calibration_config.')
  122. return calibration_fn