interpretation_algorithms.py 16.2 KB
Newer Older
S
sunyanfang01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

S
sunyanfang01 已提交
15 16 17 18 19 20
import os
import numpy as np
import time

from . import lime_base
from ..as_data_reader.readers import read_image
S
sunyanfang01 已提交
21 22
from ._session_preparation import paddle_get_fc_weights, compute_features_for_kmeans, h_pre_models_kmeans
from .normlime_base import combine_normlime_and_lime, get_feature_for_kmeans, load_kmeans_model
S
sunyanfang01 已提交
23 24 25 26 27

import cv2


class CAM(object):
S
SunAhong1993 已提交
28
    def __init__(self, predict_fn, label_names):
S
sunyanfang01 已提交
29 30 31 32 33 34 35 36 37 38 39
        """

        Args:
            predict_fn: input: images_show [N, H, W, 3], RGB range(0, 255)
                        output: [
                        logits [N, num_classes],
                        feature map before global average pooling [N, num_channels, h_, w_]
                        ]

        """
        self.predict_fn = predict_fn
S
SunAhong1993 已提交
40
        self.label_names = label_names
S
sunyanfang01 已提交
41

S
sunyanfang01 已提交
42 43
    def preparation_cam(self, data_):
        image_show = read_image(data_)
S
sunyanfang01 已提交
44 45 46 47 48
        result = self.predict_fn(image_show)

        logit = result[0][0]
        if abs(np.sum(logit) - 1.0) > 1e-4:
            # softmax
S
sunyanfang01 已提交
49
            logit = logit - np.max(logit)
S
sunyanfang01 已提交
50 51 52 53 54
            exp_result = np.exp(logit)
            probability = exp_result / np.sum(exp_result)
        else:
            probability = logit

S
sunyanfang01 已提交
55
        # only interpret top 1
S
sunyanfang01 已提交
56 57 58 59 60 61 62 63 64 65
        pred_label = np.argsort(probability)
        pred_label = pred_label[-1:]

        self.predicted_label = pred_label[0]
        self.predicted_probability = probability[pred_label[0]]
        self.image = image_show[0]
        self.labels = pred_label

        fc_weights = paddle_get_fc_weights()
        feature_maps = result[1]
S
SunAhong1993 已提交
66 67 68 69 70
        
        l = pred_label[0]
        ln = l
        if self.label_names is not None:
            ln = self.label_names[l]
S
sunyanfang01 已提交
71

S
SunAhong1993 已提交
72
        print(f'predicted result: {ln} with probability {probability[pred_label[0]]:.3f}')
S
sunyanfang01 已提交
73 74
        return feature_maps, fc_weights

S
sunyanfang01 已提交
75
    def interpret(self, data_, visualization=True, save_to_disk=True, save_outdir=None):
S
sunyanfang01 已提交
76 77 78 79 80 81 82
        feature_maps, fc_weights = self.preparation_cam(data_)
        cam = get_cam(self.image, feature_maps, fc_weights, self.predicted_label)

        if visualization or save_to_disk:
            import matplotlib.pyplot as plt
            from skimage.segmentation import mark_boundaries
            l = self.labels[0]
S
SunAhong1993 已提交
83 84 85
            ln = l 
            if self.label_names is not None:
                ln = self.label_names[l]
S
sunyanfang01 已提交
86 87 88 89 90 91 92 93 94 95 96

            psize = 5
            nrows = 1
            ncols = 2

            plt.close()
            f, axes = plt.subplots(nrows, ncols, figsize=(psize * ncols, psize * nrows))
            for ax in axes.ravel():
                ax.axis("off")
            axes = axes.ravel()
            axes[0].imshow(self.image)
S
SunAhong1993 已提交
97
            axes[0].set_title(f"label {ln}, proba: {self.predicted_probability: .3f}")
S
sunyanfang01 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

            axes[1].imshow(cam)
            axes[1].set_title("CAM")

        if save_to_disk and save_outdir is not None:
            os.makedirs(save_outdir, exist_ok=True)
            save_fig(data_, save_outdir, 'cam')

        if visualization:
            plt.show()

        return


class LIME(object):
S
SunAhong1993 已提交
113
    def __init__(self, predict_fn, label_names, num_samples=3000, batch_size=50):
