3.4. Test models with the xAI evaluatin metrics of th ReVel framework

[12]:
import torch

torch.set_num_threads(1)
from torch.utils.data.dataloader import DataLoader
import tqdm
import numpy as np
import json
import argparse
import pandas as pd
import os

from ReVel.LLEs import get_xai_model
from ReVel.perturbations import get_perturbation
from ReVel.load_data import load_data
from ReVel.revel.revel import ReVel
import TSHIELD.procedures as procedures
device = "cpu"

n_class = 102
ds = "Flowers"
iterations = 5
batch_size = 32
max_examples = 500
samples = 10
sigma = 12
xai_model = "LIME"
dim = 8

csv_file = "./metrics.csv"
perturbation = get_perturbation(
    name="square", dim=dim, num_classes=n_class, final_size=(224, 224)
)
Test = load_data(ds, perturbation=perturbation, train=False, dir="./data")
# Hacer que Test tenga solo las primeras 'samples' de Test
if isinstance(samples, int):
    indices = np.random.choice(
        [i for i in range(len(Test))], size=samples, replace=False
    )
    Test = torch.utils.data.Subset(Test, indices)

TestLoader = iter(DataLoader(Test, batch_size=1, shuffle=False))
classifier = procedures.classifier("efficientnet-b2", n_class)
classifier.to(device)


state_dict = torch.load(
    f'{os.getcwd()}/model.pth',
    map_location=device,
)

classifier.load_state_dict(state_dict)
classifier.to(device)
classifier.eval()
print("Loaded the pretrained model.")
Loaded the pretrained model.
/tmp/ipykernel_93584/3587458112.py:46: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.
  state_dict = torch.load(

3.5. REVEL metrics calculation for a model trained on the Flowers dataset

[ ]:
index = 0
for data in tqdm.tqdm(TestLoader, total=len(TestLoader)):#len(TestLoader)):
    inputs, labels = data
    for k, inp in enumerate(inputs):
        inp = inp.to(device)

        # inp dims: (C,H,W) -> (H,W,C)
        inp = np.transpose(inp, (1, 2, 0))

        labels = labels[k].to(device)
        explainer = get_xai_model(
            name=xai_model,
            perturbation=perturbation,
            max_examples=max_examples,
            dim=dim,
            sigma=sigma,
        )
        def classify(image, model=classifier):
            """
            This function takes an image and returns the predicted probabilities.
            :param image: A tensor of shape HxWxC
            :return: A tensor of shape Cx1
            """
            if isinstance(image, np.ndarray):
                image = np.expand_dims(image, 0)

                image = torch.Tensor(image).to(device)

            else:
                image = torch.unsqueeze(image, 0)

            # image dims: (N,H,W,C) -> (N,C,H,W)

            image = torch.transpose(image, 3, 2).transpose(2, 1)

            result = model(image)
            return result
        def model_fordward(
                X: np.array, explainator=explainer, model=classify, img=inp
            ):
            neutral = explainator.perturbation.fn_neutral_image(img)

            avoid = [i for i in range(len(X)) if X[i] == 0]

            segments = explainator.perturbation.segmentation_fn(img.numpy())
            perturbation = explainator.perturbation.perturbation(
                img, neutral, segments=segments, indexes=avoid
            )
            return model(perturbation)
        segments = explainer.perturbation.segmentation_fn(inp.numpy())

        revel = ReVel(
            model_f=classify,
            model_g=model_fordward,
            instance=inp,
            lle=explainer,
            n_classes=n_class,
            segments=segments,
        )
        df = revel.evaluate(times=iterations)
        df.loc[:, "dataset"] = ds
        df.loc[:, "name"] = "SHIELD"
        df.loc[:, "index"] = index
        index+=1
        if os.path.exists(csv_file):
            bigDF = pd.read_csv(csv_file)
            bigDF = pd.concat([bigDF, df])
        else:
            bigDF = df
        bigDF.to_csv(csv_file, index=False)
[17]:
display(bigDF.head(10))

conciseness local_fidelity local_concordance prescriptivity robustness dataset name index
0 0.592374 0.968821 0.948301 0.986014 0.900298 Flowers SHIELD 0
1 0.575238 0.970056 0.950214 0.986120 0.900298 Flowers SHIELD 0
2 0.621403 0.971654 0.953586 0.982834 0.900298 Flowers SHIELD 0
3 0.656200 0.968553 0.948588 0.986866 0.900298 Flowers SHIELD 0
4 0.555271 0.966748 0.944305 0.988516 0.900298 Flowers SHIELD 0
5 0.718255 0.974289 0.955635 0.983946 0.905916 Flowers SHIELD 1
6 0.697398 0.970710 0.950923 0.980930 0.905916 Flowers SHIELD 1
7 0.690674 0.975697 0.957971 0.980183 0.905916 Flowers SHIELD 1
8 0.687614 0.963620 0.938403 0.978476 0.905916 Flowers SHIELD 1
9 0.668301 0.974379 0.956623 0.981830 0.905916 Flowers SHIELD 1