├── data └── images │ ├── zebra_elephant1.jpg │ ├── zebra_elephant2.jpg │ ├── zebra_elephant3.jpg │ ├── zebra_elephant4.jpg │ └── zebra_elephant5.jpg ├── gpu-docker └── Dockerfile ├── utils ├── helper.py └── visualizations.py ├── README.md └── LICENSE /data/images/zebra_elephant1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uchidalab/softmaxgradient-lrp/HEAD/data/images/zebra_elephant1.jpg -------------------------------------------------------------------------------- /data/images/zebra_elephant2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uchidalab/softmaxgradient-lrp/HEAD/data/images/zebra_elephant2.jpg -------------------------------------------------------------------------------- /data/images/zebra_elephant3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uchidalab/softmaxgradient-lrp/HEAD/data/images/zebra_elephant3.jpg -------------------------------------------------------------------------------- /data/images/zebra_elephant4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uchidalab/softmaxgradient-lrp/HEAD/data/images/zebra_elephant4.jpg -------------------------------------------------------------------------------- /data/images/zebra_elephant5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uchidalab/softmaxgradient-lrp/HEAD/data/images/zebra_elephant5.jpg -------------------------------------------------------------------------------- /gpu-docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM tensorflow/tensorflow:1.10.0-gpu-py3 2 | LABEL maintainer="Brian Kenji Iwana" 3 | 4 | ENV PYTHONPATH "${PYTHONPATH}:/work" 5 | ENV DEBIAN_FRONTEND=noninteractive 6 | RUN apt-get update && apt-get install -y git \ 7 | && apt-get install -y python3-tk 8 | 9 | RUN pip install git+https://github.com/albermax/innvestigate@1.0.8.3 10 | RUN pip install scikit-image==0.15.0 11 | RUN pip install tqdm 12 | -------------------------------------------------------------------------------- /utils/helper.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | def heatmap(heatmap, cmap="seismic", interpolation="none", colorbar=False, M=None): 5 | if M is None: 6 | M = np.abs(heatmap).max() 7 | if M == 0: 8 | M = 1 9 | plt.imshow(heatmap, cmap=cmap, vmax=M, vmin=-M, interpolation=interpolation) 10 | plt.xticks([]) 11 | plt.yticks([]) 12 | plt.tight_layout() 13 | if colorbar: 14 | plt.colorbar() 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Softmax Gradient Layer-wise Relevance Propagation (SGLRP) 2 | 3 | This is a Keras implementation of the the paper Brian Kenji Iwana, Ryouhei Kuroki, and Seiichi Uchida, *Explaining Convolutional Neural Networks using Softmax Gradient Layer-wise Relevance Propagation,* ICCV Workshops, 2019. [arXiv](https://arxiv.org/abs/1908.04351) 4 | 5 | ## Abstract 6 | 7 | Convolutional Neural Networks (CNN) have become state-of-the-art in the field of image classification. However, not everything is understood about their inner representations. This paper tackles the interpretability and explainability of the predictions of CNNs for multi-class classification problems. Specifically, we propose a novel visualization method of pixel-wise input attribution called Softmax-Gradient Layer-wise Relevance Propagation (SGLRP). The proposed model is a class discriminate extension to Deep Taylor Decomposition (DTD) using the gradient of softmax to back propagate the relevance of the output probability to the input image. Through qualitative and quantitative analysis, we demonstrate that SGLRP can successfully localize and attribute the regions on input images which contribute to a target object's classification. We show that the proposed method excels at discriminating the target objects class from the other possible objects in the images. We confirm that SGLRP performs better than existing Layer-wise Relevance Propagation (LRP) based methods and can help in the understanding of the decision process of CNNs. 8 | 9 | ## News 10 | 11 | - 2020/01/26: SGLRPSeqA, SGLRPSeqB - New implentation of SGLRP based on Sequential LRP. White paper incoming, for now if you use SGLRPSeqA or SGLRPSeqB, cite the paper below. Warning, experimental, sometimes it doesn't work as expected. 12 | - 2019/12/20: GPU docker support 13 | - 2019/11/02: ICCV Workshop on Explainable AI 14 | - 2019/08/06: ArXiv paper posted 15 | - 2019/07/23: Initial commit 16 | 17 | ## Details 18 | 19 | SGLRP is a class contrastive extension of LRP. The general idea is that a relevance *penalty* is propagated through the network to create the relevance heatmaps. 20 | 21 | Specifically, we use the gradient of softmax as the initial relevance signal for LRP. Or, 22 | ![sglrpdef](https://latex.codecogs.com/gif.latex?R_%7Bn%7D%5E%7B%28L%29%7D%20%3D%20%5Cfrac%7B%5Cpartial%20%5Chat%7By%7D_t%7D%7B%5Cpartial%20z_n%7D%20%3D%20%5Cleft%5C%7B%5Cbegin%7Bmatrix%7D%20%26%20%5Chat%7By%7D_t%281-%5Chat%7By%7D_t%29%20%26%20n%3Dt%20%5C%5C%20%26%20-%20%5Chat%7By%7D_t%5Chat%7By%7D_n%20%26%20%5Cmathrm%7Botherwise%7D%2C%20%5Cend%7Bmatrix%7D%5Cright.) 23 | 24 | where *t* is the target class and *n* is the other classes. 25 | 26 | ## Requires 27 | 28 | This code was developed in Python 3.5.2. and requires Tensorflow 1.10.0 29 | 30 | ### Normal Install 31 | 32 | ``` 33 | pip install keras==2.1.5 numpy==1.14.5 matplotlib==2.2.2 innvestigate==1.0.8.3 scikit-image==0.15.0 34 | ``` 35 | 36 | ### Docker 37 | 38 | ``` 39 | sudo docker build -t sglrp . 40 | docker run --runtime nvidia -rm -it -p 127.0.0.1:8888:8888 -v `pwd`:/work -w /work sglrp jupyter notebook --allow-root 41 | ``` 42 | 43 | ## Usage 44 | 45 | ### SGLRP Class 46 | 47 | ``` 48 | utils.visualizations.SGLRP(partial_model, target_id, relu=False, low=-1., high=1., **kwargs) 49 | ``` 50 | #### Arguments 51 | 52 | **partial_model** : *Keras Model instance* 53 | 54 |     A keras model with the output of softmax cut off, but the input to the output layer intact. The partial model can be found using the innvestigate library using the ```innvestigate.utils.keras.graph.pre_softmax_tensors()``` function. 55 | 56 | **target_id** : *int* 57 | 58 |     The index of the target class. 59 | 60 | **relu** : *bool* 61 | 62 |     Controls if ReLU is applied to the visualization. ```True``` means that only the positive relevance is shown; ```False``` shows both the positive and negative relevance. 63 | 64 | **low** : *float* 65 | 66 |     The upper bounds of the inputs. 67 | 68 | **high** : *float* 69 | 70 |     The lower bounds of the inputs. 71 | 72 | ### SGLRP.analyze() 73 | 74 | ``` 75 | SGLRP.analyze(input_imgs) 76 | ``` 77 | #### Arguments 78 | 79 | **input_imgs** : *4D array* 80 | 81 |     Array of input images in the format of ```(image_id, height, width, channel)```. 82 | 83 | 84 | #### Returns 85 | 86 | *4D array* 87 | 88 |     Array of heatmaps in the format of ```(image_id, height, width, channel)```. 89 | 90 | ### Simple Example 91 | 92 | ``` 93 | from utils.visualizations import SGLRP 94 | import innvestigate.utils as iutils 95 | 96 | model = [keras model] 97 | partial_model = Model(inputs=model.inputs, outputs=iutils.keras.graph.pre_softmax_tensors(model.outputs)) 98 | 99 | target_id = [id of target class] 100 | analysis = SGLRP(partial_model, target_id).analyze(input_imgs) 101 | 102 | ``` 103 | 104 | ### Full Example 105 | 106 | [Example Notebook](example.ipynb) 107 | 108 | ## Citation 109 | 110 | B. K. Iwana, R. Kuroki, and S. Uchida, "Explaining Convolutional Neural Networks using Softmax Gradient Layer-wise Relevance Propagation," in International Conference on Computer Vision Workshops, 2019. 111 | 112 | ``` 113 | @inproceedings{iwana2019explaining, 114 | title={Explaining Convolutional Neural Networks using Softmax Gradient Layer-wise Relevance Propagation}, 115 | author={Iwana, Brian Kenji and Kuroki, Ryohei and Uchida, Seiichi}, 116 | booktitle={International Conference on Computer Vision Workshops}, 117 | year={2019} 118 | } 119 | ``` 120 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Ryohei Kuroki 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /utils/visualizations.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from keras import backend as K 3 | from innvestigate.analyzer import BoundedDeepTaylor, GuidedBackprop 4 | from innvestigate.analyzer import LRPEpsilon, LRPSequentialPresetAFlat, LRPSequentialPresetBFlat 5 | from innvestigate.analyzer import Deconvnet, IntegratedGradients, SmoothGrad 6 | import innvestigate.utils as iutils 7 | from keras.layers import Lambda, Layer 8 | from skimage.transform import resize 9 | 10 | 11 | class _SoftMax(Layer): 12 | def call(self, x): 13 | return [K.softmax(tmp) for tmp in iutils.to_list(x)] 14 | 15 | class _MaskedGuidedBackprop(GuidedBackprop): 16 | def __init__(self, 17 | model, 18 | R_mask, 19 | **kwargs): 20 | super(_MaskedGuidedBackprop, self).__init__(model, neuron_selection_mode="all", **kwargs) 21 | self.initialize_r_mask(R_mask) 22 | 23 | def initialize_r_mask(self, R_mask): 24 | """0か1のベクトルでRが通れる道をターゲットのみに限定 25 | Arguments: 26 | initial_R_mask {[type]} -- [description] 27 | """ 28 | 29 | self.R_mask = K.constant(R_mask) 30 | 31 | def _head_mapping(self, X): 32 | """ 33 | 初期化時に与えたOne-hotベクターとの要素積をとることでRが通れる道を限定 34 | """ 35 | initial_R = Lambda(lambda x: (x * self.R_mask))(X) 36 | return initial_R 37 | 38 | 39 | class GBP(_MaskedGuidedBackprop): 40 | def __init__(self, 41 | model, 42 | target_id, 43 | relu=False, 44 | **kwargs): 45 | """ターゲット:predictionの値,それ以外0 46 | Arguments: 47 | model {[type]} -- [description] 48 | target_id {[type]} -- [description] 49 | predictions {[type]} -- [description] 50 | """ 51 | self.relu=relu 52 | R_mask = np.zeros(model.output_shape[1]) 53 | R_mask[target_id] = 1 54 | super(GBP, self).__init__(model, R_mask=R_mask, **kwargs) 55 | 56 | def analyze(self, inputs): 57 | if self.relu: 58 | return np.maximum(super(GBP, self).analyze(inputs), 0) 59 | else: 60 | return super(GBP, self).analyze(inputs) 61 | 62 | class _MaskedDeepTaylor(BoundedDeepTaylor): 63 | """Give any specific path to the DTD 64 | """ 65 | 66 | def __init__(self, model, R_mask, **kwargs): 67 | super(_MaskedDeepTaylor, self).__init__( 68 | model, neuron_selection_mode="all", **kwargs) 69 | self.initialize_r_mask(R_mask) 70 | 71 | def initialize_r_mask(self, R_mask): 72 | """Mask R road 73 | Arguments: 74 | initial_R_mask {[type]} -- [description] 75 | """ 76 | 77 | self.R_mask = K.constant(R_mask) 78 | 79 | def _head_mapping(self, X): 80 | """Multiplication with the initialized one-hot vector 81 | """ 82 | initial_R = Lambda(lambda x: (x * self.R_mask))(X) 83 | return initial_R 84 | 85 | 86 | class LRP(_MaskedDeepTaylor): 87 | def __init__(self, 88 | model, 89 | target_id, 90 | relu=False, 91 | low=-1., 92 | high=1., 93 | **kwargs): 94 | """Target value:same as prediction,otherwise:0 95 | Arguments: 96 | model {[type]} -- [description] 97 | target_id {[type]} -- [description] 98 | predictions {[type]} -- [description] 99 | """ 100 | self.relu = relu 101 | R_mask = np.zeros((model.output_shape[1])) 102 | R_mask[target_id] = 1 103 | super(LRP, self).__init__(model, R_mask=R_mask, low=low, high=high, **kwargs) 104 | 105 | def analyze(self, inputs): 106 | if self.relu: 107 | return np.maximum(super(LRP, self).analyze(inputs), 0) 108 | else: 109 | return super(LRP, self).analyze(inputs) 110 | 111 | 112 | class _LRPSubtraction(object): 113 | def __init__(self, 114 | model, 115 | target_id, 116 | scaling=True, 117 | **kwargs): 118 | self.model = model 119 | self.target_id = target_id 120 | self.scaling = scaling 121 | self.target_analyzer = self._get_target_analyzer(**kwargs) 122 | self.others_analyzer = self._get_others_analyzer(**kwargs) 123 | 124 | def _get_target_analyzer(self, **kwargs): 125 | raise NotImplementedError 126 | 127 | def _get_others_analyzer(self, **kwargs): 128 | raise NotImplementedError 129 | 130 | def analyze_target(self, inputs): 131 | return self.target_analyzer.analyze(inputs) 132 | 133 | def analyze_others(self, inputs): 134 | return self.others_analyzer.analyze(inputs) 135 | 136 | def analyze(self, inputs): 137 | analysis_target = self.analyze_target(inputs) 138 | analysis_others = self.analyze_others(inputs) 139 | 140 | # 画像毎にスケーリング調整 141 | equal_magnification = 1 142 | if self.scaling: 143 | equal_magnification = analysis_target.sum( 144 | axis=(1, 2, 3), keepdims=True) / analysis_others.sum( 145 | axis=(1, 2, 3), keepdims=True) 146 | analysis = analysis_target - analysis_others * equal_magnification 147 | return analysis 148 | 149 | 150 | class _CLRPBase(BoundedDeepTaylor): 151 | def __init__(self, 152 | model, 153 | target_id, 154 | **kwargs): 155 | super(_CLRPBase, self).__init__( 156 | model, neuron_selection_mode="all", **kwargs) 157 | self.target_id = target_id 158 | self.class_num = model.output_shape[1] 159 | self.initialize_r_mask() 160 | 161 | def initialize_r_mask(self): 162 | raise NotImplementedError 163 | 164 | def _head_mapping(self, X): 165 | target_value = Lambda(lambda x: (x[:, self.target_id]))(X) 166 | X = Lambda(lambda x: (x[:, None] * self.R_mask))(target_value) 167 | return X 168 | 169 | class _CLRPTarget(_CLRPBase): 170 | def initialize_r_mask(self): 171 | R_mask = np.zeros(self.class_num) 172 | R_mask[self.target_id] = 1 173 | self.R_mask = K.constant(R_mask) 174 | 175 | 176 | class _CLRPOthers(_CLRPBase): 177 | """R dual for CLRP1 178 | """ 179 | 180 | def initialize_r_mask(self): 181 | R_mask = np.ones(self.class_num) 182 | R_mask[self.target_id] = 0 183 | R_mask /= self.class_num - 1 184 | self.R_mask = K.constant(R_mask) 185 | 186 | 187 | class CLRP(_LRPSubtraction): 188 | def __init__(self, 189 | model, 190 | target_id, 191 | relu=False, 192 | low=-1., 193 | high=1., 194 | **kwargs): 195 | super(CLRP, self).__init__(model, target_id=target_id, low=low, high=high, **kwargs) 196 | self.relu = relu 197 | 198 | def _get_target_analyzer(self, **kwargs): 199 | return _CLRPTarget(self.model, target_id=self.target_id, **kwargs) 200 | 201 | def _get_others_analyzer(self, **kwargs): 202 | return _CLRPOthers(self.model, target_id=self.target_id, **kwargs) 203 | 204 | def analyze(self, inputs): 205 | if self.relu: 206 | return np.maximum(super(CLRP, self).analyze(inputs), 0) 207 | else: 208 | return super(CLRP, self).analyze(inputs) 209 | 210 | class _SGLRPBase(BoundedDeepTaylor): 211 | """Initialize R with Softmax Gradient 212 | """ 213 | def __init__(self, 214 | model, 215 | target_id, 216 | **kwargs): 217 | super(_SGLRPBase, self).__init__(model, neuron_selection_mode="all", **kwargs) 218 | self.target_id = target_id 219 | self.class_num = model.output_shape[1] 220 | self.initialize_r_mask() 221 | 222 | def initialize_r_mask(self): 223 | raise NotImplementedError 224 | 225 | 226 | def _head_mapping(self, X): 227 | """ 228 | target:yt(1-yt) base: ytyi 229 | """ 230 | # It's possible to have a perfect prediction. A small amount is added to prevent problems. 231 | epsilon = 1e-8 232 | 233 | # target is 1, else 0 234 | Kronecker_delta = np.zeros(self.class_num) 235 | Kronecker_delta[self.target_id] = 1 236 | Kronecker_delta = K.constant(Kronecker_delta) 237 | 238 | # target is 0, else 1 239 | Inv_Kronecker_delta = np.ones(self.class_num) 240 | Inv_Kronecker_delta[self.target_id] = 0 241 | Inv_Kronecker_delta = K.constant(Inv_Kronecker_delta) 242 | 243 | X = _SoftMax()(X) 244 | target_value = Lambda(lambda x: (x[:, self.target_id]))(X) 245 | 246 | 247 | X = Lambda( 248 | lambda x: (x * (1. - x) + epsilon) * Kronecker_delta + x * Inv_Kronecker_delta * target_value[:, None], 249 | output_shape=lambda input_shape: (None, int(input_shape[1])))(X) 250 | 251 | X = Lambda(lambda x: (self.R_mask * x))(X) 252 | return X 253 | 254 | 255 | class _SGLRPTarget(_SGLRPBase): 256 | def initialize_r_mask(self): 257 | R_mask = np.zeros(self.class_num) 258 | R_mask[self.target_id] = 1 259 | self.R_mask = K.constant(R_mask) 260 | 261 | 262 | class _SGLRPDual(_SGLRPBase): 263 | def initialize_r_mask(self): 264 | R_mask = np.ones(self.class_num) 265 | R_mask[self.target_id] = 0 266 | self.R_mask = K.constant(R_mask) 267 | 268 | 269 | class SGLRP(_LRPSubtraction): 270 | def __init__(self, 271 | model, 272 | target_id, 273 | relu=False, 274 | low=-1., 275 | high=1., 276 | **kwargs): 277 | super(SGLRP, self).__init__(model, target_id=target_id, low=low, high=high, **kwargs) 278 | self.relu = relu 279 | 280 | def _get_target_analyzer(self, **kwargs): 281 | return _SGLRPTarget(self.model, target_id=self.target_id, **kwargs) 282 | 283 | def _get_others_analyzer(self, **kwargs): 284 | return _SGLRPDual(self.model, target_id=self.target_id, **kwargs) 285 | 286 | def analyze(self, inputs): 287 | if self.relu: 288 | return np.maximum(super(SGLRP, self).analyze(inputs), 0) 289 | else: 290 | return super(SGLRP, self).analyze(inputs) 291 | 292 | 293 | class SGLRPSeqA(LRPSequentialPresetAFlat): 294 | def __init__(self, 295 | model, 296 | target_id, 297 | relu=False, 298 | **kwargs): 299 | self.relu=relu 300 | self.target_id = target_id 301 | self.class_num = model.output_shape[1] 302 | super(SGLRPSeqA, self).__init__(model, neuron_selection_mode="all", **kwargs) 303 | 304 | def _head_mapping(self, X): 305 | """ 306 | target:yt(1-yt) base: ytyi 307 | """ 308 | # It's possible to have a perfect prediction. A small amount is added to prevent problems. 309 | epsilon = 1e-8 310 | 311 | # target is 1, else 0 312 | Kronecker_delta = np.zeros(self.class_num) 313 | Kronecker_delta[self.target_id] = 1 314 | Kronecker_delta = K.constant(Kronecker_delta) 315 | 316 | # target is 0, else 1 317 | Inv_Kronecker_delta = np.ones(self.class_num) 318 | Inv_Kronecker_delta[self.target_id] = 0 319 | Inv_Kronecker_delta = K.constant(Inv_Kronecker_delta) 320 | 321 | X = _SoftMax()(X) 322 | target_value = Lambda(lambda x: (x[:, self.target_id]))(X) 323 | 324 | 325 | X = Lambda( 326 | lambda x: (x * (1. - x) + epsilon) * Kronecker_delta - x * Inv_Kronecker_delta * target_value[:, None], 327 | output_shape=lambda input_shape: (None, int(input_shape[1])))(X) 328 | 329 | return X 330 | 331 | def analyze(self, inputs): 332 | if self.relu: 333 | return np.maximum(super(SGLRPSeqA, self).analyze(inputs), 0) 334 | else: 335 | return super(SGLRPSeqA, self).analyze(inputs) 336 | 337 | class SGLRPSeqB(LRPSequentialPresetBFlat): 338 | def __init__(self, 339 | model, 340 | target_id, 341 | relu=False, 342 | **kwargs): 343 | self.relu=relu 344 | self.target_id = target_id 345 | self.class_num = model.output_shape[1] 346 | super(SGLRPSeqB, self).__init__(model, neuron_selection_mode="all", **kwargs) 347 | 348 | def _head_mapping(self, X): 349 | """ 350 | target:yt(1-yt) base: ytyi 351 | """ 352 | # It's possible to have a perfect prediction. A small amount is added to prevent problems. 353 | epsilon = 1e-8 354 | 355 | # target is 1, else 0 356 | Kronecker_delta = np.zeros(self.class_num) 357 | Kronecker_delta[self.target_id] = 1 358 | Kronecker_delta = K.constant(Kronecker_delta) 359 | 360 | # target is 0, else 1 361 | Inv_Kronecker_delta = np.ones(self.class_num) 362 | Inv_Kronecker_delta[self.target_id] = 0 363 | Inv_Kronecker_delta = K.constant(Inv_Kronecker_delta) 364 | 365 | X = _SoftMax()(X) 366 | target_value = Lambda(lambda x: (x[:, self.target_id]))(X) 367 | 368 | 369 | X = Lambda( 370 | lambda x: (x * (1. - x) + epsilon) * Kronecker_delta - x * Inv_Kronecker_delta * target_value[:, None], 371 | output_shape=lambda input_shape: (None, int(input_shape[1])))(X) 372 | 373 | return X 374 | 375 | def analyze(self, inputs): 376 | if self.relu: 377 | return np.maximum(super(SGLRPSeqB, self).analyze(inputs), 0) 378 | else: 379 | return super(SGLRPSeqB, self).analyze(inputs) 380 | 381 | class LRPE(LRPEpsilon): 382 | def __init__(self, 383 | model, 384 | target_id, 385 | relu=False, 386 | **kwargs): 387 | self.relu=relu 388 | R_mask = np.zeros(model.output_shape[1]) 389 | R_mask[target_id] = 1 390 | self.initialize_r_mask(R_mask) 391 | super(LRPE, self).__init__(model, neuron_selection_mode="all", **kwargs) 392 | 393 | def initialize_r_mask(self, R_mask): 394 | """0か1のベクトルでRが通れる道をターゲットのみに限定 395 | Arguments: 396 | initial_R_mask {[type]} -- [description] 397 | """ 398 | 399 | self.R_mask = K.constant(R_mask) 400 | 401 | def _head_mapping(self, X): 402 | """ 403 | 初期化時に与えたOne-hotベクターとの要素積をとることでRが通れる道を限定 404 | """ 405 | initial_R = Lambda(lambda x: (x * self.R_mask))(X) 406 | return initial_R 407 | 408 | def analyze(self, inputs): 409 | if self.relu: 410 | return np.maximum(super(LRPE, self).analyze(inputs), 0) 411 | else: 412 | return super(LRPE, self).analyze(inputs) 413 | 414 | class LRPB(LRPSequentialPresetBFlat): 415 | def __init__(self, 416 | model, 417 | target_id, 418 | relu=False, 419 | **kwargs): 420 | self.relu=relu 421 | R_mask = np.zeros(model.output_shape[1]) 422 | R_mask[target_id] = 1 423 | self.initialize_r_mask(R_mask) 424 | super(LRPB, self).__init__(model, neuron_selection_mode="all", **kwargs) 425 | 426 | def initialize_r_mask(self, R_mask): 427 | """0か1のベクトルでRが通れる道をターゲットのみに限定 428 | Arguments: 429 | initial_R_mask {[type]} -- [description] 430 | """ 431 | 432 | self.R_mask = K.constant(R_mask) 433 | 434 | def _head_mapping(self, X): 435 | """ 436 | 初期化時に与えたOne-hotベクターとの要素積をとることでRが通れる道を限定 437 | """ 438 | initial_R = Lambda(lambda x: (x * self.R_mask))(X) 439 | return initial_R 440 | 441 | def analyze(self, inputs): 442 | if self.relu: 443 | return np.maximum(super(LRPB, self).analyze(inputs), 0) 444 | else: 445 | return super(LRPB, self).analyze(inputs) 446 | 447 | class LRPA(LRPSequentialPresetAFlat): 448 | def __init__(self, 449 | model, 450 | target_id, 451 | relu=False, 452 | **kwargs): 453 | self.relu=relu 454 | R_mask = np.zeros(model.output_shape[1]) 455 | R_mask[target_id] = 1 456 | self.initialize_r_mask(R_mask) 457 | super(LRPA, self).__init__(model, neuron_selection_mode="all", **kwargs) 458 | 459 | def initialize_r_mask(self, R_mask): 460 | """0か1のベクトルでRが通れる道をターゲットのみに限定 461 | Arguments: 462 | initial_R_mask {[type]} -- [description] 463 | """ 464 | 465 | self.R_mask = K.constant(R_mask) 466 | 467 | def _head_mapping(self, X): 468 | """ 469 | 初期化時に与えたOne-hotベクターとの要素積をとることでRが通れる道を限定 470 | """ 471 | initial_R = Lambda(lambda x: (x * self.R_mask))(X) 472 | return initial_R 473 | 474 | def analyze(self, inputs): 475 | if self.relu: 476 | return np.maximum(super(LRPA, self).analyze(inputs), 0) 477 | else: 478 | return super(LRPA, self).analyze(inputs) 479 | 480 | class SG(SmoothGrad): 481 | def __init__(self, 482 | model, 483 | target_id, 484 | relu=False, 485 | **kwargs): 486 | self.relu=relu 487 | R_mask = np.zeros(model.output_shape[1]) 488 | R_mask[target_id] = 1 489 | self.initialize_r_mask(R_mask) 490 | super(SG, self).__init__(model, **kwargs) 491 | 492 | def initialize_r_mask(self, R_mask): 493 | """0か1のベクトルでRが通れる道をターゲットのみに限定 494 | Arguments: 495 | initial_R_mask {[type]} -- [description] 496 | """ 497 | 498 | self.R_mask = K.constant(R_mask) 499 | 500 | def _head_mapping(self, X): 501 | """ 502 | 初期化時に与えたOne-hotベクターとの要素積をとることでRが通れる道を限定 503 | """ 504 | initial_R = Lambda(lambda x: (x * self.R_mask))(X) 505 | return initial_R 506 | 507 | def analyze(self, inputs): 508 | if self.relu: 509 | return np.maximum(super(SG, self).analyze(inputs), 0) 510 | else: 511 | return super(SG, self).analyze(inputs) 512 | 513 | class IG(IntegratedGradients): 514 | def __init__(self, 515 | model, 516 | target_id, 517 | relu=False, 518 | **kwargs): 519 | self.relu=relu 520 | R_mask = np.zeros(model.output_shape[1]) 521 | R_mask[target_id] = 1 522 | self.initialize_r_mask(R_mask) 523 | super(IG, self).__init__(model, **kwargs) 524 | 525 | def initialize_r_mask(self, R_mask): 526 | """0か1のベクトルでRが通れる道をターゲットのみに限定 527 | Arguments: 528 | initial_R_mask {[type]} -- [description] 529 | """ 530 | 531 | self.R_mask = K.constant(R_mask) 532 | 533 | def _head_mapping(self, X): 534 | """ 535 | 初期化時に与えたOne-hotベクターとの要素積をとることでRが通れる道を限定 536 | """ 537 | initial_R = Lambda(lambda x: (x * self.R_mask))(X) 538 | return initial_R 539 | 540 | def analyze(self, inputs): 541 | if self.relu: 542 | return np.maximum(super(IG, self).analyze(inputs), 0) 543 | else: 544 | return super(IG, self).analyze(inputs) 545 | 546 | class GradCAM(object): 547 | def __init__(self, 548 | model, 549 | target_id, 550 | layer_name="block5_pool", 551 | relu=False, 552 | **kwargs): 553 | 554 | class_output = model.output[:, target_id] 555 | 556 | conv_output = model.get_layer( 557 | layer_name).output 558 | grads = K.gradients(class_output, conv_output)[ 559 | 0] 560 | self.gradient_function = K.function( 561 | [model.input], 562 | [conv_output, grads], 563 | ) 564 | self.relu = relu 565 | 566 | def analyze(self, inputs): 567 | outputs, grads_vals = self.gradient_function([inputs]) 568 | 569 | weights = np.mean(grads_vals, axis=(1, 2)) 570 | cams = (outputs * weights[:, np.newaxis, np.newaxis, :]).sum( 571 | axis=3, keepdims=True) 572 | 573 | resized_cams = resize(cams, np.shape(inputs), mode='reflect', anti_aliasing=True) 574 | 575 | if self.relu: 576 | return np.maximum(resized_cams, 0) 577 | else: 578 | return resized_cams 579 | 580 | class MultiGradCAM(object): 581 | def __init__(self, 582 | model, 583 | target_id, 584 | layer_name="block5_pool", 585 | relu=False, 586 | **kwargs): 587 | 588 | class_output = model.output[:, target_id] 589 | # if the layer is shared, this needs to be done 590 | conv_output = model.get_layer(layer_name).get_output_at(0) 591 | grads = K.gradients(class_output, conv_output)[0] 592 | self.gradient_function = K.function( 593 | [model.input[0], model.input[1]], # this is the key difference, two inputs 594 | [conv_output, grads], 595 | ) 596 | self.relu = relu 597 | 598 | def analyze(self, inputs): 599 | outputs, grads_vals = self.gradient_function(inputs) 600 | weights = np.mean(grads_vals, axis=(1, 2)) 601 | cams = (outputs * weights[:, np.newaxis, np.newaxis, :]).sum( 602 | axis=3, keepdims=True) 603 | 604 | # the reshape was wrong because the input size is different with two inputs 605 | resized_cams = resize(cams, np.shape(inputs[0]), mode='reflect', anti_aliasing=True) 606 | 607 | if self.relu: 608 | return np.maximum(resized_cams, 0) 609 | else: 610 | return resized_cams 611 | 612 | class GuidedGradCAM(object): 613 | def __init__(self, 614 | model, 615 | target_id, 616 | layer_name="block5_pool", 617 | relu=False, 618 | **kwargs): 619 | self.model = model 620 | self.target_id = target_id 621 | self.relu = relu 622 | self.gradcam = GradCAM(self.model, target_id=self.target_id, layer_name=layer_name, relu=relu, **kwargs) 623 | self.guidedbackprop = GBP(self.model, target_id=self.target_id, relu=relu, **kwargs) 624 | 625 | def analyze(self, inputs): 626 | return self.gradcam.analyze(inputs) * self.guidedbackprop.analyze(inputs) --------------------------------------------------------------------------------