S
sunyanfang01 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126
        """
        LIME wrapper. See lime_base.py for the detailed LIME implementation.
        Args:
            predict_fn: from image [N, H, W, 3] to logits [N, num_classes], this is necessary for computing LIME.
            num_samples: the number of samples that LIME takes for fitting.
            batch_size: batch size for model inference each time.
        """
        self.num_samples = num_samples
        self.batch_size = batch_size

        self.predict_fn = predict_fn
        self.labels = None
        self.image = None
S
sunyanfang01 已提交
127
        self.lime_interpreter = None
S
SunAhong1993 已提交
128
        self.label_names = label_names
S
sunyanfang01 已提交
129

S
sunyanfang01 已提交
130 131
    def preparation_lime(self, data_):
        image_show = read_image(data_)
S
sunyanfang01 已提交
132 133 134 135 136 137
        result = self.predict_fn(image_show)

        result = result[0]  # only one image here.

        if abs(np.sum(result) - 1.0) > 1e-4:
            # softmax
S
sunyanfang01 已提交
138
            result = result - np.max(result)
S
sunyanfang01 已提交
139 140 141 142 143
            exp_result = np.exp(result)
            probability = exp_result / np.sum(exp_result)
        else:
            probability = result

S
sunyanfang01 已提交
144
        # only interpret top 1
S
sunyanfang01 已提交
145 146 147 148 149 150 151
        pred_label = np.argsort(probability)
        pred_label = pred_label[-1:]

        self.predicted_label = pred_label[0]
        self.predicted_probability = probability[pred_label[0]]
        self.image = image_show[0]
        self.labels = pred_label
S
SunAhong1993 已提交
152 153 154 155 156 157 158
        
        l = pred_label[0]
        ln = l
        if self.label_names is not None:
            ln = self.label_names[l]
            
        print(f'predicted result: {ln} with probability {probability[pred_label[0]]:.3f}')
S
sunyanfang01 已提交
159 160

        end = time.time()
S
sunyanfang01 已提交
161 162 163 164
        algo = lime_base.LimeImageInterpreter()
        interpreter = algo.interpret_instance(self.image, self.predict_fn, self.labels, 0,
                                              num_samples=self.num_samples, batch_size=self.batch_size)
        self.lime_interpreter = interpreter
S
sunyanfang01 已提交
165 166
        print('lime time: ', time.time() - end, 's.')

S
sunyanfang01 已提交
167 168
    def interpret(self, data_, visualization=True, save_to_disk=True, save_outdir=None):
        if self.lime_interpreter is None:
S
sunyanfang01 已提交
169 170 171 172 173 174
            self.preparation_lime(data_)

        if visualization or save_to_disk:
            import matplotlib.pyplot as plt
            from skimage.segmentation import mark_boundaries
            l = self.labels[0]
S
SunAhong1993 已提交
175 176 177
            ln = l 
            if self.label_names is not None:
                ln = self.label_names[l]
S
sunyanfang01 已提交
178 179 180

            psize = 5
            nrows = 2
S
sunyanfang01 已提交
181
            weights_choices = [0.6, 0.7, 0.75, 0.8, 0.85]
S
sunyanfang01 已提交
182 183 184 185 186 187 188 189
            ncols = len(weights_choices)

            plt.close()
            f, axes = plt.subplots(nrows, ncols, figsize=(psize * ncols, psize * nrows))
            for ax in axes.ravel():
                ax.axis("off")
            axes = axes.ravel()
            axes[0].imshow(self.image)
S
SunAhong1993 已提交
190
            axes[0].set_title(f"label {ln}, proba: {self.predicted_probability: .3f}")
S
sunyanfang01 已提交
191

S
sunyanfang01 已提交
192
            axes[1].imshow(mark_boundaries(self.image, self.lime_interpreter.segments))
S
sunyanfang01 已提交
193 194 195 196
            axes[1].set_title("superpixel segmentation")

            # LIME visualization
            for i, w in enumerate(weights_choices):
