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

attribution_map.py 2.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. =============================================================
  13. """
  14. import torch
  15. from typing import Type, Callable
  16. from captum.attr import Attribution
  17. from captum.attr import NoiseTunnel
  18. def with_norm(func: Callable[[torch.Tensor], torch.Tensor], x: torch.Tensor, square: bool = False):
  19. x = func(x)
  20. x = torch.norm(x.flatten(1), dim=1, p=2)
  21. if square:
  22. x = torch.pow(x, 2)
  23. return x
  24. def attribution_map(
  25. func: Callable[[torch.Tensor], torch.Tensor],
  26. attribution_type: Type,
  27. with_noise: bool,
  28. probe_data: torch.Tensor,
  29. norm_square: bool = False,
  30. **attribution_kwargs
  31. ) -> torch.Tensor:
  32. """
  33. Calculate attribution map with given attribution type(algorithm).
  34. Args:
  35. model: pytorch module
  36. attribution_type: attribution algorithm, e.g. IntegratedGradients, InputXGradient, ...
  37. with_noise: whether to add noise tunnel
  38. probe_data: input data to model
  39. device: torch.device("cuda: 0")
  40. attribution_kwargs: other kwargs for attribution method
  41. Return: attribution map
  42. """
  43. attribution: Attribution = attribution_type(lambda x: with_norm(func, x, norm_square))
  44. if with_noise:
  45. attribution = NoiseTunnel(attribution)
  46. attr_map = attribution.attribute(
  47. inputs=probe_data,
  48. target=None,
  49. **attribution_kwargs
  50. )
  51. return attr_map.detach()
  52. def attr_map_distance(map_1: torch.Tensor, map_2: torch.Tensor):
  53. if map_1.shape != map_2.shape:
  54. map_1 = torch.nn.functional.interpolate( map_1, size=map_2.shape[-2:] )
  55. #dist = torch.dist(map_1.flatten(1), map_2.flatten(1), p=2).mean()
  56. dist = 1 - torch.cosine_similarity(map_1.flatten(1), map_2.flatten(1)).mean()
  57. return dist.item()
  58. def attr_map_similarity(map_1: torch.Tensor, map_2: torch.Tensor):
  59. assert(map_1.shape == map_2.shape)
  60. dist = torch.cosine_similarity(map_1.flatten(1), map_2.flatten(1)).mean()
  61. return dist.item()
  62. if __name__ == "__main__":
  63. import captum
  64. def ff(x):
  65. return x ** 2
  66. m = attribution_map(
  67. ff,
  68. captum.attr.InputXGradient,
  69. with_noise=False,
  70. probe_data=torch.tensor([[1, 2, 3, 4]], dtype=torch.float, requires_grad=True),
  71. norm_square=True
  72. )
  73. print(m)

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能

Contributors (1)