Skip to content

Commit

Permalink
compatible with py2 and py3
Browse files Browse the repository at this point in the history
  • Loading branch information
wuysh committed Feb 20, 2020
1 parent 1a74ebf commit 1bdf303
Show file tree
Hide file tree
Showing 69 changed files with 409 additions and 207 deletions.
1 change: 1 addition & 0 deletions DataPoison/mnist_paddle.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from __future__ import print_function

from builtins import range
import os
import argparse
from PIL import Image
Expand Down
1 change: 1 addition & 0 deletions DataPoison/poison_mnist_paddle.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from __future__ import print_function

from builtins import range
import os
import argparse
from PIL import Image
Expand Down
12 changes: 8 additions & 4 deletions DataPoison/poison_mnist_pytorch.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
import torch
import torchvision
import torch.nn as nn
Expand Down Expand Up @@ -90,7 +94,7 @@ def train(epoch):
if batch_idx % log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
old_div(100. * batch_idx, len(train_loader)), loss.item()))
train_losses.append(loss.item())
train_counter.append(
(batch_idx*64) + ((epoch-1)*len(train_loader.dataset)))
Expand All @@ -111,7 +115,7 @@ def test():
test_losses.append(test_loss)
print('\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
old_div(100. * correct, len(test_loader.dataset))))

# Data poison
poison = Net()
Expand Down Expand Up @@ -154,7 +158,7 @@ def p_test():
test_losses.append(test_loss)
print('\nTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
old_div(100. * correct, len(test_loader.dataset))))

def poi_test():
poison.eval()
Expand All @@ -176,7 +180,7 @@ def poi_test():
test_losses.append(test_loss)
print('\nPoisonTest set: Avg. loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
old_div(100. * correct, len(test_loader.dataset))))

p_test()
for epoch in range(1, n_epochs + 1):
Expand Down
1 change: 1 addition & 0 deletions advbox/adversary.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
adversarial example.
"""
from builtins import object
import numpy as np
import logging
logger=logging.getLogger(__name__)
Expand Down
5 changes: 3 additions & 2 deletions advbox/attacks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@
"""
The base model of the model.
"""
from builtins import object
import logging
from abc import ABCMeta
from abc import abstractmethod

import numpy as np
from future.utils import with_metaclass


class Attack(object):
class Attack(with_metaclass(ABCMeta, object)):
"""
Abstract base class for adversarial attacks. `Attack` represent an
adversarial attack which search an adversarial example. subclass should
Expand All @@ -31,7 +33,6 @@ class Attack(object):
model(Model): an instance of the class advbox.base.Model.
"""
__metaclass__ = ABCMeta

def __init__(self, model):
self.model = model
Expand Down
4 changes: 3 additions & 1 deletion advbox/attacks/cw.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
L2 distance metrics especially
"""
from __future__ import division
from __future__ import print_function

from builtins import range
import logging
import numpy as np

Expand Down Expand Up @@ -153,7 +155,7 @@ def _apply(self,
if self.l2 == None:
self.img_adv = img
adv_label, adv_score = self._predict_adv(self.img_adv)
print ('predict label:', adv_label, 'softmax:', adv_score)
print(('predict label:', adv_label, 'softmax:', adv_score))
# check adversary target if success
self.img_adv = np.squeeze(self.img_adv)
self.img_adv = self.img_adv.reshape(img.shape)
Expand Down
2 changes: 2 additions & 0 deletions advbox/attacks/cw2_pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
L2 distance metrics especially
"""
from __future__ import division
from __future__ import print_function

from builtins import range
import logging
import numpy as np

Expand Down
4 changes: 3 additions & 1 deletion advbox/attacks/deepfool.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
"""
from __future__ import division

from builtins import str
from builtins import range
import logging

import numpy as np
Expand Down Expand Up @@ -75,7 +77,7 @@ def _apply(self, adversary, iterations=100, overshoot=0.02):
gradient = self.model.gradient(adversary.original, pre_label)
x = np.copy(adversary.original)

for iteration in xrange(iterations):
for iteration in range(iterations):
w = np.inf
w_norm = np.inf
pert = np.inf
Expand Down
2 changes: 2 additions & 0 deletions advbox/attacks/gradient_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
"""
from __future__ import division

from builtins import range
import logging
from collections import Iterable

import numpy as np


from .base import Attack
from functools import reduce

__all__ = [
'GradientMethodAttack', 'FastGradientSignMethodAttack', 'FGSM',
Expand Down
1 change: 1 addition & 0 deletions advbox/attacks/lbfgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"""
from __future__ import division

from builtins import range
import logging

import numpy as np
Expand Down
3 changes: 3 additions & 0 deletions advbox/attacks/localsearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
"""
from __future__ import division

from builtins import zip
from builtins import str
from builtins import range
import logging
from collections import Iterable
logger=logging.getLogger(__name__)
Expand Down
5 changes: 3 additions & 2 deletions advbox/attacks/saliency.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""
from __future__ import division

from builtins import range
import logging
import random
import numpy as np
Expand Down Expand Up @@ -74,7 +75,7 @@ def _apply(self,
# count tracks how often each pixel was changed
counts = np.zeros_like(original_image)

labels = range(self.model.num_classes())
labels = list(range(self.model.num_classes()))
adv_img = original_image.copy()
min_, max_ = self.model.bounds()

Expand Down Expand Up @@ -152,7 +153,7 @@ def _generate_random_target(self, original_label):
num_classes = self.model.num_classes()
assert num_random_target <= num_classes - 1

target_labels = random.sample(range(num_classes), num_random_target + 1)
target_labels = random.sample(list(range(num_classes)), num_random_target + 1)
target_labels = [t for t in target_labels if t != original_label]
target_labels = target_labels[:num_random_target]

Expand Down
13 changes: 8 additions & 5 deletions advbox/attacks/tf/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
"""
from __future__ import division
from builtins import range
from past.utils import old_div
import logging
logger=logging.getLogger(__name__)

Expand All @@ -40,21 +43,21 @@ def fgsm(x,
grad, = tf.gradients(loss, x)

if ord == 1:
red_ind = list(xrange(1, len(x.get_shape())))
red_ind = list(range(1, len(x.get_shape())))
avoid_zero_div = 1e-8
avoid_nan_norm = tf.maximum(avoid_zero_div,
reduce_sum(tf.abs(grad),
reduction_indices=red_ind,
keepdims=True))
normalized_grad = grad / avoid_nan_norm
normalized_grad = old_div(grad, avoid_nan_norm)
elif ord == 2:
red_ind = list(xrange(1, len(x.get_shape())))
red_ind = list(range(1, len(x.get_shape())))
avoid_zero_div = 1e-8
square = tf.maximum(avoid_zero_div,
reduce_sum(tf.square(grad),
reduction_indices=red_ind,
keepdims=True))
normalized_grad = grad / tf.sqrt(square)
normalized_grad = old_div(grad, tf.sqrt(square))
else:
normalized_grad = tf.sign(grad)
normalized_grad = tf.stop_gradient(normalized_grad)
Expand All @@ -78,7 +81,7 @@ def deepfool(x,

grad, = tf.gradients(loss, x)

r=grad*loss/tf.reduce_sum(tf.square(grad))
r=old_div(grad*loss,tf.reduce_sum(tf.square(grad)))

#目标是让loss下降
adv_x = x - r
Expand Down
6 changes: 4 additions & 2 deletions advbox/defences/feature_squeezing.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
"""
from __future__ import division
from past.utils import old_div
import logging
logger=logging.getLogger(__name__)

Expand All @@ -40,14 +42,14 @@ def FeatureFqueezingDefence(x, y=None, bit_depth=None, clip_values=(0.0, 1.0)):

#归一化到(0,1)
x_ = x - LB
x_ = x_ / (UB-LB)
x_ = old_div(x_, (UB-LB))

#转换到bit_depth整数
max_value = np.rint(2 ** bit_depth - 1)
res = np.rint(x_ * max_value)

#还原到clip_values范围
res= res/max_value* (UB - LB) + LB
res= old_div(res,max_value)* (UB - LB) + LB

#确保万无一失 clip生效
assert (res <= UB).all() and (res >= LB).all()
Expand Down
3 changes: 2 additions & 1 deletion advbox/defences/thermometer_encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"""
from builtins import range
import logging
logger=logging.getLogger(__name__)

Expand All @@ -37,7 +38,7 @@ def _perchannel(x,num_space):

onehot_rep = to_categorical(pos.reshape(-1), num_space)

for i in reversed(range(1, num_space)):
for i in reversed(list(range(1, num_space))):
onehot_rep[:, i] += np.sum(onehot_rep[:, :i], axis=1)


Expand Down
9 changes: 6 additions & 3 deletions advbox/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@
"""
The base model of the model.
"""
from __future__ import division
from builtins import object
from past.utils import old_div
from abc import ABCMeta
from abc import abstractmethod

import numpy as np
from future.utils import with_metaclass


class Model(object):
class Model(with_metaclass(ABCMeta, object)):
"""
Base class of model to provide attack.
Expand All @@ -31,7 +35,6 @@ class Model(object):
preprocess(tuple): Two element tuple used to preprocess the input.
First substract the first element, then divide the second element.
"""
__metaclass__ = ABCMeta

def __init__(self, bounds, channel_axis, preprocess=None):
assert len(bounds) == 2
Expand Down Expand Up @@ -72,7 +75,7 @@ def _process_input(self, input_):
res = input_ - sub
if not np.all(sub == 1):
if res is None: # "res = input_ - sub" is not executed!
res = input_ / div
res = old_div(input_, div)
else:
res /= div
if res is None: # "res = (input_ - sub)/ div" is not executed!
Expand Down
1 change: 1 addition & 0 deletions advbox/models/keras.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""
from __future__ import absolute_import

from builtins import str
import numpy as np
import os

Expand Down
1 change: 1 addition & 0 deletions advbox/models/pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
Pytorch model
"""
from __future__ import absolute_import
from __future__ import print_function

import numpy as np
import os
Expand Down
2 changes: 2 additions & 0 deletions advbox/models/tensorflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
"""
from __future__ import absolute_import

from builtins import str
from builtins import range
import numpy as np
import os

Expand Down
Loading

0 comments on commit 1bdf303

Please sign in to comment.