|
| 1 | +from pytest_cases import param_fixture, parametrize, parametrize_with_cases |
| 2 | + |
| 3 | +from alibi_detect.saving.tests.datasets import ContinuousData |
| 4 | +from alibi_detect.saving.tests.models import encoder_model |
| 5 | + |
| 6 | +from alibi_detect.cd.tensorflow import HiddenOutput as HiddenOutput_tf |
| 7 | +from alibi_detect.saving.loading import _load_model_config, _load_optimizer_config |
| 8 | +from alibi_detect.saving.saving import _path2str, _save_model_config |
| 9 | +from alibi_detect.saving.schemas import ModelConfig |
| 10 | + |
| 11 | +backend = param_fixture("backend", ['tensorflow']) |
| 12 | + |
| 13 | + |
| 14 | +def test_load_optimizer_tf(backend): |
| 15 | + "Test the tensorflow _load_optimizer_config." |
| 16 | + class_name = 'Adam' |
| 17 | + learning_rate = 0.01 |
| 18 | + epsilon = 1e-7 |
| 19 | + amsgrad = False |
| 20 | + |
| 21 | + # Load |
| 22 | + cfg_opt = { |
| 23 | + 'class_name': class_name, |
| 24 | + 'config': { |
| 25 | + 'name': class_name, |
| 26 | + 'learning_rate': learning_rate, |
| 27 | + 'epsilon': epsilon, |
| 28 | + 'amsgrad': amsgrad |
| 29 | + } |
| 30 | + } |
| 31 | + optimizer = _load_optimizer_config(cfg_opt, backend=backend) |
| 32 | + assert type(optimizer).__name__ == class_name |
| 33 | + assert optimizer.learning_rate == learning_rate |
| 34 | + assert optimizer.epsilon == epsilon |
| 35 | + assert optimizer.amsgrad == amsgrad |
| 36 | + |
| 37 | + |
| 38 | +@parametrize_with_cases("data", cases=ContinuousData.data_synthetic_nd, prefix='data_') |
| 39 | +@parametrize('model', [encoder_model]) |
| 40 | +@parametrize('layer', [None, -1]) |
| 41 | +def test_save_model_tf(data, model, layer, tmp_path): |
| 42 | + """ |
| 43 | + Unit test for _save_model_config and _load_model_config with tensorflow model. |
| 44 | + """ |
| 45 | + # Save model |
| 46 | + filepath = tmp_path |
| 47 | + input_shape = (data[0].shape[1],) |
| 48 | + cfg_model, _ = _save_model_config(model, base_path=filepath, input_shape=input_shape) |
| 49 | + cfg_model = _path2str(cfg_model) |
| 50 | + cfg_model = ModelConfig(**cfg_model).dict() |
| 51 | + assert tmp_path.joinpath('model').is_dir() |
| 52 | + assert tmp_path.joinpath('model/model.h5').is_file() |
| 53 | + |
| 54 | + # Adjust config |
| 55 | + cfg_model['src'] = tmp_path.joinpath('model') # Need to manually set to absolute path here |
| 56 | + if layer is not None: |
| 57 | + cfg_model['layer'] = layer |
| 58 | + |
| 59 | + # Load model |
| 60 | + model_load = _load_model_config(cfg_model) |
| 61 | + if layer is None: |
| 62 | + assert isinstance(model_load, type(model)) |
| 63 | + else: |
| 64 | + assert isinstance(model_load, HiddenOutput_tf) |
0 commit comments