math_functions.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. import paddle
  15. def compute_mean_covariance(img):
  16. batch_size = img.shape[0]
  17. channel_num = img.shape[1]
  18. height = img.shape[2]
  19. width = img.shape[3]
  20. num_pixels = height * width
  21. # batch_size * channel_num * 1 * 1
  22. mu = img.mean(2, keepdim=True).mean(3, keepdim=True)
  23. # batch_size * channel_num * num_pixels
  24. img_hat = img - mu.expand_as(img)
  25. img_hat = img_hat.reshape([batch_size, channel_num, num_pixels])
  26. # batch_size * num_pixels * channel_num
  27. img_hat_transpose = img_hat.transpose([0, 2, 1])
  28. # batch_size * channel_num * channel_num
  29. covariance = paddle.bmm(img_hat, img_hat_transpose)
  30. covariance = covariance / num_pixels
  31. return mu, covariance
  32. def dice_coefficient(y_true_cls, y_pred_cls, training_mask):
  33. eps = 1e-5
  34. intersection = paddle.sum(y_true_cls * y_pred_cls * training_mask)
  35. union = paddle.sum(y_true_cls * training_mask) + paddle.sum(
  36. y_pred_cls * training_mask) + eps
  37. loss = 1. - (2 * intersection / union)
  38. return loss