|
| 1 | +from typing import Union |
| 2 | +import inspect |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +from tensorflow.keras.metrics import Metric |
| 6 | +import typeguard |
| 7 | + |
| 8 | + |
| 9 | +@typeguard.typechecked |
| 10 | +def check_metric_serialization( |
| 11 | + metric: Metric, |
| 12 | + y_true: Union[tuple, np.ndarray], |
| 13 | + y_pred: Union[tuple, np.ndarray], |
| 14 | + sample_weight: Union[tuple, np.ndarray, None] = None, |
| 15 | + strict: bool = True, |
| 16 | +): |
| 17 | + config = metric.get_config() |
| 18 | + class_ = metric.__class__ |
| 19 | + |
| 20 | + check_config(config, class_, strict) |
| 21 | + |
| 22 | + metric_copy = class_(**config) |
| 23 | + metric_copy.set_weights(metric.get_weights()) |
| 24 | + |
| 25 | + if isinstance(y_true, tuple): |
| 26 | + y_true = get_random_array(y_true) |
| 27 | + if isinstance(y_pred, tuple): |
| 28 | + y_pred = get_random_array(y_pred) |
| 29 | + if isinstance(sample_weight, tuple) and sample_weight is not None: |
| 30 | + sample_weight = get_random_array(sample_weight) |
| 31 | + |
| 32 | + # the behavior should be the same for the original and the copy |
| 33 | + if sample_weight is None: |
| 34 | + metric.update_state(y_true, y_pred) |
| 35 | + metric_copy.update_state(y_true, y_pred) |
| 36 | + else: |
| 37 | + metric.update_state(y_true, y_pred, sample_weight) |
| 38 | + metric_copy.update_state(y_true, y_pred, sample_weight) |
| 39 | + |
| 40 | + assert_all_arrays_close(metric.get_weights(), metric_copy.get_weights()) |
| 41 | + metric_result = metric.result().numpy() |
| 42 | + metric_copy_result = metric_copy.result().numpy() |
| 43 | + if metric_result != metric_copy_result: |
| 44 | + raise ValueError( |
| 45 | + "The original gave a result of {} after an " |
| 46 | + "`.update_states()` call, but the copy gave " |
| 47 | + "a result of {} after the same " |
| 48 | + "call.".format(metric_result, metric_copy_result) |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def check_config(config, class_, strict): |
| 53 | + init_signature = inspect.signature(class_.__init__) |
| 54 | + |
| 55 | + for parameter_name in init_signature.parameters: |
| 56 | + if parameter_name == "self": |
| 57 | + continue |
| 58 | + elif parameter_name == "args" and strict: |
| 59 | + raise KeyError( |
| 60 | + "Please do not use args in the class constructor of {}, " |
| 61 | + "as it hides the real signature " |
| 62 | + "and degrades the user experience. " |
| 63 | + "If you have no alternative to *args, " |
| 64 | + "use `strict=False` in check_metric_serialization.".format( |
| 65 | + class_.__name__ |
| 66 | + ) |
| 67 | + ) |
| 68 | + elif parameter_name == "kwargs" and strict: |
| 69 | + raise KeyError( |
| 70 | + "Please do not use kwargs in the class constructor of {}, " |
| 71 | + "as it hides the real signature " |
| 72 | + "and degrades the user experience. " |
| 73 | + "If you have no alternative to **kwargs, " |
| 74 | + "use `strict=False` in check_metric_serialization.".format( |
| 75 | + class_.__name__ |
| 76 | + ) |
| 77 | + ) |
| 78 | + if parameter_name not in config: |
| 79 | + raise KeyError( |
| 80 | + "The constructor parameter {} is not present in the config dict " |
| 81 | + "obtained with `.get_config()` of {}. All parameters should be set to " |
| 82 | + "ensure a perfect copy of the keras object can be obtained when " |
| 83 | + "serialized.".format(parameter_name, class_.__name__) |
| 84 | + ) |
| 85 | + |
| 86 | + |
| 87 | +def assert_all_arrays_close(list1, list2): |
| 88 | + for array1, array2 in zip(list1, list2): |
| 89 | + np.testing.assert_allclose(array1, array2) |
| 90 | + |
| 91 | + |
| 92 | +def get_random_array(shape): |
| 93 | + return np.random.uniform(size=shape).astype(np.float32) |
0 commit comments