S
sunyanfang01 已提交
197 198
                num_to_show = auto_choose_num_features_to_show(self.lime_interpreter, l, w)
                temp, mask = self.lime_interpreter.get_image_and_mask(
S
sunyanfang01 已提交
199 200 201
                    l, positive_only=False, hide_rest=False, num_features=num_to_show
                )
                axes[ncols + i].imshow(mark_boundaries(temp, mask))
S
SunAhong1993 已提交
202
                axes[ncols + i].set_title(f"label {ln}, first {num_to_show} superpixels")
S
sunyanfang01 已提交
203 204 205 206 207 208 209 210 211 212 213 214

        if save_to_disk and save_outdir is not None:
            os.makedirs(save_outdir, exist_ok=True)
            save_fig(data_, save_outdir, 'lime', self.num_samples)

        if visualization:
            plt.show()

        return


class NormLIME(object):
S
SunAhong1993 已提交
215
    def __init__(self, predict_fn, label_names, num_samples=3000, batch_size=50,
S
sunyanfang01 已提交
216
                 kmeans_model_for_normlime=None, normlime_weights=None):
S
sunyanfang01 已提交
217 218 219 220 221 222 223 224 225 226
        if kmeans_model_for_normlime is None:
            try:
                self.kmeans_model = load_kmeans_model(h_pre_models_kmeans)
            except:
                raise ValueError("NormLIME needs the KMeans model, where we provided a default one in "
                                 "pre_models/kmeans_model.pkl.")
        else:
            print("Warning: It is *strongly* suggested to use the default KMeans model in pre_models/kmeans_model.pkl. "
                  "Use another one will change the final result.")
            self.kmeans_model = load_kmeans_model(kmeans_model_for_normlime)
S
sunyanfang01 已提交
227 228 229 230

        self.num_samples = num_samples
        self.batch_size = batch_size

S
sunyanfang01 已提交
231 232 233 234 235
        try:
            self.normlime_weights = np.load(normlime_weights, allow_pickle=True).item()
        except:
            self.normlime_weights = None
            print("Warning: not find the correct precomputed Normlime result.")
S
sunyanfang01 已提交
236 237 238 239 240

        self.predict_fn = predict_fn

        self.labels = None
        self.image = None
S
SunAhong1993 已提交
241
        self.label_names = label_names
S
sunyanfang01 已提交
242 243 244 245 246 247 248 249

    def predict_cluster_labels(self, feature_map, segments):
        return self.kmeans_model.predict(get_feature_for_kmeans(feature_map, segments))

    def predict_using_normlime_weights(self, pred_labels, predicted_cluster_labels):
        # global weights
        g_weights = {y: [] for y in pred_labels}
        for y in pred_labels:
S
sunyanfang01 已提交
250
            cluster_weights_y = self.normlime_weights.get(y, {})
S
sunyanfang01 已提交
251 252 253 254 255 256 257 258 259
            g_weights[y] = [
                (i, cluster_weights_y.get(k, 0.0)) for i, k in enumerate(predicted_cluster_labels)
            ]

            g_weights[y] = sorted(g_weights[y],
                                  key=lambda x: np.abs(x[1]), reverse=True)

        return g_weights

S
sunyanfang01 已提交
260
    def preparation_normlime(self, data_):
S
sunyanfang01 已提交
261
        self._lime = LIME(
S
sunyanfang01 已提交
262
            self.predict_fn,
S
SunAhong1993 已提交
263
            self.label_names,
S
sunyanfang01 已提交
264 265 266
            self.num_samples,
            self.batch_size
        )
S
sunyanfang01 已提交
267
        self._lime.preparation_lime(data_)
S
sunyanfang01 已提交
268

S
sunyanfang01 已提交
269
        image_show = read_image(data_)
S
sunyanfang01 已提交
270

S
sunyanfang01 已提交
271 272
        self.predicted_label = self._lime.predicted_label
        self.predicted_probability = self._lime.predicted_probability
S
sunyanfang01 已提交
273
        self.image = image_show[0]
S
sunyanfang01 已提交
274 275 276
        self.labels = self._lime.labels
        # print(f'predicted result: {self.predicted_label} with probability {self.predicted_probability: .3f}')
        print('performing NormLIME operations ...')
