from relax.data_module import load_data
from relax.ml_model import load_ml_module
VAECF
relax.methods.vaecf.sample_latent
relax.methods.vaecf.sample_latent (rng_key, mean, logvar)
relax.methods.vaecf.VAE
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:
= keras.Input(shape=(37,))
inputs = keras.layers.Dense(32, activation="relu")(inputs)
x = keras.layers.Dense(5, activation="softmax")(x)
outputs = keras.Model(inputs=inputs, outputs=outputs) model
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:
= keras.Input(shape=(None, None, 3))
inputs = keras.layers.RandomCrop(width=128, height=128)(inputs)
processed = keras.layers.Conv2D(filters=32, kernel_size=3)(processed)
conv = keras.layers.GlobalAveragePooling2D()(conv)
pooling = keras.layers.Dense(10)(pooling)
feature
= keras.Model(inputs, feature)
full_model = keras.Model(processed, conv)
backbone = keras.Model(conv, feature) activations
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):
= self.dense1(inputs)
x return self.dense2(x)
= MyModel() model
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):
= self.dense1(inputs)
x = self.dropout(x, training=training)
x return self.dense2(x)
= MyModel() model
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.
= keras.Sequential([
model =(None, None, 3)),
keras.Input(shape=32, kernel_size=3),
keras.layers.Conv2D(filters ])
Parameters:
- layers (
list[int]
) - mc_samples (
<class 'int'>
, default=50) – pred_fn: Callable, - kwargs
relax.methods.vaecf.VAECFConfig
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
class relax.methods.vaecf.VAECF (config=None, vae=None, name=‘VAECF’)
Base class for parametric counterfactual modules.
Methods
set_apply_constraints_fn (apply_constraints_fn)
set_compute_reg_loss_fn (compute_reg_loss_fn)
apply_constraints (*args, **kwargs)
compute_reg_loss (*args, **kwargs)
save (path)
load_from_path (path)
before_generate_cf (*args, **kwargs)
generate_cf (*args, **kwargs)
= load_data('dummy')
dm = load_ml_module('dummy').pred_fn
pred_fn = dm['train']
train_xs, train_ys = dm['test'] test_xs, test_ys
= VAECF() vaecf
=10) vaecf.train(dm, pred_fn, epochs
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>
= vaecf.generate_cf(test_xs[:1], pred_fn, rng_key=jrand.PRNGKey(42)) cf
= 100
n_tests = partial(vaecf.generate_cf, pred_fn=pred_fn)
partial_gen = jax.vmap(partial_gen)(test_xs[:n_tests], rng_key=jrand.split(jrand.PRNGKey(0), n_tests))
cfs
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