I am trying to create an adversarial example using this function:
def create_adversarial_pattern(input_image, input_label):
input_image = tf.cast(input_image, tf.float32)
with tf.GradientTape() as tape:
tape.watch(input_image)
predcition = model(input_image)
loss = loss_object(input_label, prediction)
gradient = tape.gradient(loss, input_image) # <------- this line
signedgrad = tf.sign(gradient)
return signed_grad
but the gradient variable has a value of None which is obviously not great. GradientTape.gradient is supposed to return something. This is the implementation of the function
#load image
image = load_img(test_dir + "0/1-30226-A-0.wav.png")
print("Image: " + str(type(image)))
arr = img_to_array(image)
print("Array No. 1: " + str(type(arr)) + " : " + str(arr.shape))
arr /= 255.0
#predict image
arr_ = []
arr_.append(arr)
arr_ = np.array(arr_)
print("Array No. 2: " + str(type(arr_)) + " : " + str(arr_.shape))
prediction = model.predict(arr_)
image_label = prediction.tolist().index(max(prediction.tolist()))
image_label_arr = []
image_label_arr.append(image_label)
image_label_arr = np.array(image_label_arr)
image_label_arr = tf.keras.utils.to_categorical(image_label_arr, len(classes))
print(classes[image_label] + " : " + str(image_label))
print(image_label_arr)
#create example
perturbations = create_adversarial_pattern(arr.reshape((1, 128, 216, 3)), image_label_arr).numpy
this is the model I am using
def create_model():
model = Sequential()
model.add(Conv2D(32, (3,3), input_shape = array_image.shape))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Conv2D(32, (3, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Conv2D(64, (3, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation("relu"))
model.add(Dropout(0.5))
model.add(Dense(numberOfClass)) #output
model.add(Activation("softmax"))
model.compile(loss = "categorical_crossentropy",
optimizer = "rmsprop",
metrics = ["accuracy"])
return model
I've made some fixes to your code (see the comments inside the code). It should work as expected.
The line
print("grad {}".format(gradient))
gives the following output: