コード例 #1
0
def main(argv=None):
    dataObject = data_load.get_appropriate_data(FLAGS.dataset)(None, None)
    datagen = dataObject.data_generator()
    (X_train, Y_train), (X_test, Y_test) = dataObject.get_blackbox_data()
    (X_validation, Y_validation) = dataObject.get_validation_data()
    datagen.fit(X_train)
    n_classes, is_mnist = Y_train.shape[1], (FLAGS.dataset == "mnist")
    if is_mnist:
        model, _ = lenet.lenet_network(n_classes=10, is_mnist=is_mnist)
    else:
        model, _ = resnet.residual_network(n_classes=n_classes,
                                           stack_n=FLAGS.stack_n,
                                           mnist=is_mnist,
                                           get_logits=False)
    attack, attack_params = helpers.get_appropriate_attack(
        FLAGS.dataset,
        dataObject.get_range(),
        FLAGS.attack_name,
        KerasModelWrapper(model),
        common.sess,
        harden=True,
        attack_type="None")
    helpers.customTrainModel(model,
                             X_train,
                             Y_train,
                             X_validation,
                             Y_validation,
                             datagen,
                             FLAGS.nb_epochs,
                             densenet.scheduler,
                             FLAGS.batch_size,
                             attacks=[(attack, attack_params)])
    model.save(FLAGS.save_here)
def main(argv=None):
    dataObject = data_load.get_appropriate_data(FLAGS.dataset)(None, None)
    datagen = dataObject.data_generator()
    atack_X, attack_Y = None, None
    if FLAGS.mode == "harden":
        attack_X, attack_Y = dataObject.get_hardening_data()
    elif FLAGS.mode == "attack":
        attack_X, attack_Y = dataObject.get_attack_data()
    else:
        raise Exception("Invalid mode specified!")
        exit()
    n_classes, model = attack_Y.shape[1], load_model(FLAGS.model)
    attack, attack_params = helpers.get_appropriate_attack(
        FLAGS.dataset,
        dataObject.get_range(),
        FLAGS.attack_name,
        KerasModelWrapper(model),
        common.sess,
        harden=True,
        attack_type="None")
    perturbed_X = helpers.performBatchwiseAttack(attack_X, attack,
                                                 attack_params,
                                                 FLAGS.batch_size)
    fooled_rate = 1 - model.evaluate(
        perturbed_X, attack_Y, batch_size=FLAGS.batch_size)[1]
    print("\nError on adversarial examples: %f" % (fooled_rate))
    if FLAGS.save_here:
        np.save(FLAGS.save_here + "_x.npy", perturbed_X)
        np.save(FLAGS.save_here + "_y.npy", attack_Y)
コード例 #3
0
	def train(self, X_tr, y_tr, X_val, y_val, dataObject, model):
		datagen = dataObject.data_generator()
		datagen.fit(X_tr)
		attacks = FLAGS.attack.split(',')
		if len(attacks) > 1:
			attacks = attacks[1:]
			attack_params = []
			clever_wrapper = KerasModelWrapper(model)
			for attack in attacks:
				attack_params.append(helpers.get_appropriate_attack(FLAGS.dataset, dataObject.get_range(), attack, clever_wrapper, common.sess, harden=True, attack_type="None"))
		else:
			attack_params=None
		def scheduler(epoch):
			if epoch <= 75:
				return 0.1
			if epoch <= 115:
				return 0.01
			return 0.001
		early_stop = None
		if FLAGS.early_stopping:
			print("Early stopping activated")
			early_stop = (0.005, 20) # min_delta, patience
		lr_plateau = None
		if FLAGS.lr_plateau:
			print("Dynamic LR activated")
			lr_plateau = (0.001, 0.1, 10, 0.005) # min_lr, factor, patience, min_delta
		if FLAGS.lr_plateau or FLAGS.early_stopping:
			print("LR scheduler disabled")
			scheduler = None # Override scheduler
		helpers.customTrainModel(model, X_tr, y_tr, X_val, y_val, datagen, self.nb_epochs, scheduler, self.batch_size, attacks=attack_params, early_stop=early_stop, lr_plateau=lr_plateau)