S
sunyanfang01 已提交
277 278

        cluster_labels = self.predict_cluster_labels(
S
sunyanfang01 已提交
279
            compute_features_for_kmeans(image_show).transpose((1, 2, 0)), self._lime.lime_interpreter.segments
S
sunyanfang01 已提交
280 281 282 283 284 285
        )

        g_weights = self.predict_using_normlime_weights(self.labels, cluster_labels)

        return g_weights

S
sunyanfang01 已提交
286
    def interpret(self, data_, visualization=True, save_to_disk=True, save_outdir=None):
S
sunyanfang01 已提交
287 288 289 290
        if self.normlime_weights is None:
            raise ValueError("Not find the correct precomputed NormLIME result. \n"
                             "\t Try to call compute_normlime_weights() first or load the correct path.")

S
sunyanfang01 已提交
291
        g_weights = self.preparation_normlime(data_)
S
sunyanfang01 已提交
292
        lime_weights = self._lime.lime_interpreter.local_weights
S
sunyanfang01 已提交
293 294 295 296 297

        if visualization or save_to_disk:
            import matplotlib.pyplot as plt
            from skimage.segmentation import mark_boundaries
            l = self.labels[0]
S
SunAhong1993 已提交
298 299 300
            ln = l
            if self.label_names is not None:
                ln = self.label_names[l]
S
sunyanfang01 已提交
301 302 303

            psize = 5
            nrows = 4
S
sunyanfang01 已提交
304 305
            weights_choices = [0.6, 0.7, 0.75, 0.8, 0.85]
            nums_to_show = []
S
sunyanfang01 已提交
306 307 308 309 310 311 312 313 314
            ncols = len(weights_choices)

            plt.close()
            f, axes = plt.subplots(nrows, ncols, figsize=(psize * ncols, psize * nrows))
            for ax in axes.ravel():
                ax.axis("off")

            axes = axes.ravel()
            axes[0].imshow(self.image)
S
SunAhong1993 已提交
315
            axes[0].set_title(f"label {ln}, proba: {self.predicted_probability: .3f}")
S
sunyanfang01 已提交
316

S
sunyanfang01 已提交
317
            axes[1].imshow(mark_boundaries(self.image, self._lime.lime_interpreter.segments))
S
sunyanfang01 已提交
318 319 320 321
            axes[1].set_title("superpixel segmentation")

            # LIME visualization
            for i, w in enumerate(weights_choices):
S
sunyanfang01 已提交
322
                num_to_show = auto_choose_num_features_to_show(self._lime.lime_interpreter, l, w)
S
sunyanfang01 已提交
323
                nums_to_show.append(num_to_show)
S
sunyanfang01 已提交
324
                temp, mask = self._lime.lime_interpreter.get_image_and_mask(
S
sunyanfang01 已提交
325 326 327
                    l, positive_only=False, hide_rest=False, num_features=num_to_show
                )
                axes[ncols + i].imshow(mark_boundaries(temp, mask))
S
sunyanfang01 已提交
328
                axes[ncols + i].set_title(f"LIME: first {num_to_show} superpixels")
S
sunyanfang01 已提交
329 330

            # NormLIME visualization
S
sunyanfang01 已提交
331
            self._lime.lime_interpreter.local_weights = g_weights
S
sunyanfang01 已提交
332
            for i, num_to_show in enumerate(nums_to_show):
S
sunyanfang01 已提交
333
                temp, mask = self._lime.lime_interpreter.get_image_and_mask(
S
sunyanfang01 已提交
334 335 336
                    l, positive_only=False, hide_rest=False, num_features=num_to_show
                )
                axes[ncols * 2 + i].imshow(mark_boundaries(temp, mask))
S
sunyanfang01 已提交
337
                axes[ncols * 2 + i].set_title(f"NormLIME: first {num_to_show} superpixels")
S
sunyanfang01 已提交
338 339 340

            # NormLIME*LIME visualization
            combined_weights = combine_normlime_and_lime(lime_weights, g_weights)
S
sunyanfang01 已提交
341
            self._lime.lime_interpreter.local_weights = combined_weights
S
sunyanfang01 已提交
342
            for i, num_to_show in enumerate(nums_to_show):
S
sunyanfang01 已提交
343
                temp, mask = self._lime.lime_interpreter.get_image_and_mask(
S
sunyanfang01 已提交
344 345 346
                    l, positive_only=False, hide_rest=False, num_features=num_to_show
                )
                axes[ncols * 3 + i].imshow(mark_boundaries(temp, mask))
S
sunyanfang01 已提交
347
                axes[ncols * 3 + i].set_title(f"Combined: first {num_to_show} superpixels")
S
sunyanfang01 已提交
348

S
sunyanfang01 已提交
349
            self._lime.lime_interpreter.local_weights = lime_weights
S
sunyanfang01 已提交
350 351 352 353 354 355 356 357 358

        if save_to_disk and save_outdir is not None:
            os.makedirs(save_outdir, exist_ok=True)
            save_fig(data_, save_outdir, 'normlime', self.num_samples)

        if visualization:
            plt.show()


S
sunyanfang01 已提交
359 360 361
def auto_choose_num_features_to_show(lime_interpreter, label, percentage_to_show):
    segments = lime_interpreter.segments
    lime_weights = lime_interpreter.local_weights[label]
S
sunyanfang01 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    num_pixels_threshold_in_a_sp = segments.shape[0] * segments.shape[1] // len(np.unique(segments)) // 8

    # l1 norm with filtered weights.
    used_weights = [(tuple_w[0], tuple_w[1]) for i, tuple_w in enumerate(lime_weights) if tuple_w[1] > 0]
    norm = np.sum([tuple_w[1] for i, tuple_w in enumerate(used_weights)])
    normalized_weights = [(tuple_w[0], tuple_w[1] / norm) for i, tuple_w in enumerate(lime_weights)]

    a = 0.0
    n = 0
    for i, tuple_w in enumerate(normalized_weights):
        if tuple_w[1] < 0:
            continue
        if len(np.where(segments == tuple_w[0])[0]) < num_pixels_threshold_in_a_sp:
            continue

        a += tuple_w[1]
        if a > percentage_to_show:
            n = i + 1
            break

S
sunyanfang01 已提交
382 383 384
    if percentage_to_show <= 0.0:
        return 5

S
sunyanfang01 已提交
385
    if n == 0:
S
sunyanfang01 已提交
386
        return auto_choose_num_features_to_show(lime_interpreter, label, percentage_to_show-0.1)
S
sunyanfang01 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

    return n


def get_cam(image_show, feature_maps, fc_weights, label_index, cam_min=None, cam_max=None):
    _, nc, h, w = feature_maps.shape

    cam = feature_maps * fc_weights[:, label_index].reshape(1, nc, 1, 1)
    cam = cam.sum((0, 1))

    if cam_min is None:
        cam_min = np.min(cam)
    if cam_max is None:
        cam_max = np.max(cam)

    cam = cam - cam_min
    cam = cam / cam_max
    cam = np.uint8(255 * cam)
    cam_img = cv2.resize(cam, image_show.shape[0:2], interpolation=cv2.INTER_LINEAR)

    heatmap = cv2.applyColorMap(np.uint8(255 * cam_img), cv2.COLORMAP_JET)
    heatmap = np.float32(heatmap)
    cam = heatmap + np.float32(image_show)
    cam = cam / np.max(cam)

    return cam


def save_fig(data_, save_outdir, algorithm_name, num_samples=3000):
    import matplotlib.pyplot as plt
    if isinstance(data_, str):
        if algorithm_name == 'cam':
            f_out = f"{algorithm_name}_{data_.split('/')[-1]}.png"
        else:
            f_out = f"{algorithm_name}_{data_.split('/')[-1]}_s{num_samples}.png"
        plt.savefig(
            os.path.join(save_outdir, f_out)
        )
    else:
        n = 0
        if algorithm_name == 'cam':
            f_out = f'cam-{n}.png'
        else:
            f_out = f'{algorithm_name}_s{num_samples}-{n}.png'
        while os.path.exists(
                os.path.join(save_outdir, f_out)
        ):
            n += 1
            if algorithm_name == 'cam':
                f_out = f'cam-{n}.png'
            else:
                f_out = f'{algorithm_name}_s{num_samples}-{n}.png'
            continue
        plt.savefig(
            os.path.join(
                save_outdir, f_out
            )
S
SunAhong1993 已提交
444
        )