Skip to content

Commit ae33fe1

Browse files
authored
Add files via upload
1 parent 970c74a commit ae33fe1

File tree

2 files changed

+176
-0
lines changed

2 files changed

+176
-0
lines changed

art/evaluations/great_art.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# MIT License
2+
#
3+
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6+
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8+
# persons to whom the Software is furnished to do so, subject to the following conditions:
9+
#
10+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11+
# Software.
12+
#
13+
14+
import numpy as np
15+
import torch
16+
from torch.autograd import Variable
17+
from robustbench.utils import load_model
18+
19+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20+
21+
def great_score(samples, labels, model_name):
22+
"""
23+
Calculate the GREAT score and accuracy for given samples using the specified model.
24+
25+
Args:
26+
samples (np.ndarray): Input samples (images) as a numpy array.
27+
labels (np.ndarray): True labels for the samples.
28+
model_name (str): Name of the model to use for evaluation.
29+
30+
Returns:
31+
tuple: (great_score, accuracy)
32+
"""
33+
# Load the model
34+
model = load_model(model_name=model_name, dataset='cifar10', threat_model='L2').to(device)
35+
36+
# Prepare the data
37+
images = torch.from_numpy(samples).to(device)
38+
labels = torch.from_numpy(labels).to(device)
39+
40+
# Evaluate the model
41+
model.eval()
42+
with torch.no_grad():
43+
outputs = model(images)
44+
45+
# Apply sigmoid and softmax
46+
outputs = torch.sigmoid(outputs)
47+
outputs = torch.softmax(outputs, dim=1)
48+
49+
# Calculate accuracy
50+
predicted_labels = outputs.argmax(dim=1)
51+
correct_predictions = (predicted_labels == labels)
52+
accuracy = correct_predictions.float().mean().item()
53+
54+
# Calculate the GREAT score
55+
great_scores = []
56+
for i in range(len(samples)):
57+
if correct_predictions[i]:
58+
predicted_label = predicted_labels[i]
59+
top2_values, _ = torch.topk(outputs[i], k=2)
60+
difference = (top2_values[0] - top2_values[1]).item()
61+
great_scores.append(difference)
62+
else:
63+
great_scores.append(0)
64+
65+
average_great_score = np.mean(great_scores)
66+
67+
return average_great_score, accuracy
68+

art/evaluations/great_art_test.py

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# MIT License
2+
#
3+
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2024
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6+
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8+
# persons to whom the Software is furnished to do so, subject to the following conditions:
9+
#
10+
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11+
# Software.
12+
#
13+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14+
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
16+
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17+
# SOFTWARE.
18+
19+
from art.defences.evaluation.evasion import great_score
20+
import numpy as np
21+
from scipy import stats
22+
from robustbench.data import load_cifar10
23+
24+
def load_gan_generated_data(n_examples=500):
25+
"""
26+
This function is a placeholder for loading GAN-generated data based on CIFAR10.
27+
In actual implementation, this should be replaced with code to generate or load
28+
GAN-generated samples.
29+
30+
Args:
31+
n_examples (int): Number of examples to generate/load.
32+
33+
Returns:
34+
tuple: (x_test, y_test) where x_test is the generated images and y_test is the corresponding labels.
35+
"""
36+
# NOTE: In actual implementation, replace this with GAN data generation or loading
37+
# For example:
38+
# x_test, y_test = generate_gan_samples(n_examples)
39+
# or
40+
# x_test, y_test = load_gan_samples_from_file('path/to/gan_samples.npz')
41+
42+
print("NOTE: Currently using CIFAR10 data as a placeholder.")
43+
print("In actual implementation, replace this function with GAN-generated data loading.")
44+
45+
x_test, y_test = load_cifar10(n_examples=n_examples)
46+
47+
# Convert to numpy arrays if they aren't already
48+
x_test = x_test.numpy() if hasattr(x_test, 'numpy') else x_test
49+
y_test = y_test.numpy() if hasattr(y_test, 'numpy') else y_test
50+
51+
return x_test, y_test
52+
53+
def test_great_score():
54+
try:
55+
# Load GAN-generated data (currently a placeholder using CIFAR10)
56+
x_test, y_test = load_gan_generated_data(n_examples=500)
57+
58+
# List of models to test
59+
model_list = [
60+
'Rebuffi2021Fixing_70_16_cutmix_extra',
61+
'Gowal2020Uncovering_extra',
62+
'Rebuffi2021Fixing_70_16_cutmix_ddpm',
63+
'Rebuffi2021Fixing_28_10_cutmix_ddpm',
64+
'Augustin2020Adversarial_34_10_extra',
65+
'Sehwag2021Proxy',
66+
'Augustin2020Adversarial_34_10',
67+
'Rade2021Helper_R18_ddpm',
68+
'Rebuffi2021Fixing_R18_cutmix_ddpm',
69+
'Gowal2020Uncovering',
70+
'Sehwag2021Proxy_R18',
71+
'Wu2020Adversarial',
72+
'Augustin2020Adversarial',
73+
'Engstrom2019Robustness',
74+
'Rice2020Overfitting',
75+
'Rony2019Decoupling',
76+
'Ding2020MMA'
77+
]
78+
79+
results = []
80+
81+
for model_name in model_list:
82+
score, accuracy = great_score(x_test, y_test, model_name)
83+
results.append(score)
84+
print(f"Model: {model_name}")
85+
print(f"- GREAT Score: {score:.4f}")
86+
print(f"- Accuracy: {accuracy:.4f}")
87+
print()
88+
89+
# Predefined accuracy values
90+
accuracies = [87.20, 85.60, 90.60, 90.00, 86.20, 89.20, 86.40, 86.60, 87.60, 86.40, 88.60, 84.60, 85.20, 82.20, 81.80, 79.20, 77.60]
91+
92+
# Predefined ranking
93+
rankings = [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
94+
95+
print("Correlation with accuracies:")
96+
print(stats.spearmanr(results, accuracies))
97+
98+
print("\nCorrelation with rankings:")
99+
print(stats.spearmanr(results, rankings))
100+
101+
return results
102+
103+
except Exception as e:
104+
print(f"An error occurred during the execution of test_great_score: {str(e)}")
105+
return None
106+
107+
if __name__ == "__main__":
108+
test_great_score()

0 commit comments

Comments
 (0)