├── LICENSE
├── README.md
├── Results
├── PN_ID340_Gamma_100.0
│ ├── Adv_id340_kappa10.0_Orig3_Adv5_Delta8.png
│ ├── Adv_id340_kappa10.0_Orig3_Adv5_Delta8.png.npy
│ ├── Delta_id340_kappa10.0_Orig3_Adv5_Delta8.png
│ ├── Delta_id340_kappa10.0_Orig3_Adv5_Delta8.png.npy
│ ├── Orig_original3.png
│ └── Orig_original3.png.npy
└── PP_ID2953_Gamma_100.0
│ ├── Adv_id2953_kappa10.0_Orig5_Adv3_Delta5.png
│ ├── Adv_id2953_kappa10.0_Orig5_Adv3_Delta5.png.npy
│ ├── Delta_id2953_kappa10.0_Orig5_Adv3_Delta5.png
│ ├── Delta_id2953_kappa10.0_Orig5_Adv3_Delta5.png.npy
│ ├── Orig_original5.png
│ └── Orig_original5.png.npy
├── Utils.py
├── aen_CEM.py
├── main.py
├── models
├── AE_codec
│ ├── mnist_AE_1_decoder.h5
│ └── mnist_AE_1_decoder.json
└── mnist
└── setup_mnist.py
/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 [yyyy] [name of copyright owner]
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Contrastive-Explanation-Method
2 | Codes for reproducing the contrastive explanation in “[Explanations based on the Missing: Towards Contrastive Explanations with Pertinent Negatives](https://arxiv.org/abs/1802.07623)”
3 |
4 |
5 | To find the pertinent positive (PP) of an instance,
6 |
7 | ```shell
8 | python3 main.py -i 2953 --mode PP --kappa 10 --gamma 100
9 | ```
10 | This would find the PP of image ID 2953 in the test images from the MNIST dataset.
11 |
12 |
13 |
14 |
15 | From left to right: the original image and the pertinent positive component. This PP in Image 2953 is sufficient to be classified as 5.
16 |
17 | To find the pertinent negative (PN) of an instance,
18 |
19 | ```shell
20 | python3 main.py -i 340 --mode PN --kappa 10 --gamma 100
21 | ```
22 | This would find the PN of image ID 340 in the test images from the MNIST dataset.
23 |
24 | 

25 |
26 |
27 | From left to right: the original image, the pertinent negative component and the image composed of the original image and PN. If we add PN to Image 340, it would be classified as 5.
28 |
29 | The argument `kappa` (confidence lebel) and `gamma` (regularization coefficient of autoencoder) are tuning parameters for the optimization setup. Both PP and PN are used to explain the model prediction results. For more details, please refer to the paper.
30 |
--------------------------------------------------------------------------------
/Results/PN_ID340_Gamma_100.0/Adv_id340_kappa10.0_Orig3_Adv5_Delta8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PN_ID340_Gamma_100.0/Adv_id340_kappa10.0_Orig3_Adv5_Delta8.png
--------------------------------------------------------------------------------
/Results/PN_ID340_Gamma_100.0/Adv_id340_kappa10.0_Orig3_Adv5_Delta8.png.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PN_ID340_Gamma_100.0/Adv_id340_kappa10.0_Orig3_Adv5_Delta8.png.npy
--------------------------------------------------------------------------------
/Results/PN_ID340_Gamma_100.0/Delta_id340_kappa10.0_Orig3_Adv5_Delta8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PN_ID340_Gamma_100.0/Delta_id340_kappa10.0_Orig3_Adv5_Delta8.png
--------------------------------------------------------------------------------
/Results/PN_ID340_Gamma_100.0/Delta_id340_kappa10.0_Orig3_Adv5_Delta8.png.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PN_ID340_Gamma_100.0/Delta_id340_kappa10.0_Orig3_Adv5_Delta8.png.npy
--------------------------------------------------------------------------------
/Results/PN_ID340_Gamma_100.0/Orig_original3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PN_ID340_Gamma_100.0/Orig_original3.png
--------------------------------------------------------------------------------
/Results/PN_ID340_Gamma_100.0/Orig_original3.png.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PN_ID340_Gamma_100.0/Orig_original3.png.npy
--------------------------------------------------------------------------------
/Results/PP_ID2953_Gamma_100.0/Adv_id2953_kappa10.0_Orig5_Adv3_Delta5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PP_ID2953_Gamma_100.0/Adv_id2953_kappa10.0_Orig5_Adv3_Delta5.png
--------------------------------------------------------------------------------
/Results/PP_ID2953_Gamma_100.0/Adv_id2953_kappa10.0_Orig5_Adv3_Delta5.png.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PP_ID2953_Gamma_100.0/Adv_id2953_kappa10.0_Orig5_Adv3_Delta5.png.npy
--------------------------------------------------------------------------------
/Results/PP_ID2953_Gamma_100.0/Delta_id2953_kappa10.0_Orig5_Adv3_Delta5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PP_ID2953_Gamma_100.0/Delta_id2953_kappa10.0_Orig5_Adv3_Delta5.png
--------------------------------------------------------------------------------
/Results/PP_ID2953_Gamma_100.0/Delta_id2953_kappa10.0_Orig5_Adv3_Delta5.png.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PP_ID2953_Gamma_100.0/Delta_id2953_kappa10.0_Orig5_Adv3_Delta5.png.npy
--------------------------------------------------------------------------------
/Results/PP_ID2953_Gamma_100.0/Orig_original5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PP_ID2953_Gamma_100.0/Orig_original5.png
--------------------------------------------------------------------------------
/Results/PP_ID2953_Gamma_100.0/Orig_original5.png.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/Results/PP_ID2953_Gamma_100.0/Orig_original5.png.npy
--------------------------------------------------------------------------------
/Utils.py:
--------------------------------------------------------------------------------
1 | ## Utils.py -- Some utility functions
2 | ##
3 | ## Copyright (C) 2018, IBM Corp
4 | ## Chun-Chen Tu
5 | ## PaiShun Ting
6 | ## Pin-Yu Chen
7 | ##
8 | ## Licensed under the Apache License, Version 2.0 (the "License");
9 | ## you may not use this file except in compliance with the License.
10 | ## You may obtain a copy of the License at
11 | ##
12 | ## http://www.apache.org/licenses/LICENSE-2.0
13 | ##
14 | ## Unless required by applicable law or agreed to in writing, software
15 | ## distributed under the License is distributed on an "AS IS" BASIS,
16 | ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | ## See the License for the specific language governing permissions and
18 | ## limitations under the License.
19 |
20 | from keras.models import Model, model_from_json, Sequential
21 | from PIL import Image
22 |
23 | import tensorflow as tf
24 | import os
25 | import numpy as np
26 |
27 |
28 | def load_AE(codec_prefix, print_summary=False):
29 |
30 | saveFilePrefix = "models/AE_codec/" + codec_prefix + "_"
31 |
32 | decoder_model_filename = saveFilePrefix + "decoder.json"
33 | decoder_weight_filename = saveFilePrefix + "decoder.h5"
34 |
35 | if not os.path.isfile(decoder_model_filename):
36 | raise Exception("The file for decoder model does not exist:{}".format(decoder_model_filename))
37 | json_file = open(decoder_model_filename, 'r')
38 | decoder = model_from_json(json_file.read(), custom_objects={"tf": tf})
39 | json_file.close()
40 |
41 | if not os.path.isfile(decoder_weight_filename):
42 | raise Exception("The file for decoder weights does not exist:{}".format(decoder_weight_filename))
43 | decoder.load_weights(decoder_weight_filename)
44 |
45 | if print_summary:
46 | print("Decoder summaries")
47 | decoder.summary()
48 |
49 | return decoder
50 |
51 | def save_img(img, name = "output.png"):
52 |
53 | np.save(name, img)
54 | fig = np.around((img + 0.5)*255)
55 | fig = fig.astype(np.uint8).squeeze()
56 | pic = Image.fromarray(fig)
57 | pic.save(name)
58 |
59 | def generate_data(data, id, target_label):
60 | inputs = []
61 | target_vec = []
62 |
63 | inputs.append(data.test_data[id])
64 | target_vec.append(np.eye(data.test_labels.shape[1])[target_label])
65 |
66 | inputs = np.array(inputs)
67 | target_vec = np.array(target_vec)
68 |
69 | return inputs, target_vec
70 |
71 | def model_prediction(model, inputs):
72 | prob = model.model.predict(inputs)
73 | predicted_class = np.argmax(prob)
74 | prob_str = np.array2string(prob).replace('\n','')
75 | return prob, predicted_class, prob_str
76 |
--------------------------------------------------------------------------------
/aen_CEM.py:
--------------------------------------------------------------------------------
1 | ## aen_attack.py -- attack a network optimizing elastic-net distance with an en decision rule
2 | ## when autoencoder loss is applied
3 | ##
4 | ## Copyright (C) 2018, IBM Corp
5 | ## Chun-Chen Tu
6 | ## PaiShun Ting
7 | ## Pin-Yu Chen
8 | ##
9 | ## Licensed under the Apache License, Version 2.0 (the "License");
10 | ## you may not use this file except in compliance with the License.
11 | ## You may obtain a copy of the License at
12 | ##
13 | ## http://www.apache.org/licenses/LICENSE-2.0
14 | ##
15 | ## Unless required by applicable law or agreed to in writing, software
16 | ## distributed under the License is distributed on an "AS IS" BASIS,
17 | ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 | ## See the License for the specific language governing permissions and
19 | ## limitations under the License.
20 |
21 | import sys
22 | import tensorflow as tf
23 | import numpy as np
24 |
25 |
26 | class AEADEN:
27 | def __init__(self, sess, model, mode, AE, batch_size, kappa, init_learning_rate,
28 | binary_search_steps, max_iterations, initial_const, beta, gamma):
29 |
30 |
31 | image_size, num_channels, nun_classes = model.image_size, model.num_channels, model.num_labels
32 | shape = (batch_size, image_size, image_size, num_channels)
33 |
34 | self.sess = sess
35 | self.INIT_LEARNING_RATE = init_learning_rate
36 | self.MAX_ITERATIONS = max_iterations
37 | self.BINARY_SEARCH_STEPS = binary_search_steps
38 | self.kappa = kappa
39 | self.init_const = initial_const
40 | self.batch_size = batch_size
41 | self.AE = AE
42 | self.mode = mode
43 | self.beta = beta
44 | self.gamma = gamma
45 |
46 | # these are variables to be more efficient in sending data to tf
47 | self.orig_img = tf.Variable(np.zeros(shape), dtype=tf.float32)
48 | self.adv_img = tf.Variable(np.zeros(shape), dtype=tf.float32)
49 | self.adv_img_s = tf.Variable(np.zeros(shape), dtype=tf.float32)
50 | self.target_lab = tf.Variable(np.zeros((batch_size,nun_classes)), dtype=tf.float32)
51 | self.const = tf.Variable(np.zeros(batch_size), dtype=tf.float32)
52 | self.global_step = tf.Variable(0.0, trainable=False)
53 |
54 | # and here's what we use to assign them
55 | self.assign_orig_img = tf.placeholder(tf.float32, shape)
56 | self.assign_adv_img = tf.placeholder(tf.float32, shape)
57 | self.assign_adv_img_s = tf.placeholder(tf.float32, shape)
58 | self.assign_target_lab = tf.placeholder(tf.float32, (batch_size,nun_classes))
59 | self.assign_const = tf.placeholder(tf.float32, [batch_size])
60 |
61 |
62 | """Fast Iterative Soft Thresholding"""
63 | """--------------------------------"""
64 | self.zt = tf.divide(self.global_step, self.global_step+tf.cast(3, tf.float32))
65 |
66 | cond1 = tf.cast(tf.greater(tf.subtract(self.adv_img_s, self.orig_img),self.beta), tf.float32)
67 | cond2 = tf.cast(tf.less_equal(tf.abs(tf.subtract(self.adv_img_s,self.orig_img)),self.beta), tf.float32)
68 | cond3 = tf.cast(tf.less(tf.subtract(self.adv_img_s, self.orig_img),tf.negative(self.beta)), tf.float32)
69 | upper = tf.minimum(tf.subtract(self.adv_img_s, self.beta), tf.cast(0.5, tf.float32))
70 | lower = tf.maximum(tf.add(self.adv_img_s, self.beta), tf.cast(-0.5, tf.float32))
71 | self.assign_adv_img = tf.multiply(cond1,upper)+tf.multiply(cond2,self.orig_img)+tf.multiply(cond3,lower)
72 |
73 | cond4=tf.cast(tf.greater(tf.subtract( self.assign_adv_img, self.orig_img),0), tf.float32)
74 | cond5=tf.cast(tf.less_equal(tf.subtract( self.assign_adv_img,self.orig_img),0), tf.float32)
75 | if self.mode == "PP":
76 | self.assign_adv_img = tf.multiply(cond5,self.assign_adv_img)+tf.multiply(cond4,self.orig_img)
77 | elif self.mode == "PN":
78 | self.assign_adv_img = tf.multiply(cond4,self.assign_adv_img)+tf.multiply(cond5,self.orig_img)
79 |
80 | self.assign_adv_img_s = self.assign_adv_img+tf.multiply(self.zt, self.assign_adv_img-self.adv_img)
81 | cond6=tf.cast(tf.greater(tf.subtract( self.assign_adv_img_s, self.orig_img),0), tf.float32)
82 | cond7=tf.cast(tf.less_equal(tf.subtract( self.assign_adv_img_s,self.orig_img),0), tf.float32)
83 | if self.mode == "PP":
84 | self.assign_adv_img_s = tf.multiply(cond7, self.assign_adv_img_s)+tf.multiply(cond6,self.orig_img)
85 | elif self.mode == "PN":
86 | self.assign_adv_img_s = tf.multiply(cond6, self.assign_adv_img_s)+tf.multiply(cond7,self.orig_img)
87 |
88 |
89 | self.adv_updater = tf.assign(self.adv_img, self.assign_adv_img)
90 | self.adv_updater_s = tf.assign(self.adv_img_s, self.assign_adv_img_s)
91 |
92 | """--------------------------------"""
93 | # prediction BEFORE-SOFTMAX of the model
94 | self.delta_img = self.orig_img-self.adv_img
95 | self.delta_img_s = self.orig_img-self.adv_img_s
96 | if self.mode == "PP":
97 | self.ImgToEnforceLabel_Score = model.predict(self.delta_img)
98 | self.ImgToEnforceLabel_Score_s = model.predict(self.delta_img_s)
99 | elif self.mode == "PN":
100 | self.ImgToEnforceLabel_Score = model.predict(self.adv_img)
101 | self.ImgToEnforceLabel_Score_s = model.predict(self.adv_img_s)
102 |
103 | # distance to the input data
104 | self.L2_dist = tf.reduce_sum(tf.square(self.delta_img),[1,2,3])
105 | self.L2_dist_s = tf.reduce_sum(tf.square(self.delta_img_s),[1,2,3])
106 | self.L1_dist = tf.reduce_sum(tf.abs(self.delta_img),[1,2,3])
107 | self.L1_dist_s = tf.reduce_sum(tf.abs(self.delta_img_s),[1,2,3])
108 | self.EN_dist = self.L2_dist + tf.multiply(self.L1_dist, self.beta)
109 | self.EN_dist_s = self.L2_dist_s + tf.multiply(self.L1_dist_s, self.beta)
110 |
111 | # compute the probability of the label class versus the maximum other
112 | self.target_lab_score = tf.reduce_sum((self.target_lab)*self.ImgToEnforceLabel_Score,1)
113 | target_lab_score_s = tf.reduce_sum((self.target_lab)*self.ImgToEnforceLabel_Score_s,1)
114 | self.max_nontarget_lab_score = tf.reduce_max((1-self.target_lab)*self.ImgToEnforceLabel_Score - (self.target_lab*10000),1)
115 | max_nontarget_lab_score_s = tf.reduce_max((1-self.target_lab)*self.ImgToEnforceLabel_Score_s - (self.target_lab*10000),1)
116 | if self.mode == "PP":
117 | Loss_Attack = tf.maximum(0.0, self.max_nontarget_lab_score - self.target_lab_score + self.kappa)
118 | Loss_Attack_s = tf.maximum(0.0, max_nontarget_lab_score_s - target_lab_score_s + self.kappa)
119 | elif self.mode == "PN":
120 | Loss_Attack = tf.maximum(0.0, -self.max_nontarget_lab_score + self.target_lab_score + self.kappa)
121 | Loss_Attack_s = tf.maximum(0.0, -max_nontarget_lab_score_s + target_lab_score_s + self.kappa)
122 | # sum up the losses
123 | self.Loss_L1Dist = tf.reduce_sum(self.L1_dist)
124 | self.Loss_L1Dist_s = tf.reduce_sum(self.L1_dist_s)
125 | self.Loss_L2Dist = tf.reduce_sum(self.L2_dist)
126 | self.Loss_L2Dist_s = tf.reduce_sum(self.L2_dist_s)
127 | self.Loss_Attack = tf.reduce_sum(self.const*Loss_Attack)
128 | self.Loss_Attack_s = tf.reduce_sum(self.const*Loss_Attack_s)
129 | if self.mode == "PP":
130 | self.Loss_AE_Dist = self.gamma*tf.square(tf.norm(self.AE(self.delta_img)-self.delta_img))
131 | self.Loss_AE_Dist_s = self.gamma*tf.square(tf.norm(self.AE(self.delta_img)-self.delta_img_s))
132 | elif self.mode == "PN":
133 | self.Loss_AE_Dist = self.gamma*tf.square(tf.norm(self.AE(self.adv_img)-self.adv_img))
134 | self.Loss_AE_Dist_s = self.gamma*tf.square(tf.norm(self.AE(self.adv_img_s)-self.adv_img_s))
135 |
136 | self.Loss_ToOptimize = self.Loss_Attack_s + self.Loss_L2Dist_s + self.Loss_AE_Dist_s
137 | self.Loss_Overall = self.Loss_Attack + self.Loss_L2Dist + self.Loss_AE_Dist + tf.multiply(self.beta, self.Loss_L1Dist)
138 |
139 | self.learning_rate = tf.train.polynomial_decay(self.INIT_LEARNING_RATE, self.global_step, self.MAX_ITERATIONS, 0, power=0.5)
140 | optimizer = tf.train.GradientDescentOptimizer(self.learning_rate)
141 | start_vars = set(x.name for x in tf.global_variables())
142 | self.train = optimizer.minimize(self.Loss_ToOptimize, var_list=[self.adv_img_s], global_step=self.global_step)
143 | end_vars = tf.global_variables()
144 | new_vars = [x for x in end_vars if x.name not in start_vars]
145 |
146 | # these are the variables to initialize when we run
147 | self.setup = []
148 | self.setup.append(self.orig_img.assign(self.assign_orig_img))
149 | self.setup.append(self.target_lab.assign(self.assign_target_lab))
150 | self.setup.append(self.const.assign(self.assign_const))
151 | self.setup.append(self.adv_img.assign(self.assign_adv_img))
152 | self.setup.append(self.adv_img_s.assign(self.assign_adv_img_s))
153 |
154 | self.init = tf.variables_initializer(var_list=[self.global_step]+[self.adv_img_s]+[self.adv_img]+new_vars)
155 |
156 | def attack(self, imgs, labs):
157 |
158 | def compare(x,y):
159 | if not isinstance(x, (float, int, np.int64)):
160 | x = np.copy(x)
161 | # x[y] -= self.kappa if self.PP else -self.kappa
162 | if self.mode == "PP":
163 | x[y] -= self.kappa
164 | elif self.mode == "PN":
165 | x[y] += self.kappa
166 | x = np.argmax(x)
167 | if self.mode == "PP":
168 | return x==y
169 | else:
170 | return x!=y
171 |
172 | batch_size = self.batch_size
173 |
174 | # set the lower and upper bounds accordingly
175 | Const_LB = np.zeros(batch_size)
176 | CONST = np.ones(batch_size)*self.init_const
177 | Const_UB = np.ones(batch_size)*1e10
178 | # the best l2, score, and image attack
179 | overall_best_dist = [1e10]*batch_size
180 | overall_best_attack = [np.zeros(imgs[0].shape)]*batch_size
181 |
182 | for binary_search_steps_idx in range(self.BINARY_SEARCH_STEPS):
183 | # completely reset adam's internal state.
184 | self.sess.run(self.init)
185 | img_batch = imgs[:batch_size]
186 | label_batch = labs[:batch_size]
187 |
188 | current_step_best_dist = [1e10]*batch_size
189 | current_step_best_score = [-1]*batch_size
190 |
191 | # set the variables so that we don't have to send them over again
192 | self.sess.run(self.setup, {self.assign_orig_img: img_batch,
193 | self.assign_target_lab: label_batch,
194 | self.assign_const: CONST,
195 | self.assign_adv_img: img_batch,
196 | self.assign_adv_img_s: img_batch})
197 |
198 | for iteration in range(self.MAX_ITERATIONS):
199 | # perform the attack
200 | self.sess.run([self.train])
201 | self.sess.run([self.adv_updater, self.adv_updater_s])
202 |
203 | Loss_Overall, Loss_EN, OutputScore, adv_img = self.sess.run([self.Loss_Overall, self.EN_dist, self.ImgToEnforceLabel_Score, self.adv_img])
204 | Loss_Attack, Loss_L2Dist, Loss_L1Dist, Loss_AE_Dist = self.sess.run([self.Loss_Attack, self.Loss_L2Dist, self.Loss_L1Dist, self.Loss_AE_Dist])
205 | target_lab_score, max_nontarget_lab_score_s = self.sess.run([self.target_lab_score, self.max_nontarget_lab_score])
206 |
207 | if iteration%(self.MAX_ITERATIONS//10) == 0:
208 | print("iter:{} const:{}". format(iteration, CONST))
209 | print("Loss_Overall:{:.4f}, Loss_Attack:{:.4f}". format(Loss_Overall, Loss_Attack))
210 | print("Loss_L2Dist:{:.4f}, Loss_L1Dist:{:.4f}, AE_loss:{}". format(Loss_L2Dist, Loss_L1Dist, Loss_AE_Dist))
211 | print("target_lab_score:{:.4f}, max_nontarget_lab_score:{:.4f}". format(target_lab_score[0], max_nontarget_lab_score_s[0]))
212 | print("")
213 | sys.stdout.flush()
214 |
215 | for batch_idx,(the_dist, the_score, the_adv_img) in enumerate(zip(Loss_EN, OutputScore, adv_img)):
216 | if the_dist < current_step_best_dist[batch_idx] and compare(the_score, np.argmax(label_batch[batch_idx])):
217 | current_step_best_dist[batch_idx] = the_dist
218 | current_step_best_score[batch_idx] = np.argmax(the_score)
219 | if the_dist < overall_best_dist[batch_idx] and compare(the_score, np.argmax(label_batch[batch_idx])):
220 | overall_best_dist[batch_idx] = the_dist
221 | overall_best_attack[batch_idx] = the_adv_img
222 |
223 | # adjust the constant as needed
224 | for batch_idx in range(batch_size):
225 | if compare(current_step_best_score[batch_idx], np.argmax(label_batch[batch_idx])) and current_step_best_score[batch_idx] != -1:
226 | # success, divide const by two
227 | Const_UB[batch_idx] = min(Const_UB[batch_idx],CONST[batch_idx])
228 | if Const_UB[batch_idx] < 1e9:
229 | CONST[batch_idx] = (Const_LB[batch_idx] + Const_UB[batch_idx])/2
230 | else:
231 | # failure, either multiply by 10 if no solution found yet
232 | # or do binary search with the known upper bound
233 | Const_LB[batch_idx] = max(Const_LB[batch_idx],CONST[batch_idx])
234 | if Const_UB[batch_idx] < 1e9:
235 | CONST[batch_idx] = (Const_LB[batch_idx] + Const_UB[batch_idx])/2
236 | else:
237 | CONST[batch_idx] *= 10
238 |
239 | # return the best solution found
240 | overall_best_attack = overall_best_attack[0]
241 | return overall_best_attack.reshape((1,) + overall_best_attack.shape)
242 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | ## main.py -- sample code to test attack procedure
2 | ##
3 | ## Copyright (C) 2018, IBM Corp
4 | ## Chun-Chen Tu
5 | ## PaiShun Ting
6 | ## Pin-Yu Chen
7 | ##
8 | ## Licensed under the Apache License, Version 2.0 (the "License");
9 | ## you may not use this file except in compliance with the License.
10 | ## You may obtain a copy of the License at
11 | ##
12 | ## http://www.apache.org/licenses/LICENSE-2.0
13 | ##
14 | ## Unless required by applicable law or agreed to in writing, software
15 | ## distributed under the License is distributed on an "AS IS" BASIS,
16 | ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | ## See the License for the specific language governing permissions and
18 | ## limitations under the License.
19 |
20 | import os
21 | import sys
22 | import tensorflow as tf
23 | import numpy as np
24 | import random
25 | import time
26 | from keras.layers import Lambda
27 | from setup_mnist import MNIST, MNISTModel
28 |
29 | import Utils as util
30 | from aen_CEM import AEADEN
31 |
32 |
33 | def main(args):
34 | with tf.Session() as sess:
35 | random.seed(121)
36 | np.random.seed(1211)
37 |
38 | image_id = args['img_id']
39 | arg_max_iter = args['maxiter']
40 | arg_b = args['binary_steps']
41 | arg_init_const = args['init_const']
42 | arg_mode = args['mode']
43 | arg_kappa = args['kappa']
44 | arg_beta = args['beta']
45 | arg_gamma =args['gamma']
46 |
47 |
48 |
49 | AE_model = util.load_AE("mnist_AE_1")
50 | data, model = MNIST(), MNISTModel("models/mnist", sess, False)
51 |
52 | orig_prob, orig_class, orig_prob_str = util.model_prediction(model, np.expand_dims(data.test_data[image_id], axis=0))
53 | target_label = orig_class
54 | print("Image:{}, infer label:{}".format(image_id, target_label))
55 | orig_img, target = util.generate_data(data, image_id, target_label)
56 |
57 | attack = AEADEN(sess, model, mode = arg_mode, AE = AE_model, batch_size=1, kappa=arg_kappa, init_learning_rate=1e-2,
58 | binary_search_steps=arg_b, max_iterations=arg_max_iter, initial_const=arg_init_const, beta=arg_beta, gamma=arg_gamma)
59 |
60 | adv_img = attack.attack(orig_img, target)
61 |
62 | adv_prob, adv_class, adv_prob_str = util.model_prediction(model, adv_img)
63 | delta_prob, delta_class, delta_prob_str = util.model_prediction(model, orig_img-adv_img)
64 |
65 | INFO = "[INFO]id:{}, kappa:{}, Orig class:{}, Adv class:{}, Delta class: {}, Orig prob:{}, Adv prob:{}, Delta prob:{}".format(image_id, arg_kappa, orig_class, adv_class, delta_class, orig_prob_str, adv_prob_str, delta_prob_str)
66 | print(INFO)
67 |
68 | suffix = "id{}_kappa{}_Orig{}_Adv{}_Delta{}".format(image_id, arg_kappa, orig_class, adv_class, delta_class)
69 | arg_save_dir = "{}_ID{}_Gamma_{}".format(arg_mode, image_id, arg_gamma)
70 | os.system("mkdir -p Results/{}".format(arg_save_dir))
71 | util.save_img(orig_img, "Results/{}/Orig_original{}.png".format(arg_save_dir, orig_class))
72 | util.save_img(adv_img, "Results/{}/Adv_{}.png".format(arg_save_dir, suffix))
73 | util.save_img(np.absolute(orig_img-adv_img)-0.5, "Results/{}/Delta_{}.png".format(arg_save_dir, suffix))
74 |
75 | sys.stdout.flush()
76 |
77 |
78 | if __name__ == "__main__":
79 | import argparse
80 | parser = argparse.ArgumentParser()
81 | parser.add_argument("-i", "--img_id", type=int)
82 | parser.add_argument("-m", "--maxiter", type=int, default=1000)
83 | parser.add_argument("-b", "--binary_steps", type=int, default=9)
84 | parser.add_argument("-c", "--init_const", type=float, default=10.0)
85 | parser.add_argument("--mode", choices=["PN", "PP"], default="PN")
86 | parser.add_argument("--kappa", type=float, default=0)
87 | parser.add_argument("--beta", type=float, default=1e-1)
88 | parser.add_argument("--gamma", type=float, default=0)
89 |
90 | args = vars(parser.parse_args())
91 | main(args)
92 |
--------------------------------------------------------------------------------
/models/AE_codec/mnist_AE_1_decoder.h5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/models/AE_codec/mnist_AE_1_decoder.h5
--------------------------------------------------------------------------------
/models/AE_codec/mnist_AE_1_decoder.json:
--------------------------------------------------------------------------------
1 | {"class_name": "Sequential", "config": [{"class_name": "Sequential", "config": [{"class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "batch_input_shape": [null, 28, 28, 1], "dtype": "float32", "filters": 16, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_1", "trainable": true, "activation": "relu"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "filters": 16, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_2", "trainable": true, "activation": "relu"}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "pool_size": [2, 2], "padding": "same", "strides": [2, 2], "data_format": "channels_last"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_3", "trainable": true, "filters": 1, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}]}, {"class_name": "Conv2D", "config": {"name": "conv2d_4", "trainable": true, "filters": 16, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_3", "trainable": true, "activation": "relu"}}, {"class_name": "UpSampling2D", "config": {"name": "up_sampling2d_1", "trainable": true, "size": [2, 2], "data_format": "channels_last"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_5", "trainable": true, "filters": 16, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Activation", "config": {"name": "activation_4", "trainable": true, "activation": "relu"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_6", "trainable": true, "filters": 1, "kernel_size": [3, 3], "strides": [1, 1], "padding": "same", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}], "keras_version": "2.0.5", "backend": "tensorflow"}
--------------------------------------------------------------------------------
/models/mnist:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBM/Contrastive-Explanation-Method/c09c28ccf2bc0b04348963d405ed702eca0f02b6/models/mnist
--------------------------------------------------------------------------------
/setup_mnist.py:
--------------------------------------------------------------------------------
1 | ## setup_mnist.py -- mnist data and model loading code
2 | ##
3 | ## Copyright (C) 2016, Nicholas Carlini .
4 | ##
5 | ## This program is licenced under the BSD 2-Clause licence,
6 | ## contained in the LICENCE file in this directory.
7 |
8 | import tensorflow as tf
9 | import numpy as np
10 | import os
11 | import pickle
12 | import gzip
13 | import urllib.request
14 |
15 | from keras.models import Sequential
16 | from keras.layers import Dense, Dropout, Activation, Flatten
17 | from keras.layers import Conv2D, MaxPooling2D
18 | from keras.utils import np_utils
19 | from keras.models import load_model
20 |
21 | def extract_data(filename, num_images):
22 | with gzip.open(filename) as bytestream:
23 | bytestream.read(16)
24 | buf = bytestream.read(num_images*28*28)
25 | data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
26 | data = (data / 255) - 0.5
27 | data = data.reshape(num_images, 28, 28, 1)
28 | return data
29 |
30 | def extract_labels(filename, num_images):
31 | with gzip.open(filename) as bytestream:
32 | bytestream.read(8)
33 | buf = bytestream.read(1 * num_images)
34 | labels = np.frombuffer(buf, dtype=np.uint8)
35 | return (np.arange(10) == labels[:, None]).astype(np.float32)
36 |
37 | class MNIST:
38 | def __init__(self):
39 | if not os.path.exists("data"):
40 | os.mkdir("data")
41 | files = ["train-images-idx3-ubyte.gz",
42 | "t10k-images-idx3-ubyte.gz",
43 | "train-labels-idx1-ubyte.gz",
44 | "t10k-labels-idx1-ubyte.gz"]
45 | for name in files:
46 |
47 | urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/' + name, "data/"+name)
48 |
49 | train_data = extract_data("data/train-images-idx3-ubyte.gz", 60000)
50 | train_labels = extract_labels("data/train-labels-idx1-ubyte.gz", 60000)
51 | self.test_data = extract_data("data/t10k-images-idx3-ubyte.gz", 10000)
52 | self.test_labels = extract_labels("data/t10k-labels-idx1-ubyte.gz", 10000)
53 |
54 | VALIDATION_SIZE = 5000
55 |
56 | self.validation_data = train_data[:VALIDATION_SIZE, :, :, :]
57 | self.validation_labels = train_labels[:VALIDATION_SIZE]
58 | self.train_data = train_data[VALIDATION_SIZE:, :, :, :]
59 | self.train_labels = train_labels[VALIDATION_SIZE:]
60 |
61 |
62 | class MNISTModel:
63 | def __init__(self, restore = None, session=None, use_log=False):
64 | self.num_channels = 1
65 | self.image_size = 28
66 | self.num_labels = 10
67 |
68 | model = Sequential()
69 |
70 | model.add(Conv2D(32, (3, 3),
71 | input_shape=(28, 28, 1)))
72 | model.add(Activation('relu'))
73 | model.add(Conv2D(32, (3, 3)))
74 | model.add(Activation('relu'))
75 | model.add(MaxPooling2D(pool_size=(2, 2)))
76 |
77 | model.add(Conv2D(64, (3, 3)))
78 | model.add(Activation('relu'))
79 | model.add(Conv2D(64, (3, 3)))
80 | model.add(Activation('relu'))
81 | model.add(MaxPooling2D(pool_size=(2, 2)))
82 |
83 | model.add(Flatten())
84 | model.add(Dense(200))
85 | model.add(Activation('relu'))
86 | model.add(Dense(200))
87 | model.add(Activation('relu'))
88 | model.add(Dense(10))
89 | # output log probability, used for black-box attack
90 | if use_log:
91 | model.add(Activation('softmax'))
92 | if restore:
93 | model.load_weights(restore)
94 |
95 | self.model = model
96 |
97 | def predict(self, data):
98 | return self.model(data)
99 |
100 |
--------------------------------------------------------------------------------