@@ -78,7 +78,7 @@ def __init__(
7878 self .learning_rate = learning_rate
7979 self .max_iter = max_iter
8080 self .batch_size = batch_size
81- self ._patch = np .ones ( shape = patch_shape ) * ( self .estimator .clip_values [1 ] + self .estimator .clip_values [0 ]) / 2.0
81+ self ._patch = np .random . randint ( self .estimator .clip_values [0 ], self .estimator .clip_values [1 ], size = patch_shape ). astype ( np . float32 )
8282 self ._check_params ()
8383
8484 self .target_label = []
@@ -87,7 +87,7 @@ def generate(
8787 self ,
8888 x : np .ndarray ,
8989 y : Optional [np .ndarray ] = None ,
90- target_label : Union [int , List [int ], np .ndarray ] = 0 ,
90+ target_label : Optional [ Union [int , List [int ], np .ndarray ]] = None ,
9191 ** kwargs
9292 ) -> np .ndarray :
9393 """
@@ -105,16 +105,17 @@ def generate(
105105 raise ValueError ("The DPatch attack does not use target labels." )
106106 if x .ndim != 4 :
107107 raise ValueError ("The adversarial patch can only be applied to images." )
108- if isinstance (target_label , int ):
109- self .target_label = [target_label ] * x .shape [0 ]
110- elif isinstance (target_label , np .ndarray ):
111- if not (target_label .shape == (x .shape [0 ], 1 ) or target_label .shape == (x .shape [0 ],)):
112- raise ValueError ("The target_label has to be a 1-dimensional array." )
113- self .target_label = target_label .tolist ()
114- else :
115- if not len (target_label ) == x .shape [0 ] or not isinstance (target_label , list ):
116- raise ValueError ("The target_label as list of integers needs to of length number of images in `x`." )
117- self .target_label = target_label
108+ if target_label is not None :
109+ if isinstance (target_label , int ):
110+ self .target_label = [target_label ] * x .shape [0 ]
111+ elif isinstance (target_label , np .ndarray ):
112+ if not (target_label .shape == (x .shape [0 ], 1 ) or target_label .shape == (x .shape [0 ],)):
113+ raise ValueError ("The target_label has to be a 1-dimensional array." )
114+ self .target_label = target_label .tolist ()
115+ else :
116+ if not len (target_label ) == x .shape [0 ] or not isinstance (target_label , list ):
117+ raise ValueError ("The target_label as list of integers needs to of length number of images in `x`." )
118+ self .target_label = target_label
118119
119120 for i_step in trange (self .max_iter , desc = "DPatch iteration" ):
120121 if i_step == 0 or (i_step + 1 ) % 100 == 0 :
@@ -125,19 +126,32 @@ def generate(
125126 )
126127 patch_target : List [Dict [str , np .ndarray ]] = list ()
127128
128- for i_image in range (patched_images .shape [0 ]):
129+ if self .target_label :
130+
131+ for i_image in range (patched_images .shape [0 ]):
132+ i_x_1 = transforms [i_image ]["i_x_1" ]
133+ i_x_2 = transforms [i_image ]["i_x_2" ]
134+ i_y_1 = transforms [i_image ]["i_y_1" ]
135+ i_y_2 = transforms [i_image ]["i_y_2" ]
136+
137+ target_dict = dict ()
138+ target_dict ["boxes" ] = np .asarray ([[i_x_1 , i_y_1 , i_x_2 , i_y_2 ]])
139+ target_dict ["labels" ] = np .asarray ([self .target_label [i_image ], ])
140+ target_dict ["scores" ] = np .asarray ([1.0 , ])
129141
130- i_x_1 = transforms [i_image ]["i_x_1" ]
131- i_x_2 = transforms [i_image ]["i_x_2" ]
132- i_y_1 = transforms [i_image ]["i_y_1" ]
133- i_y_2 = transforms [i_image ]["i_y_2" ]
142+ patch_target .append (target_dict )
134143
135- target_dict = dict ()
136- target_dict ["boxes" ] = np .asarray ([[i_x_1 , i_y_1 , i_x_2 , i_y_2 ]])
137- target_dict ["labels" ] = np .asarray ([self .target_label [i_image ],])
138- target_dict ["scores" ] = np .asarray ([1.0 ,])
144+ else :
139145
140- patch_target .append (target_dict )
146+ predictions = self .estimator .predict (x = patched_images )
147+
148+ for i_image in range (patched_images .shape [0 ]):
149+ target_dict = dict ()
150+ target_dict ["boxes" ] = predictions [i_image ]["boxes" ].detach ().cpu ().numpy ()
151+ target_dict ["labels" ] = predictions [i_image ]["labels" ].detach ().cpu ().numpy ()
152+ target_dict ["scores" ] = predictions [i_image ]["scores" ].detach ().cpu ().numpy ()
153+
154+ patch_target .append (target_dict )
141155
142156 num_batches = math .ceil (x .shape [0 ] / self .batch_size )
143157 patch_gradients = np .zeros_like (self ._patch )
@@ -162,9 +176,13 @@ def generate(
162176 else :
163177 patch_gradients_i = gradients [i_image , i_x_1 :i_x_2 , i_y_1 :i_y_2 , :]
164178
165- patch_gradients += patch_gradients_i
179+ patch_gradients = patch_gradients + patch_gradients_i
180+
181+ if self .target_label :
182+ self ._patch = self ._patch - np .sign (patch_gradients ) * self .learning_rate
183+ else :
184+ self ._patch = self ._patch + np .sign (patch_gradients ) * self .learning_rate
166185
167- self ._patch -= patch_gradients * self .learning_rate
168186 self ._patch = np .clip (
169187 self ._patch , a_min = self .estimator .clip_values [0 ], a_max = self .estimator .clip_values [1 ],
170188 )
0 commit comments