VAECF

relax.methods.vaecf.sample_latent

[source]

relax.methods.vaecf.sample_latent (rng_key, mean, logvar)

relax.methods.vaecf.VAE

[source]

class relax.methods.vaecf.VAE (layers, mc_samples=50, **kwargs)

A model grouping layers into an object with training/inference features.

There are three ways to instantiate a Model:

With the “Functional API”

You start from Input, you chain layer calls to specify the model’s forward pass, and finally you create your model from inputs and outputs:

inputs = keras.Input(shape=(37,))
x = keras.layers.Dense(32, activation="relu")(inputs)
outputs = keras.layers.Dense(5, activation="softmax")(x)
model = keras.Model(inputs=inputs, outputs=outputs)

Note: Only dicts, lists, and tuples of input tensors are supported. Nested inputs are not supported (e.g. lists of list or dicts of dict).

A new Functional API model can also be created by using the intermediate tensors. This enables you to quickly extract sub-components of the model.

Example:

inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=128, height=128)(inputs)
conv = keras.layers.Conv2D(filters=32, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)

full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)

Note that the backbone and activations models are not created with keras.Input objects, but with the tensors that originate from keras.Input objects. Under the hood, the layers and weights will be shared across these models, so that user can train the full_model, and use backbone or activations to do feature extraction. The inputs and outputs of the model can be nested structures of tensors as well, and the created models are standard Functional API models that support all the existing APIs.

By subclassing the Model class

In that case, you should define your layers in __init__() and you should implement the model’s forward pass in call().

class MyModel(keras.Model):
    def __init__(self):
        super().__init__()
        self.dense1 = keras.layers.Dense(32, activation="relu")
        self.dense2 = keras.layers.Dense(5, activation="softmax")

    def call(self, inputs):
        x = self.dense1(inputs)
        return self.dense2(x)

model = MyModel()

If you subclass Model, you can optionally have a training argument (boolean) in call(), which you can use to specify a different behavior in training and inference:

class MyModel(keras.Model):
    def __init__(self):
        super().__init__()
        self.dense1 = keras.layers.Dense(32, activation="relu")
        self.dense2 = keras.layers.Dense(5, activation="softmax")
        self.dropout = keras.layers.Dropout(0.5)

    def call(self, inputs, training=False):
        x = self.dense1(inputs)
        x = self.dropout(x, training=training)
        return self.dense2(x)

model = MyModel()

Once the model is created, you can config the model with losses and metrics with model.compile(), train the model with model.fit(), or use the model to do prediction with model.predict().

With the Sequential class

In addition, keras.Sequential is a special case of model where the model is purely a stack of single-input, single-output layers.

model = keras.Sequential([
    keras.Input(shape=(None, None, 3)),
    keras.layers.Conv2D(filters=32, kernel_size=3),
])

Parameters:

  • layers (list[int])
  • mc_samples (<class 'int'>, default=50) – pred_fn: Callable,
  • kwargs

relax.methods.vaecf.VAECFConfig

[source]

class relax.methods.vaecf.VAECFConfig (layers=[20, 16, 14, 12, 5], dropout_rate=0.1, opt_name=‘adam’, lr=0.001, mc_samples=50, validity_reg=42.0)

Configurator of VAECFModule.

Parameters:

  • layers (List[int], default=[20, 16, 14, 12, 5]) – Sequence of Encoder/Decoder layer sizes.
  • dropout_rate (float, default=0.1) – Dropout rate.
  • opt_name (str, default=adam) – Optimizer name.
  • lr (float, default=0.001) – Learning rate.
  • mc_samples (int, default=50) – Number of samples for mu.
  • validity_reg (float, default=42.0) – Regularization for validity.

relax.methods.vaecf.VAECF

[source]

class relax.methods.vaecf.VAECF (config=None, vae=None, name=‘VAECF’)

Base class for parametric counterfactual modules.

Methods

[source]

set_apply_constraints_fn (apply_constraints_fn)

[source]

set_compute_reg_loss_fn (compute_reg_loss_fn)

[source]

apply_constraints (*args, **kwargs)

[source]

compute_reg_loss (*args, **kwargs)

[source]

save (path)

[source]

load_from_path (path)

[source]

before_generate_cf (*args, **kwargs)

generate_cf (*args, **kwargs)

from relax.data_module import load_data
from relax.ml_model import load_ml_module
dm = load_data('dummy')
pred_fn = load_ml_module('dummy').pred_fn
train_xs, train_ys = dm['train']
test_xs, test_ys = dm['test']
vaecf = VAECF()
vaecf.train(dm, pred_fn, epochs=10)
Epoch 1/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 15s 2s/step - loss: 10.8419
Epoch 2/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 36ms/step - loss: 7.9748
Epoch 3/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 36ms/step - loss: 6.1708
Epoch 4/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 35ms/step - loss: 5.1577
Epoch 5/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 38ms/step - loss: 4.3424
Epoch 6/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 35ms/step - loss: 3.7982
Epoch 7/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 36ms/step - loss: 3.3180
Epoch 8/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 38ms/step - loss: 2.9390
Epoch 9/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 36ms/step - loss: 2.6337
Epoch 10/10
6/6 ━━━━━━━━━━━━━━━━━━━━ 0s 36ms/step - loss: 2.3621
<__main__.VAECF>
cf = vaecf.generate_cf(test_xs[:1], pred_fn, rng_key=jrand.PRNGKey(42))
n_tests = 100
partial_gen = partial(vaecf.generate_cf, pred_fn=pred_fn)
cfs = jax.vmap(partial_gen)(test_xs[:n_tests], rng_key=jrand.split(jrand.PRNGKey(0), n_tests))

assert cfs.shape == test_xs[:100].shape

print("Validity: ", keras.metrics.binary_accuracy(
    (1 - pred_fn(test_xs[:100])).round(),
    pred_fn(cfs[:, :])
).mean())
Validity:  0.55