def init_ad_ae(state_dict: Dict, ae: tf.keras.Model, model: tf.keras.Model, model_hl: List[tf.keras.Model]) -> AdversarialAE: """ Initialize AdversarialAE. Parameters ---------- state_dict Dictionary containing the parameter values. ae Loaded VAE. model Loaded classification model. model_hl List of tf.keras models. Returns ------- Initialized AdversarialAE instance. """ ad = AdversarialAE(threshold=state_dict['threshold'], ae=ae, model=model, model_hl=model_hl, w_model_hl=state_dict['w_model_hl'], temperature=state_dict['temperature']) return ad
def test_adv_vae(adv_ae_params): # AdversarialAE parameters threshold, w_model, w_recon, threshold_perc, return_instance_score = adv_ae_params # define encoder and decoder encoder_net = tf.keras.Sequential( [ InputLayer(input_shape=(input_dim,)), Dense(5, activation=tf.nn.relu), Dense(latent_dim, activation=None) ] ) decoder_net = tf.keras.Sequential( [ InputLayer(input_shape=(latent_dim,)), Dense(5, activation=tf.nn.relu), Dense(input_dim, activation=tf.nn.sigmoid) ] ) # init OutlierVAE advae = AdversarialAE( threshold=threshold, model=model, encoder_net=encoder_net, decoder_net=decoder_net ) assert advae.threshold == threshold assert advae.meta == {'name': 'AdversarialAE', 'detector_type': 'offline', 'data_type': None, 'version': __version__} for layer in advae.model.layers: assert not layer.trainable # fit AdversarialVAE, infer threshold and compute scores advae.fit(X, w_model=w_model, w_recon=w_recon, epochs=5, verbose=False) advae.infer_threshold(X, threshold_perc=threshold_perc) iscore = advae.score(X) perc_score = 100 * (iscore < advae.threshold).astype(int).sum() / iscore.shape[0] assert threshold_perc + 1 > perc_score > threshold_perc - 1 # make and check predictions ad_preds = advae.predict(X, return_instance_score=return_instance_score) assert ad_preds['meta'] == advae.meta if return_instance_score: assert ad_preds['data']['is_adversarial'].sum() == (ad_preds['data']['instance_score'] > advae.threshold).astype(int).sum() else: assert ad_preds['data']['instance_score'] is None
Dense(10, activation=tf.nn.relu), Dense(n_gmm, activation=tf.nn.softmax) ]) threshold_net = tf.keras.Sequential([ InputLayer(input_shape=(seq_len, latent_dim)), Dense(5, activation=tf.nn.relu) ]) # define model inputs = tf.keras.Input(shape=(input_dim, )) outputs = tf.keras.layers.Dense(2, activation=tf.nn.softmax)(inputs) model = tf.keras.Model(inputs=inputs, outputs=outputs) detector = [ AdversarialAE(threshold=threshold, model=model, **kwargs), IForest(threshold=threshold), Mahalanobis(threshold=threshold), OutlierAEGMM(threshold=threshold, gmm_density_net=gmm_density_net, n_gmm=n_gmm, **kwargs), OutlierVAE(threshold=threshold, latent_dim=latent_dim, samples=samples, **kwargs), OutlierAE(threshold=threshold, **kwargs), OutlierVAEGMM(threshold=threshold, gmm_density_net=gmm_density_net, n_gmm=n_gmm, latent_dim=latent_dim,