def test_tf_keras_exception(): bounds = (0, 255) def mean_brightness_net(images): logits = tf.reduce_mean(images, axis=(1, 2)) return logits model = mean_brightness_net with pytest.raises(ValueError): TensorFlowModel.from_keras(model, bounds=bounds) TensorFlowModel.from_keras(model, bounds=bounds, input_shape=(5, 5, 3))
def __init__(self, kmodel, method, criterion): ''' Adversarial Trainingを行うクラス params :kmodel: Kerasモデル(学習済み) :method: foolboxのbatch_attacksモジュール ''' self.kmodel = kmodel self.fmodel = TensorFlowModel.from_keras(kmodel, bounds=(0, 1)) self.criterion = criterion self.method_base = method
def test_tf_keras_constructor(): bounds = (0, 255) def create_model(): data_format = "channels_last" input_shape = [28, 28, 1] l = tf.keras.layers # noqa: E741 max_pool = l.MaxPooling2D((2, 2), (2, 2), padding="same", data_format=data_format) return tf.keras.Sequential([ l.Conv2D( 32, 5, padding="same", data_format=data_format, input_shape=input_shape, activation=tf.nn.relu, ), max_pool, l.Conv2D( 64, 5, padding="same", data_format=data_format, activation=tf.nn.relu, ), max_pool, l.Flatten(), l.Dense(1024, activation=tf.nn.relu), l.Dropout(0.4), l.Dense(10), ]) model = create_model() fmodel = TensorFlowModel.from_keras(model, bounds=bounds) assert fmodel.num_classes() == 10 fmodel.session.run(tf.global_variables_initializer()) test_images = np.random.rand(2, 28, 28, 1).astype(np.float32) assert fmodel.forward(test_images).shape == (2, 10)
def fit(self, x, y, epochs, validation_data=None, batch_size=32, verbose=1): ''' params :x: オリジナルデータ :y: オリジナルラベル :i: イテレーション数 ''' self.x = x self.y = y for i in range(epochs): print(f'\n{i+1} / {epochs} epochs') # rand_idx = np.random.permutation(np.arange(self.x.shape[0])) # 全データのAdversarial Examplesをランダムな順番で作成 rand_idx = np.random.choice( np.arange(self.x.shape[0]), size=batch_size) # 全データ作成している時間がないので、ランダムな10サンプル分を作成 self.fmodel = TensorFlowModel.from_keras(self.kmodel, bounds=(0, 1)) self.method = self.method_base(self.fmodel, criterion=self.criterion) self.adv_imgs, self.orig_cls = [], [] for r_idx in rand_idx: x_adv = self.method(self.x[r_idx], self.y[r_idx], unpack=False) if x_adv.image is None: continue self.adv_imgs.append(x_adv.image) self.orig_cls.append(x_adv.original_class) self.x = np.append(self.x, np.array(self.adv_imgs), axis=0) self.y = np.append(self.y, self.orig_cls) self.kmodel.fit(x=self.x, y=self.y, epochs=1, validation_data=validation_data, verbose=verbose)