Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- img = X_train[12]
- img = np.expand_dims(img, axis=0)
- predictions = cnn_model.predict(img)
- print(predictions[0][0]*100)
- min_pixel = img.reshape((img.shape[1]*img.shape[2], 3)).min(axis=0).min()
- max_pixel = img.reshape((img.shape[1]*img.shape[2], 3)).max(axis=0).max()
- original = X_train[12]
- original = (original - min_pixel) * (255/(max_pixel - min_pixel))
- im = Image.fromarray(original.astype(np.uint8))
- im.save("original-image.png")
- import numpy as np
- from keras import backend as K
- from PIL import Image
- # 0 reprezentuje klasę, którą chcemy otrzymać jako wynik końcowy
- fake_class = 0
- # obrazek do "przekłamania"
- img = X_train[12]
- img = np.expand_dims(img, axis=0)
- hacked_image = np.copy(img)
- # maksymalne zmiany dozwolone na obrazku
- max_change_above = img + 1
- max_change_below = img - 1
- # Stopień aktualizacji obrazka w każdej z interacji
- if fake_class == 0:
- learning_rate = -1
- else:
- learning_rate = 1
- # Pierwsza i ostatnia warstwa sieci neuronowej
- model_input_layer = cnn_model.layers[0].input
- model_output_layer = cnn_model.layers[-1].output
- # Funkcja kosztu
- cost_function = model_output_layer[0, fake_class]
- # Funckcja gradientu
- gradient_function = K.gradients(cost_function, model_input_layer)[0]
- # Funkcja licząca bieżący koszt i gradient
- grab_cost_and_gradients_from_model = K.function([model_input_layer, K.learning_phase()], [cost_function, gradient_function])
- cost = 0.0
- iterator = 0
- while iterator < 10000:
- # Sprawdźmy koszt i gradient
- cost, gradients = grab_cost_and_gradients_from_model([hacked_image, 0])
- # Zmodyfikujmy obraz w celu oszukania modelu
- hacked_image += gradients * learning_rate
- # Sprawdźmy czy obraz nie zmienia się za bardzo
- hacked_image = np.clip(hacked_image, max_change_below, max_change_above)
- # Wypiszmy efekt iteracji
- print(cost * 100)
- iterator += 1
- predictions = cnn_model.predict_classes(hacked_image)
- print("Przewidziana klasa po dokonaniu modyfikacji obrazka: ", predictions[0][0])
- min_pixel = hacked_image.reshape((hacked_image.shape[1]*hacked_image.shape[2], 3)).min(axis=0).min()
- max_pixel = hacked_image.reshape((hacked_image.shape[1]*hacked_image.shape[2], 3)).max(axis=0).max()
- original2 = hacked_image[0]
- original2 = (original2 - min_pixel) * (255/(max_pixel - min_pixel))
- im = Image.fromarray(original2.astype(np.uint8))
- im.save("hacked-image.png")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement