@@ -711,3 +711,176 @@ def forward(self, images, labels):
711711 return adv_images
712712
713713
714+
715+
716+
717+
718+ def auc_MSP_adversarial (model , test_loader , test_attack , device , num_classes ):
719+ is_train = model .training
720+ model .eval ()
721+
722+ soft = torch .nn .Softmax (dim = 1 )
723+ anomaly_scores = []
724+ preds = []
725+ test_labels = []
726+ test_labels_acc = []
727+ with tqdm (test_loader , unit = "batch" ) as tepoch :
728+ torch .cuda .empty_cache ()
729+ for i , (data , target ) in enumerate (tepoch ):
730+ data , target = data .to (device ), target .to (device )
731+ adv_data = test_attack (data , target )
732+
733+ output = model (adv_data )
734+
735+ predictions = output .argmax (dim = 1 , keepdim = True ).squeeze ()
736+ preds += predictions .detach ().cpu ().numpy ().tolist ()
737+
738+ # probs = soft(output).squeeze()
739+ # anomaly_scores += probs[:, num_classes].detach().cpu().numpy().tolist()
740+
741+
742+ probs = soft (output )
743+
744+ max_probabilities ,_ = torch .max (probs [:,:num_classes ] , dim = 1 )
745+
746+
747+
748+
749+ anomaly_scores += max_probabilities .detach ().cpu ().numpy ().tolist ()
750+ # anomaly_scores += probs[:, num_classes].detach().cpu().numpy().tolist()
751+ target = target == num_classes
752+ test_labels += target .detach ().cpu ().numpy ().tolist ()
753+ anomaly_scores = [x * - 1 for x in anomaly_scores ]
754+ auc = roc_auc_score (test_labels , anomaly_scores )
755+
756+ if is_train :
757+ model .train ()
758+ else :
759+ model .eval ()
760+
761+ print (auc )
762+ return auc
763+
764+
765+ class PGD_MSP (Attack ):
766+ r"""
767+ PGD in the paper 'Towards Deep Learning Models Resistant to Adversarial Attacks'
768+ [https://arxiv.org/abs/1706.06083]
769+
770+ Distance Measure : Linf
771+
772+ Arguments:
773+ model (nn.Module): model to attack.
774+ eps (float): maximum perturbation. (Default: 8/255)
775+ alpha (float): step size. (Default: 2/255)
776+ steps (int): number of steps. (Default: 10)
777+ random_start (bool): using random initialization of delta. (Default: True)
778+
779+ Shape:
780+ - images: :math:`(N, C, H, W)` where `N = number of batches`, `C = number of channels`, `H = height` and `W = width`. It must have a range [0, 1].
781+ - labels: :math:`(N)` where each value :math:`y_i` is :math:`0 \leq y_i \leq` `number of labels`.
782+ - output: :math:`(N, C, H, W)`.
783+
784+ Examples::
785+ >>> attack = torchattacks.PGD(model, eps=8/255, alpha=1/255, steps=10, random_start=True)
786+ >>> adv_images = attack(images, labels)
787+
788+ """
789+
790+ def __init__ (self , model , eps = 8 / 255 , alpha = 2 / 255 , steps = 10 , random_start = True , num_classes = 10 ):
791+ super ().__init__ ("PGD" , model )
792+ self .eps = eps
793+ self .alpha = alpha
794+ self .steps = steps
795+ self .random_start = random_start
796+ self .supported_mode = ['default' , 'targeted' ]
797+ self .num_classes = num_classes
798+
799+ def forward (self , images , labels ):
800+ r"""
801+ Overridden.
802+ """
803+
804+ images = images .clone ().detach ().to (self .device )
805+ labels = labels .clone ().detach ().to (self .device )
806+
807+ softmax = nn .Softmax (dim = 1 )
808+ adv_images = images .clone ().detach ()
809+
810+ if self .random_start :
811+ # Starting at a uniformly random point
812+ adv_images = adv_images + \
813+ torch .empty_like (adv_images ).uniform_ (- self .eps , self .eps )
814+ adv_images = torch .clamp (adv_images , min = 0 , max = 1 ).detach ()
815+
816+ ones = torch .ones_like (labels )
817+ multipliers = - 1 * (ones - 2 * ones * (labels == self .num_classes ))
818+
819+ for _ in range (self .steps ):
820+ adv_images .requires_grad = True
821+ outputs = self .get_logits (adv_images )
822+ final_outputs = softmax (outputs )
823+ # choose the value of probability of ood
824+
825+ max_probabilities = torch .max (final_outputs , dim = 1 )[0 ]
826+
827+
828+
829+ cost = torch .sum (max_probabilities * multipliers )
830+
831+
832+
833+ # Update adversarial images
834+ grad = torch .autograd .grad (cost , adv_images ,
835+ retain_graph = False , create_graph = False )[0 ]
836+
837+ adv_images = adv_images .detach () + self .alpha * grad .sign ()
838+ delta = torch .clamp (adv_images - images ,
839+ min = - self .eps , max = self .eps )
840+ adv_images = torch .clamp (images + delta , min = 0 , max = 1 ).detach ()
841+
842+ # imshow(torchvision.utils.make_grid(adv_images.cpu()))
843+ # print(multipliers)
844+ return adv_images
845+
846+
847+
848+
849+
850+ def auc_MSP (model , test_loader , device , num_classes ):
851+ is_train = model .training
852+ model .eval ()
853+
854+ soft = torch .nn .Softmax (dim = 1 )
855+ anomaly_scores = []
856+ preds = []
857+ test_labels = []
858+ test_labels_acc = []
859+
860+ with torch .no_grad ():
861+ with tqdm (test_loader , unit = "batch" ) as tepoch :
862+ torch .cuda .empty_cache ()
863+ for i , (data , target ) in enumerate (tepoch ):
864+ data , target = data .to (device ), target .to (device )
865+ output = model (data )
866+
867+ predictions = output .argmax (dim = 1 , keepdim = True ).squeeze ()
868+ preds += predictions .detach ().cpu ().numpy ().tolist ()
869+
870+ # probs = soft(output).squeeze()
871+ # anomaly_scores += probs[:, num_classes].detach().cpu().numpy().tolist() model
872+
873+ probs = soft (output )
874+ max_probabilities ,_ = torch .max (probs [:,:num_classes ] , dim = 1 )
875+ anomaly_scores += max_probabilities .detach ().cpu ().numpy ().tolist ()
876+ # anomaly_scores += probs[:, num_classes].detach().cpu().numpy().tolist()
877+ target = target == num_classes
878+
879+ test_labels += target .detach ().cpu ().numpy ().tolist ()
880+ anomaly_scores = [x * - 1 for x in anomaly_scores ]
881+ auc = roc_auc_score (test_labels , anomaly_scores )
882+ print (auc )
883+
884+
885+ return auc
886+
0 commit comments