def main(argv=None):
	dataObject = data_load.get_appropriate_data(FLAGS.dataset)(None, None)
	datagen = dataObject.data_generator()
	atack_X, attack_Y = None, None
	if FLAGS.mode == "harden":
		(attack_X, attack_Y), _ = dataObject.get_blackbox_data()
	elif FLAGS.mode == "attack":
		attack_X, attack_Y = dataObject.get_attack_data()
	else:
		raise Exception("Invalid mode specified!")
		exit()
	n_classes = attack_Y.shape[1]
	if FLAGS.dataset == "cifar10":
		keras.backend.set_image_dim_ordering('th')
		attack_X = attack_X.transpose((0, 3, 1, 2))
	model = load_model(FLAGS.model)
	if not FLAGS.multiattacks:
		attack, attack_params = helpers.get_appropriate_attack(FLAGS.dataset, dataObject.get_range(), FLAGS.attack_name ,KerasModelWrapper(model), common.sess, harden=True, attack_type="black")
		perturbed_X = helpers.performBatchwiseAttack(attack_X, attack, attack_params, FLAGS.batch_size)
	else:
		attacks = FLAGS.attack_name.split(',')
		attacks = attacks[1:]
		attack_params = []
		clever_wrapper = KerasModelWrapper(model)
		for attack in attacks:
			attack_params.append(helpers.get_appropriate_attack(FLAGS.dataset, dataObject.get_range(), attack, clever_wrapper, common.sess, harden=True, attack_type="black"))
		attack_Y_shuffled = []
		perturbed_X = []
		attack_indices = np.array_split(np.random.permutation(len(attack_Y)), len(attacks))
		for i, (at, atp) in enumerate(attack_params):
			adv_data = helpers.performBatchwiseAttack(attack_X[attack_indices[i]], at, atp, FLAGS.batch_size)
			perturbed_X.append(adv_data)
			attack_Y_shuffled.append(attack_Y[attack_indices[i]])
		perturbed_X, attack_Y = np.vstack(perturbed_X), np.vstack(attack_Y)
	fooled_rate = 1 - model.evaluate(perturbed_X, attack_Y, batch_size=FLAGS.batch_size)[1]
	print("\nError on adversarial examples: %f" % (fooled_rate))
	if FLAGS.dataset == "cifar10":
		perturbed_X = perturbed_X.transpose((0, 2, 3, 1))
	if FLAGS.save_here:
		np.save(FLAGS.save_here + "_x.npy", perturbed_X)
		np.save(FLAGS.save_here + "_y.npy", attack_Y)
コード例 #5
0
     proxy = load_model(args.save_here)
     K.set_value(proxy.optimizer.lr, args.learning_rate)
 else:
     proxy = cnn.proxy(n_classes=10,
                       mnist=(args.dataset == "mnist"),
                       learning_rate=args.learning_rate)
 channel_mode = "channels_last"
 if args.dataset == "cifar10":
     channel_mode = "channels_first"
 datagen = dataObject.data_generator(channel_mode=channel_mode)
 datagen.fit(x_train)
 attacks = args.attack.split(',')
 if len(attacks) > 1:
     attacks = attacks[1:]
     attack_params = []
     clever_wrapper = KerasModelWrapper(proxy)
     for attack in attacks:
         attack_params.append(
             helpers.get_appropriate_attack(args.dataset,
                                            dataObject.get_range(),
                                            attack,
                                            clever_wrapper,
                                            common.sess,
                                            harden=True,
                                            attack_type="black"))
 else:
     attack_params = None
 helpers.customTrainModel(proxy, x_train, y_train, x_val, y_val, datagen,
                          epochs, None, batch_size, attack_params)
 proxy.save(args.save_here)
 print("Test accuracy %f" % (proxy.evaluate(x_test, y_test)[1]))