Skip to content

Synthesis Validation

For synthesis validation we have only feature based evaluation metrics.

Feature-based

Quality

pymdma.image.measures.synthesis_val.GIQA

Generated Image Quality Assessment (GIQA) metric based on Gaussian Mixture Model (GMM). By default, computes the Quality score (QS) as reported in the paper.

To compute the Diversity score (DS), exchange the real and synthetic features. The instance level result will indicate, for each real sample, how well it is represented in the synthetic distribution. The dataset level result will indicate the overal diversity score as defined in the paper.

Objective: Quality, Diversity

Parameters:

Name Type Description Default
n_components int

Number of components in the GMM. Defaults to 7.

7
covariance_type str

Type of covariance. Defaults to "full".

'full'
cache_model bool

If set to true the GMM model will only be fitted once and then cached. Defaults to False. Only set to True if the reference features are constant across all calls to the compute method.

False
random_state int

Random seed. Defaults to 0.

0
**kwargs dict

Additional keyword arguments to be used by the GMM model.

{}
References

Gu et al., GIQA: Generated Image Quality Assessment (2020). https://arxiv.org/abs/2003.08932

GIQA, GIQA: Generated Image Quality Assessment https://github.com/cientgu/GIQA

Examples:

>>> giqa = GIQA()
>>> x_feats = np.random.rand(100, 100)
>>> y_feats = np.random.rand(100, 100)
>>> quality_score: MetricResult = giqa.compute(x_feats, y_feats)
>>> diversity_score: MetricResult = giqa.compute(y_feats, x_feats)
Source code in src/pymdma/image/measures/synthesis_val/feature/giqa.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
class GIQA(FeatureMetric):
    """Generated Image Quality Assessment (GIQA) metric based on Gaussian
    Mixture Model (GMM). By default, computes the Quality score (QS) as
    reported in the paper.

    To compute the Diversity score (DS), exchange the real and synthetic features.
    The instance level result will indicate, for each real sample, how well it
    is represented in the synthetic distribution. The dataset level result will
    indicate the overal diversity score as defined in the paper.

    **Objective**: Quality, Diversity

    Parameters
    ----------
    n_components : int, optional
        Number of components in the GMM. Defaults to 7.
    covariance_type : str, optional
        Type of covariance. Defaults to "full".
    cache_model : bool, optional
        If set to true the GMM model will only be fitted once and then cached. Defaults to False.
        Only set to True if the reference features are constant across all calls to the compute method.
    random_state : int, optional
        Random seed. Defaults to 0.
    **kwargs : dict, optional
        Additional keyword arguments to be used by the GMM model.

    References
    ----------
    Gu et al., GIQA: Generated Image Quality Assessment (2020).
    https://arxiv.org/abs/2003.08932

    GIQA, GIQA: Generated Image Quality Assessment
    https://github.com/cientgu/GIQA

    Examples
    --------
    >>> giqa = GIQA()
    >>> x_feats = np.random.rand(100, 100)
    >>> y_feats = np.random.rand(100, 100)
    >>> quality_score: MetricResult = giqa.compute(x_feats, y_feats)
    >>> diversity_score: MetricResult = giqa.compute(y_feats, x_feats)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = [EvaluationLevel.INSTANCE, EvaluationLevel.DATASET]
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = True
    min_value: float = 0.0
    max_value: float = 1.0

    def __init__(
        self,
        n_components: int = 7,
        covariance_type: Literal["full", "tied", "diag", "spherical"] = "full",
        cache_model: bool = False,
        random_state: int = 0,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.n_components = n_components
        self.covariance_type = covariance_type
        self.cache_model = cache_model

        self._mixture_model = GaussianMixture(
            n_components=self.n_components,
            covariance_type=self.covariance_type,
            verbose=0,
            random_state=random_state,
            **kwargs,
        )
        self._fitted = False

    def compute(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> MetricResult:
        """Compute the GIQA metric.

        Parameters
        ----------
        real_features : np.ndarray
            ndarray of shape (n_samples, n_features) containing features of real samples.

        fake_features : np.ndarray
            ndarray of shape (n_samples, n_features) containing features of fake/generated samples.

        Returns
        -------
        result : MetricResult
            dataset-level mean of the scores and instance-level scores
        """
        # fit GMM model on real features
        if not self._fitted or (self._fitted and not self.cache_model):
            self._mixture_model.fit(real_features.astype(np.float64))
            self._fitted = True
        # compute scores for fake features
        scores = self._mixture_model.score_samples(fake_features.astype(np.float64))
        scores = min_max_scaling(scores)

        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": scores.mean()},
            instance_level={"dtype": OutputsTypes.ARRAY, "subtype": "float", "value": scores.tolist()},
        )

pymdma.image.measures.synthesis_val.ImprovedPrecision

Improved Precision Metric for accessing fidelity of generative models.

Objective: Fidelity

Parameters:

Name Type Description Default
k int

Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.

5
metric str

The metric to use when calculating distance between instances. For the available metrics, see the documentation of sklearn.metrics.pairwise_distances.

"euclidean"
n_workers int

Number of workers for computing pairwise distances. Defaults to 4.

4
**kwargs

Additional keyword arguments for compatiblilty.

{}
References

Kynkaanniemi et al., Improved Precision and Recall Metric for Assessing Generative Models (2019). https://arxiv.org/abs/1904.06991

Code adapted from: improved-precision-and-recall-metric: Improved Precision and Recall Metric for Assessing Generative Models — Official TensorFlow Implementation. https://github.com/kynkaat/improved-precision-and-recall-metric

Hypersphere estimation code was taken from: generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models. https://github.com/clovaai/generative-evaluation-prdc

Examples:

>>> improved_precision = ImprovedPrecision()
>>> real_features = np.random.rand(100, 100)
>>> fake_features = np.random.rand(100, 100)
>>> result: MetricResult = improved_precision.compute(real_features, fake_features)
Source code in src/pymdma/general/measures/prdc.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
class ImprovedPrecision(FeatureMetric):
    """Improved Precision Metric for accessing fidelity of generative models.

    **Objective**: Fidelity

    Parameters
    ----------
    k : int, optional
        Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.
    metric : str, optional, default="euclidean"
        The metric to use when calculating distance between instances.
        For the available metrics, see the documentation of `sklearn.metrics.pairwise_distances`.
    n_workers : int, optional
        Number of workers for computing pairwise distances. Defaults to 4.
    **kwargs
        Additional keyword arguments for compatiblilty.

    References
    ----------
    Kynkaanniemi et al., Improved Precision and Recall Metric for Assessing Generative Models (2019).
    https://arxiv.org/abs/1904.06991

    Code adapted from:
    improved-precision-and-recall-metric: Improved Precision and Recall Metric for Assessing Generative Models — Official TensorFlow Implementation.
    https://github.com/kynkaat/improved-precision-and-recall-metric

    Hypersphere estimation code was taken from:
    generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models.
    https://github.com/clovaai/generative-evaluation-prdc

    Examples
    --------
    >>> improved_precision = ImprovedPrecision()
    >>> real_features = np.random.rand(100, 100)
    >>> fake_features = np.random.rand(100, 100)
    >>> result: MetricResult = improved_precision.compute(real_features, fake_features)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = [EvaluationLevel.INSTANCE, EvaluationLevel.DATASET]
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = True
    min_value: float = 0.0
    max_value: float = 1.0

    def __init__(
        self,
        k: int = 5,
        metric: str = "euclidean",
        n_workers: int = 4,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.k = k
        self.metric = metric
        self.n_workers = n_workers

    def compute(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> MetricResult:
        """Compute the Improved Precision metric.

        Parameters
        ----------
        real_features : np.ndarray
            Array of shape (n_samples, n_features) containing the real features.
        fake_features : np.ndarray
            Array of shape (n_samples, n_features) containing the fake features.

        Notes
        -----
        Intermediate computations can be stored in the `context` dictionary of the `kwargs` parameter.
        Usefull when calculating multiple metrics that share the same intermediate computations.

        Returns
        -------
        result: MetricResult
            Dataset-level and instance-level results for the precision metric.
        """
        state = kwargs.get("context", {})
        if "real_nn_distances" not in state:
            state["real_nn_distances"] = compute_nearest_neighbour_distances(
                real_features,
                nearest_k=self.k,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        if "real_fake_distances" not in state:
            state["real_fake_distances"] = compute_pairwise_distance(
                real_features,
                fake_features,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        precision = (
            np.logical_or(
                (state["real_fake_distances"] < np.expand_dims(state["real_nn_distances"], axis=1)),
                np.isclose(state["real_fake_distances"], np.expand_dims(state["real_nn_distances"], axis=1)),
            )
            .any(axis=0)
            .astype(int)
        )

        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": precision.mean()},
            instance_level={"dtype": OutputsTypes.ARRAY, "subtype": "int", "value": precision.tolist()},
        )

pymdma.image.measures.synthesis_val.ImprovedRecall

Improved Recall Metric for accessing diversity of generative models.

Objective: Diversity

Parameters:

Name Type Description Default
k int

Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.

5
metric str

The metric to use when calculating distance between instances. For the available metrics, see the documentation of sklearn.metrics.pairwise_distances.

"euclidean"
n_workers int

Number of workers for computing pairwise distances. Defaults to 4.

4
**kwargs

Additional keyword arguments for compatiblilty.

{}
References

Kynkaanniemi et al., Improved Precision and Recall Metric for Assessing Generative Models (2019). https://arxiv.org/abs/1904.06991

Code adapted from: improved-precision-and-recall-metric: Improved Precision and Recall Metric for Assessing Generative Models — Official TensorFlow Implementation. https://github.com/kynkaat/improved-precision-and-recall-metric

Hypersphere estimation code was taken from: generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models. https://github.com/clovaai/generative-evaluation-prdc

Examples:

>>> improved_recall = ImprovedRecall()
>>> real_features = np.random.rand(100, 100)
>>> fake_features = np.random.rand(100, 100)
>>> result: MetricResult = improved_recall.compute(real_features, fake_features)
Source code in src/pymdma/general/measures/prdc.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
class ImprovedRecall(FeatureMetric):
    """Improved Recall Metric for accessing diversity of generative models.

    **Objective**: Diversity

    Parameters
    ----------
    k : int, optional
        Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.
    metric : str, optional, default="euclidean"
        The metric to use when calculating distance between instances.
        For the available metrics, see the documentation of `sklearn.metrics.pairwise_distances`.
    n_workers : int, optional
        Number of workers for computing pairwise distances. Defaults to 4.
    **kwargs
        Additional keyword arguments for compatiblilty.

    References
    ----------
    Kynkaanniemi et al., Improved Precision and Recall Metric for Assessing Generative Models (2019).
    https://arxiv.org/abs/1904.06991

    Code adapted from:
    improved-precision-and-recall-metric: Improved Precision and Recall Metric for Assessing Generative Models — Official TensorFlow Implementation.
    https://github.com/kynkaat/improved-precision-and-recall-metric

    Hypersphere estimation code was taken from:
    generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models.
    https://github.com/clovaai/generative-evaluation-prdc

    Examples
    --------
    >>> improved_recall = ImprovedRecall()
    >>> real_features = np.random.rand(100, 100)
    >>> fake_features = np.random.rand(100, 100)
    >>> result: MetricResult = improved_recall.compute(real_features, fake_features)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = [EvaluationLevel.INSTANCE, EvaluationLevel.DATASET]
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = True
    min_value: float = 0.0
    max_value: float = 1.0

    def __init__(
        self,
        k: int = 5,
        metric: str = "euclidean",
        n_workers: int = 4,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.k = k
        self.metric = metric
        self.n_workers = n_workers

    def compute(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> MetricResult:
        """Compute the Improved Recall metric.

        Parameters
        ----------
        real_features : np.ndarray
            Array of shape (n_samples, n_features) containing the real features.
        fake_features : np.ndarray
            Array of shape (n_samples, n_features) containing the fake features.

        Notes
        -----
        Intermediate computations can be stored in the `context` dictionary of the `kwargs` parameter.
        Usefull when calculating multiple metrics that share the same intermediate computations.

        Returns
        -------
        result: MetricResult
            Dataset-level and instance-level results for the recall metric.
        """
        state = kwargs.get("context", {})
        if "fake_nn_distances" not in state:
            state["fake_nn_distances"] = compute_nearest_neighbour_distances(
                fake_features,
                nearest_k=self.k,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        if "real_fake_distances" not in state:
            state["real_fake_distances"] = compute_pairwise_distance(
                real_features,
                fake_features,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        recall_mask = np.logical_or(
            state["real_fake_distances"] < np.expand_dims(state["fake_nn_distances"], axis=0),
            np.isclose(state["real_fake_distances"], np.expand_dims(state["fake_nn_distances"], axis=0)),
        )
        recall = recall_mask.any(axis=1).astype(int)

        # matrix with (R, F) shape -> .any() -> matrix with (F,) shape
        # an array that indicates for each F sample how many real samples are within its manifold
        recall_counts = recall_mask.sum(axis=0)

        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": recall.mean()},
            instance_level={"dtype": OutputsTypes.ARRAY, "subtype": "int", "value": recall_counts.tolist()},
        )

pymdma.image.measures.synthesis_val.Density

Density Metric for accessing fidelity of the generated samples. Unlike Improved Precision, it is robust towards outliers in the real/reference data.

Objective: Fidelity

Parameters:

Name Type Description Default
k int

Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.

5
metric str

The metric to use when calculating distance between instances. For the available metrics, see the documentation of sklearn.metrics.pairwise_distances.

"euclidean"
n_workers int

Number of workers for computing pairwise distances. Defaults to 4.

4
**kwargs

Additional keyword arguments for compatibility.

{}
References

Naeem et al., Reliable Fidelity and Diversity Metrics for Generative Models (2020). https://arxiv.org/abs/2002.09797

Code was adapted from: generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models. https://github.com/clovaai/generative-evaluation-prdc

Examples:

>>> density = Density()
>>> real_features = np.random.rand(100, 100)
>>> fake_features = np.random.rand(100, 100)
>>> result: MetricResult = density.compute(real_features, fake_features)
Source code in src/pymdma/general/measures/prdc.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
class Density(FeatureMetric):
    """Density Metric for accessing fidelity of the generated samples. Unlike
    Improved Precision, it is robust towards outliers in the real/reference
    data.

    **Objective**: Fidelity

    Parameters
    ----------
    k : int, optional
        Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.
    metric : str, optional, default="euclidean"
        The metric to use when calculating distance between instances.
        For the available metrics, see the documentation of `sklearn.metrics.pairwise_distances`.
    n_workers : int, optional
        Number of workers for computing pairwise distances. Defaults to 4.
    **kwargs
        Additional keyword arguments for compatibility.

    References
    ----------
    Naeem et al., Reliable Fidelity and Diversity Metrics for Generative Models (2020).
    https://arxiv.org/abs/2002.09797

    Code was adapted from:
    generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models.
    https://github.com/clovaai/generative-evaluation-prdc

    Examples
    --------
    >>> density = Density()
    >>> real_features = np.random.rand(100, 100)
    >>> fake_features = np.random.rand(100, 100)
    >>> result: MetricResult = density.compute(real_features, fake_features)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = [EvaluationLevel.INSTANCE, EvaluationLevel.DATASET]
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = True
    min_value: float = 0.0
    max_value: float = 1.0

    def __init__(
        self,
        k: int = 5,
        metric: str = "euclidean",
        n_workers: int = 4,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.k = k
        self.metric = metric
        self.n_workers = n_workers

    def compute(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> MetricResult:
        """Compute the Density metric.

        Parameters
        ----------
        real_features : np.ndarray
            Array of shape (n_samples, n_features) containing the real features.
        fake_features : np.ndarray
            Array of shape (n_samples, n_features) containing the fake features.

        Notes
        -----
        Intermediate computations can be stored in the `context` dictionary of the `kwargs` parameter.
        Usefull when calculating multiple metrics that share the same intermediate computations.

        Returns
        -------
        result: MetricResult
            Dataset-level and instance-level results for the density metric.
        """
        state = kwargs.get("context", {})
        if "real_nn_distances" not in state:
            state["real_nn_distances"] = compute_nearest_neighbour_distances(
                real_features,
                nearest_k=self.k,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        if "real_fake_distances" not in state:
            state["real_fake_distances"] = compute_pairwise_distance(
                real_features,
                fake_features,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        density = np.logical_or(
            (state["real_fake_distances"] < np.expand_dims(state["real_nn_distances"], axis=1)),
            np.isclose(state["real_fake_distances"], np.expand_dims(state["real_nn_distances"], axis=1)),
        )
        density = (1.0 / float(self.k)) * density.sum(axis=0)

        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": density.mean()},
            instance_level={"dtype": OutputsTypes.ARRAY, "subtype": "float", "value": density.tolist()},
        )

pymdma.image.measures.synthesis_val.Coverage

Coverage Metric for accessing diversity of the generated samples. Unlike Improved Recall, it is robust towards outliers in the real/reference data.

Objective: Diversity

Parameters:

Name Type Description Default
k int

Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.

5
metric str

The metric to use when calculating distance between instances. For the available metrics, see the documentation of sklearn.metrics.pairwise_distances.

"euclidean"
n_workers int

Number of workers for computing pairwise distances. Defaults to 4.

4
**kwargs

Additional keyword arguments for compatibility.

{}
References

Naeem et al., Reliable Fidelity and Diversity Metrics for Generative Models (2020). https://arxiv.org/abs/2002.09797

Code was adapted from: generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models. https://github.com/clovaai/generative-evaluation-prdc

Examples:

>>> coverage = Coverage()
>>> real_features = np.random.rand(100, 100)
>>> fake_features = np.random.rand(100, 100)
>>> result: MetricResult = coverage.compute(real_features, fake_features)
Source code in src/pymdma/general/measures/prdc.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
class Coverage(FeatureMetric):
    """Coverage Metric for accessing diversity of the generated samples. Unlike
    Improved Recall, it is robust towards outliers in the real/reference data.

    **Objective**: Diversity

    Parameters
    ----------
    k : int, optional
        Number of nearest neighbors to consider in the hypersphere estimation. Defaults to 5.
    metric : str, optional, default="euclidean"
        The metric to use when calculating distance between instances.
        For the available metrics, see the documentation of `sklearn.metrics.pairwise_distances`.
    n_workers : int, optional
        Number of workers for computing pairwise distances. Defaults to 4.
    **kwargs
        Additional keyword arguments for compatibility.

    References
    ----------
    Naeem et al., Reliable Fidelity and Diversity Metrics for Generative Models (2020).
    https://arxiv.org/abs/2002.09797

    Code was adapted from:
    generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models.
    https://github.com/clovaai/generative-evaluation-prdc

    Examples
    --------
    >>> coverage = Coverage()
    >>> real_features = np.random.rand(100, 100)
    >>> fake_features = np.random.rand(100, 100)
    >>> result: MetricResult = coverage.compute(real_features, fake_features)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = [EvaluationLevel.INSTANCE, EvaluationLevel.DATASET]
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = True
    min_value: float = 0.0
    max_value: float = 1.0

    def __init__(
        self,
        k: int = 5,
        metric: str = "euclidean",
        n_workers: int = 4,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.k = k
        self.metric = metric
        self.n_workers = n_workers

    def compute(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> MetricResult:
        """Compute the Coverage metric.

        Parameters
        ----------
        real_features : np.ndarray
            Array of shape (n_samples, n_features) containing the real features.
        fake_features : np.ndarray
            Array of shape (n_samples, n_features) containing the fake features.

        Notes
        -----
        Intermediate computations can be stored in the `context` dictionary of the `kwargs` parameter.
        Usefull when calculating multiple metrics that share the same intermediate computations.

        Returns
        -------
        result: MetricResult
            Dataset-level and instance-level results for the coverage metric.
        """
        state = kwargs.get("context", {})
        if "real_nn_distances" not in state:
            state["real_nn_distances"] = compute_nearest_neighbour_distances(
                real_features,
                nearest_k=self.k,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        if "real_fake_distances" not in state:
            state["real_fake_distances"] = compute_pairwise_distance(
                real_features,
                fake_features,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        coverage = np.logical_or(
            state["real_fake_distances"].min(axis=1) < state["real_nn_distances"],
            np.isclose(state["real_fake_distances"].min(axis=1), state["real_nn_distances"]),
        )

        # matrix with (R, F) shape -> .any() -> matrix with (F,) shape
        # an array that indicates for each F in how many real manifolds it is contained in
        coverage_counts = np.logical_or(
            state["real_fake_distances"] < np.expand_dims(state["real_nn_distances"], axis=1),
            np.isclose(state["real_fake_distances"], np.expand_dims(state["real_nn_distances"], axis=1)),
        ).sum(axis=0)

        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": coverage.mean()},
            instance_level={"dtype": OutputsTypes.ARRAY, "subtype": "int", "value": coverage_counts.tolist()},
        )

pymdma.image.measures.synthesis_val.FrechetDistance

Frechet Distance (FD) metric wrapper from the PIQ implementation of FID. Allows the computation of the dispersion and distance ratios for the metric.

Objective: Fidelity, Diversity

Parameters:

Name Type Description Default
compute_ratios bool

If set to True, the dispersion and distance ratios will be computed. Defaults to True.

True
**kwargs dict

Additional keyword arguments for compatibility (unused).

{}
Notes

This implementation is based on the PIQ library. The base extractor model is InceptionV3, but this implementation allows for the use of other embedding models (useful when the synthetic data is not compatible with Inception models).

See Also

general.functional.ratio.dispersion_ratio : Compute the dispersion ratio for the Frechet Distance metric. general.functional.ratio.distance_ratio : Compute the distance ratio for the Frechet Distance metric.

References

Kastryulin et al., PyTorch Image Quality: Metrics for Image Quality Assessment (2022). https://arxiv.org/abs/2208.14818

piq, PyTorch Image Quality: Metrics and Measure for Image Quality Assessment, https://github.com/photosynthesis-team/piq

Examples:

>>> fid = FrechetDistance()
>>> x_feats = np.random.rand(100, 100)
>>> y_feats = np.random.rand(100, 100)
>>> result: MetricResult = fid.compute(x_feats, y_feats)
Source code in src/pymdma/general/measures/external/piq.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class FrechetDistance(FeatureMetric):
    """Frechet Distance (FD) metric wrapper from the PIQ implementation of FID.
    Allows the computation of the dispersion and distance ratios for the
    metric.

    **Objective**: Fidelity, Diversity

    Parameters
    ----------
    compute_ratios : bool, optional
        If set to True, the dispersion and distance ratios will be computed. Defaults to True.
    **kwargs : dict, optional
        Additional keyword arguments for compatibility (unused).

    Notes
    -----
    This implementation is based on the PIQ library. The base extractor model is InceptionV3, but this implementation allows
    for the use of other embedding models (useful when the synthetic data is not compatible with Inception models).

    See Also
    --------
    general.functional.ratio.dispersion_ratio : Compute the dispersion ratio for the Frechet Distance metric.
    general.functional.ratio.distance_ratio : Compute the distance ratio for the Frechet Distance metric.

    References
    ----------
    Kastryulin et al., PyTorch Image Quality: Metrics for Image Quality Assessment (2022).
    https://arxiv.org/abs/2208.14818

    piq, PyTorch Image Quality: Metrics and Measure for Image Quality Assessment,
    https://github.com/photosynthesis-team/piq

    Examples
    --------
    >>> fid = FrechetDistance()
    >>> x_feats = np.random.rand(100, 100)
    >>> y_feats = np.random.rand(100, 100)
    >>> result: MetricResult = fid.compute(x_feats, y_feats)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = EvaluationLevel.DATASET
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = False
    min_value: float = 0.0
    max_value: float = np.inf

    extractor_model_name: str = "inception_fid"

    def __init__(
        self,
        compute_ratios: bool = True,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.compute_ratios = compute_ratios
        self._fid_inst = _FID()

    def _compute_ratios(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> Dict[str, float]:
        """Compute the dispersion and distance ratios for the Frechet Distance
        metric.

        Parameters
        ----------
        real_features : np.ndarray
            Array of shape (n_samples, n_features) containing features of real samples.
        fake_features : np.ndarray
            Array of shape (n_samples, n_features) containing features of fake/generated samples.

        Returns
        -------
        ratios: dict
            Dictionary containing the dispersion and distance ratio values.
        """
        state = kwargs.get("context", {})

        if any(key not in state for key in {"x_split_1", "x_split_2", "y_split_1", "y_split_2"}):
            state["x_split_1"], state["x_split_2"] = features_splitting(real_features, seed=0)
            state["y_split_1"], state["y_split_2"] = features_splitting(fake_features, seed=0)

        return {
            "dispersion_ratio": dispersion_ratio(
                self._fid_inst.compute_metric,
                to_tensor(state["x_split_1"]),
                to_tensor(state["x_split_2"]),
                to_tensor(state["y_split_1"]),
                to_tensor(state["y_split_2"]),
            ),
            "distance_ratio": distance_ratio(
                self._fid_inst.compute_metric,
                to_tensor(state["x_split_1"]),
                to_tensor(state["x_split_2"]),
                to_tensor(state["y_split_1"]),
                to_tensor(state["y_split_2"]),
            ),
        }

    def compute(
        self,
        real_features: Union[Tensor, np.ndarray],
        fake_features: Union[Tensor, np.ndarray],
        **kwargs,
    ) -> MetricResult:
        """Compute the Frechet Distance metric.

        Parameters
        ----------
        real_features : Union[Tensor, np.ndarray]
            Array-like of shape (n_samples, n_features) containing features of real samples.
        fake_features : Union[Tensor, np.ndarray]
            Array-like of shape (n_samples, n_features) containing features of fake/generated samples.

        Returns
        -------
        result : MetricResult
            Dataset-level FD score and the dispersion and distance ratios.
        """
        real_features = to_tensor(real_features)
        fake_features = to_tensor(fake_features)

        fid = self._fid_inst.compute_metric(real_features, fake_features)

        ratios = None
        if self.compute_ratios:
            ratios = self._compute_ratios(real_features, fake_features, **kwargs)

        return MetricResult(
            dataset_level={
                "dtype": OutputsTypes.NUMERIC,
                "subtype": "float",
                "value": fid.detach().item(),
                "stats": ratios,
            },
        )

pymdma.image.measures.synthesis_val.GeometryScore

Geometry Score (GS) metric wrapper from the PIQ implementation of GS.

Objective: Fidelity, Diversity

Parameters:

Name Type Description Default
sample_size int

Number of samples to use for the GS computation. Defaults to 128.

128
num_iters int

Number of iterations to use for the GS computation. Defaults to 1000.

1000
gamma float

Gamma parameter for the GS computation. Defaults to None.

None
i_max int

Maximum number of iterations for the GS computation. Defaults to 10.

10
num_workers int

Number of workers to use for the GS computation. Defaults to 4.

4
**kwargs dict

Additional keyword arguments for compatibility (unused).

{}
References

Kastryulin et al., PyTorch Image Quality: Metrics for Image Quality Assessment (2022). https://arxiv.org/abs/2208.14818

piq, PyTorch Image Quality: Metrics and Measure for Image Quality Assessment, https://github.com/photosynthesis-team/piq

Examples:

>>> gs = GeometryScore()
>>> x_feats = np.random.rand(100, 100)
>>> y_feats = np.random.rand(100, 100)
>>> result: MetricResult = gs.compute(x_feats, y_feats)
Source code in src/pymdma/general/measures/external/piq.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
class GeometryScore(FeatureMetric):
    """Geometry Score (GS) metric wrapper from the PIQ implementation of GS.

    **Objective**: Fidelity, Diversity

    Parameters
    ----------
    sample_size : int, optional
        Number of samples to use for the GS computation. Defaults to 128.
    num_iters : int, optional
        Number of iterations to use for the GS computation. Defaults to 1000.
    gamma : float, optional
        Gamma parameter for the GS computation. Defaults to None.
    i_max : int, optional
        Maximum number of iterations for the GS computation. Defaults to 10.
    num_workers : int, optional
        Number of workers to use for the GS computation. Defaults to 4.
    **kwargs : dict, optional
        Additional keyword arguments for compatibility (unused).

    References
    ----------
    Kastryulin et al., PyTorch Image Quality: Metrics for Image Quality Assessment (2022).
    https://arxiv.org/abs/2208.14818

    piq, PyTorch Image Quality: Metrics and Measure for Image Quality Assessment,
    https://github.com/photosynthesis-team/piq

    Examples
    --------
    >>> gs = GeometryScore()
    >>> x_feats = np.random.rand(100, 100)
    >>> y_feats = np.random.rand(100, 100)
    >>> result: MetricResult = gs.compute(x_feats, y_feats)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = EvaluationLevel.DATASET
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = False
    min_value: float = 0.0
    max_value: float = np.inf

    def __init__(
        self,
        sample_size: int = 128,
        num_iters: int = 1000,
        gamma: Optional[float] = None,
        i_max: int = 10,
        num_workers: int = 4,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.sample_size = sample_size
        self.num_iters = num_iters
        self.gamma = gamma
        self.i_max = i_max
        self.num_workers = num_workers

        self._gs = _GS(
            sample_size=self.sample_size,
            num_iters=self.num_iters,
            gamma=self.gamma,
            i_max=self.i_max,
            num_workers=self.num_workers,
        )

    def compute(
        self,
        real_features: Union[Tensor, np.ndarray],
        fake_features: Union[Tensor, np.ndarray],
        **kwargs,
    ) -> MetricResult:
        """Compute the Geometry Score metric.

        Parameters
        ----------
        real_features : Union[Tensor, np.ndarray]
            Array-like of shape (n_samples, n_features) containing features of real samples.
        fake_features : Union[Tensor, np.ndarray]
            Array-like of shape (n_samples, n_features) containing features of fake/generated samples.

        Returns
        -------
        result : MetricResult
            Dataset-level GS score.
        """
        real_features = to_tensor(real_features)
        fake_features = to_tensor(fake_features)

        score = self._gs.compute_metric(real_features, fake_features)

        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": score.detach().item()},
        )

pymdma.image.measures.synthesis_val.MultiScaleIntrinsicDistance

Multi-Scale Intrinsic Distance (MSID) metric wrapper from the PIQ implementation of MSID.

Objective: Fidelity, Diversity

Parameters:

Name Type Description Default
ts Optional[Tensor]

Tensor of shape (n_samples, n_features) containing the temperature values. Defaults to None.

None
k_neighbours int

Number of nearest neighbours to consider. Defaults to 5.

5
m_steps int

Number of steps for the MSID computation. Defaults to 10.

10
niters int

Number of iterations for the MSID computation. Defaults to 100.

100
rademacher bool

Whether to use Rademacher distribution for the MSID computation. Defaults to False. When not active will use standard normal for random vectors in Hutchinson.

False
normalized_laplacian bool

Whether to normalize the laplacian for the MSID computation. Defaults to True.

True
normalize Literal['empty', 'complete', 'er', 'none']

Normalization strategy for the laplacian. Defaults to "empty".

'empty'
msid_mode Literal['l2', 'max']

Mode for the MSID computation. Defaults to "max".

'max'
**kwargs dict

Additional keyword arguments for compatibility (unused).

{}
Notes

The results of this metric are based on random approximations, so they are not deterministic. In some datasets the results can be unstable. This can be mitigated by increasing the number of iterations with the niters parameter.

References

Kastryulin et al., PyTorch Image Quality: Metrics for Image Quality Assessment (2022). https://arxiv.org/abs/2208.14818

piq, PyTorch Image Quality: Metrics and Measure for Image Quality Assessment, https://github.com/photosynthesis-team/piq

Examples:

>>> msid = MultiScaleIntrinsicDistance()
>>> x_feats = np.random.rand(100, 100)
>>> y_feats = np.random.rand(100, 100)
>>> result: MetricResult = msid.compute(x_feats, y_feats)
Source code in src/pymdma/general/measures/external/piq.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
class MultiScaleIntrinsicDistance(FeatureMetric):
    """Multi-Scale Intrinsic Distance (MSID) metric wrapper from the PIQ
    implementation of MSID.

    **Objective**: Fidelity, Diversity

    Parameters
    ----------
    ts : Optional[Tensor], optional
        Tensor of shape (n_samples, n_features) containing the temperature values. Defaults to None.
    k_neighbours : int, optional
        Number of nearest neighbours to consider. Defaults to 5.
    m_steps : int, optional
        Number of steps for the MSID computation. Defaults to 10.
    niters : int, optional
        Number of iterations for the MSID computation. Defaults to 100.
    rademacher : bool, optional
        Whether to use Rademacher distribution for the MSID computation. Defaults to False.
        When not active will use standard normal for random vectors in Hutchinson.
    normalized_laplacian : bool, optional
        Whether to normalize the laplacian for the MSID computation. Defaults to True.
    normalize : Literal["empty", "complete", "er", "none"], optional
        Normalization strategy for the laplacian. Defaults to "empty".
    msid_mode : Literal["l2", "max"], optional
        Mode for the MSID computation. Defaults to "max".
    **kwargs : dict, optional
        Additional keyword arguments for compatibility (unused).

    Notes
    -----
    The results of this metric are based on random approximations, so they are not deterministic.
    In some datasets the results can be unstable. This can be mitigated by increasing the
    number of iterations with the `niters` parameter.


    References
    ----------
    Kastryulin et al., PyTorch Image Quality: Metrics for Image Quality Assessment (2022).
    https://arxiv.org/abs/2208.14818

    piq, PyTorch Image Quality: Metrics and Measure for Image Quality Assessment,
    https://github.com/photosynthesis-team/piq

    Examples
    --------
    >>> msid = MultiScaleIntrinsicDistance()
    >>> x_feats = np.random.rand(100, 100)
    >>> y_feats = np.random.rand(100, 100)
    >>> result: MetricResult = msid.compute(x_feats, y_feats)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = EvaluationLevel.DATASET
    metric_group = MetricGroup.QUALITY

    higher_is_better: bool = False
    min_value: float = 0.0
    max_value: float = np.inf

    extractor_model_name: str = "inception_fid"

    def __init__(
        self,
        ts: Optional[Union[Tensor, np.ndarray]] = None,
        k_neighbours: int = 5,
        m_steps: int = 10,
        niters: int = 100,
        rademacher: bool = False,
        normalized_laplacian: bool = True,
        normalize: Literal["empty", "complete", "er", "none"] = "empty",
        msid_mode: Literal["l2", "max"] = "max",
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.ts = torch.from_numpy(ts) if isinstance(ts, np.ndarray) else ts
        self.k_neighbours = k_neighbours
        self.m_steps = m_steps
        self.niters = niters
        self.rademacher = rademacher
        self.normalized_laplacian = normalized_laplacian
        self.normalize = normalize
        self.msid_mode = msid_mode

        self._msid = _MSID(
            ts=self.ts,
            k=self.k_neighbours,
            m=self.m_steps,
            niters=self.niters,
            rademacher=self.rademacher,
            normalized_laplacian=self.normalized_laplacian,
            normalize=self.normalize,
            msid_mode=self.msid_mode,
        )

    def compute(
        self,
        real_features: Union[Tensor, np.ndarray],
        fake_features: Union[Tensor, np.ndarray],
        **kwargs,
    ) -> MetricResult:
        """Compute the Multi-Scale Intrinsic Distance metric.

        Parameters
        ----------
        real_features : Union[Tensor, np.ndarray]
            Array-like of shape (n_samples, n_features) containing features of real samples.
        fake_features : Union[Tensor, np.ndarray]
            Array-like of shape (n_samples, n_features) containing features of fake/generated samples.

        Returns
        -------
        result : MetricResult
            Dataset-level MSID score.
        """
        real_features = to_tensor(real_features)
        fake_features = to_tensor(fake_features)
        score = self._msid.compute_metric(real_features, fake_features)
        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": score.detach().item()},
        )

pymdma.image.measures.synthesis_val.PrecisionRecallDistribution

Computes PRD data from sample embeddings and the maximum F_beta scores for the given precision/recall values.

The points from both distributions are mixed and then clustered. This leads to a pair of histograms of discrete distributions over the cluster centers on which the PRD algorithm is executed.

For PRD, it is recommended that number of points in eval_data and ref_data are equal since unbalanced distributions bias the clustering towards the larger dataset. The check for this condition can be performed by setting the enforce_balance flag to True (recommended).

Regarding the maximum F_beta scores, the maximum F_beta score over all pairs of precision/recall values is useful to compress a PRD plot into a single value which correlate with recall. Whereas, the max_f_beta_inv score over all pairs of precision/recall values compresses the PRD plot into a single value that correlates with precision.

Objective: Fidelity, Diversity

Parameters:

Name Type Description Default
num_clusters int

Number of cluster centers to fit. The default value is 2.

2
num_angles int

Number of angles for which to compute PRD. Must be in [3, 1e6]. The default value is 1001.

1001
num_runs int

Number of independent runs over which to average the PRD data. The default value is 10.

10
beta int

Beta parameter for F_beta score. Must be positive. The default value is 8.

8
epsilon float

Small constant to avoid numerical instability caused by division by 0 when precision and recall are close to zero. The default value is 1e-10.

1e-10
compute_stats bool

If True, F_beta scores for all precision/recall pairs will be computed. If False, F_beta scores computation is skipped. Default is True.

True
**kwargs dict

Additional keyword arguments for compatibility (unused).

{}
References

Sajjadi, Mehdi SM, et al. Assessing generative models via precision and recall (2018). https://proceedings.neurips.cc/paper_files/paper/2018/file/f7696a9b362ac5a51c3dc8f098b73923-Paper.pdf

Code adapted from: https://github.com/vanderschaarlab/evaluating-generative-models/blob/main/metrics/prd_score.py

Examples:

>>> prd = PrecisionRecallDistribution()
>>> x_feats = np.random.rand(64, 48)
>>> y_feats = np.random.rand(64, 48)
>>> result: MetricResult = prd.compute(x_feats, y_feats)
Source code in src/pymdma/general/measures/prd.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
class PrecisionRecallDistribution(FeatureMetric):
    """Computes PRD data from sample embeddings and the maximum F_beta scores
    for the given precision/recall values.

    The points from both distributions are mixed and then clustered. This leads
    to a pair of histograms of discrete distributions over the cluster centers
    on which the PRD algorithm is executed.

    For PRD, it is recommended that number of points in eval_data and ref_data are equal since
    unbalanced distributions bias the clustering towards the larger dataset. The
    check for this condition can be performed by setting the enforce_balance flag to True
    (recommended).

    Regarding the maximum F_beta scores, the maximum F_beta score over all pairs of precision/recall
    values is useful to compress a PRD plot into a single value which correlate with recall.
    Whereas, the max_f_beta_inv score over all pairs of precision/recall values compresses
    the PRD plot into a single value that correlates with precision.

    **Objective**: Fidelity, Diversity

    Parameters
    ----------
    num_clusters: int, optional
        Number of cluster centers to fit. The default value is 2.
    num_angles: int, optional
        Number of angles for which to compute PRD. Must be in [3, 1e6]. The default value is 1001.
    num_runs: int, optional
        Number of independent runs over which to average the PRD data. The default value is 10.
    beta: int, optional
        Beta parameter for F_beta score. Must be positive. The default value is 8.
    epsilon: float, optional
        Small constant to avoid numerical instability caused by division
        by 0 when precision and recall are close to zero. The default value is 1e-10.
    compute_stats: bool, optional
        If True, F_beta scores for all precision/recall pairs will be computed.
        If False, F_beta scores computation is skipped. Default is True.

    **kwargs : dict, optional
        Additional keyword arguments for compatibility (unused).

    References
    ---------
    Sajjadi, Mehdi SM, et al. Assessing generative models via precision and recall (2018).
    https://proceedings.neurips.cc/paper_files/paper/2018/file/f7696a9b362ac5a51c3dc8f098b73923-Paper.pdf

    Code adapted from:
    https://github.com/vanderschaarlab/evaluating-generative-models/blob/main/metrics/prd_score.py


    Examples
    --------
    >>> prd = PrecisionRecallDistribution()
    >>> x_feats = np.random.rand(64, 48)
    >>> y_feats = np.random.rand(64, 48)
    >>> result: MetricResult = prd.compute(x_feats, y_feats)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = EvaluationLevel.DATASET
    metric_group = MetricGroup.QUALITY

    def __init__(
        self,
        num_clusters: int = 2,
        num_angles: int = 1001,
        num_runs: int = 10,
        epsilon: float = 1e-10,
        beta: int = 8,
        compute_stats: bool = True,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.num_clusters = num_clusters
        self.num_angles = num_angles
        self.num_runs = num_runs
        self.epsilon = epsilon
        self.compute_stats = compute_stats

        assert beta > 0, "Given parameter beta must be positive."
        self.beta = beta

    def _prd_from_embedding(self, target: np.ndarray, reference: np.ndarray):
        eval_data = np.array(target, dtype=np.float64)
        ref_data = np.array(reference, dtype=np.float64)
        precisions = []
        recalls = []
        for _ in range(self.num_runs):
            eval_dist, ref_dist = cluster_into_bins(eval_data, ref_data, self.num_clusters)
            precision, recall = _compute_prd(eval_dist, ref_dist, self.num_angles, self.epsilon)
            precisions.append(precision)
            recalls.append(recall)
        precision = np.mean(precisions, axis=0)
        recall = np.mean(recalls, axis=0)
        return precision, recall

    def compute(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> MetricResult:
        """Computes PRD data from sample embeddings. Using the PRD, the maximum
        F_beta and F_beta_inv score are also computed. These scores for the
        given precision/recall values correlate, respectively, with recall and
        precision.

        Returns
        -------
        MetricResult
            Instance-level PRD values.
            Dataset-leve max_f_beta and max_f_beta_inv scores.
        """
        warning = None
        if len(fake_features) != len(real_features):
            warning = (
                "The number of points in eval_data %d is not equal to the number of "
                "points in ref_data %d. To disable this exception, set enforce_balance "
                "to False (not recommended)." % (len(fake_features), len(real_features))
            )

        precision, recall = self._prd_from_embedding(fake_features, real_features)

        stats = None
        if self.compute_stats:
            max_f_beta = np.max(_prd_to_f_beta(precision, recall, self.beta, self.epsilon))
            max_f_beta_inv = np.max(_prd_to_f_beta(recall, precision, 1 / self.beta, self.epsilon))
            stats = {
                "max_f_beta": max_f_beta,
                "max_f_beta_inv": max_f_beta_inv,
            }

        return MetricResult(
            dataset_level={
                "dtype": OutputsTypes.KEY_ARRAY,
                "subtype": "float",
                "value": {
                    "precision_values": precision,
                    "recall_values": recall,
                },
                "plot_params": {
                    "x_label": "Recall",
                    "y_label": "Precision",
                    "kind": "line",
                    "x_key": "recall_values",
                    "y_key": "precision_values",
                },
                "stats": stats,
            },
            errors=[warning] if warning else None,
        )

Privacy

pymdma.image.measures.synthesis_val.Authenticity

Authenticity Metric for assessing the authenticity of the generated samples. A synthetic sample is considered authentic if it is signficantly distinct from any real sample.

Objective: Privacy

Parameters:

Name Type Description Default
metric str

The metric to use when calculating distance between instances. For the available metrics, see the documentation of sklearn.metrics.pairwise_distances.

"euclidean"
**kwargs

Additional keyword arguments for compatibility.

{}
Notes

The authenticity metric is computed by checking if any fake sample is closer to a real sample than the real sample is to any other real sample.

References

Alaa et al., How Faithful Is Your Synthetic Data? Sample-Level Metrics for Evaluating and Auditing Generative Models. (2022) https://doi.org/10.48550/arXiv.2102.08921.

Hypersphere estimation code was adapted from: generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models. https://github.com/clovaai/generative-evaluation-prdc

Examples:

>>> authenticity = Authenticity()
>>> real_features = np.random.rand(100, 100)
>>> fake_features = np.random.rand(100, 100)
>>> result: MetricResult = authenticity.compute(real_features, fake_features)
Source code in src/pymdma/general/measures/prdc.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
class Authenticity(FeatureMetric):
    """Authenticity Metric for assessing the authenticity of the generated
    samples. A synthetic sample is considered authentic if it is signficantly
    distinct from any real sample.

    **Objective**: Privacy

    Parameters
    ----------
    metric : str, optional, default="euclidean"
        The metric to use when calculating distance between instances.
        For the available metrics, see the documentation of `sklearn.metrics.pairwise_distances`.
    **kwargs
        Additional keyword arguments for compatibility.

    Notes
    -----
    The authenticity metric is computed by checking if any fake sample is closer to a real sample than the real sample is to any other real sample.

    References
    ----------
    Alaa et al., How Faithful Is Your Synthetic Data? Sample-Level Metrics for Evaluating and Auditing Generative Models. (2022)
    https://doi.org/10.48550/arXiv.2102.08921.

    Hypersphere estimation code was adapted from:
    generative-evaluation-prdc, Reliable Fidelity and Diversity Metrics for Generative Models.
    https://github.com/clovaai/generative-evaluation-prdc

    Examples
    --------
    >>> authenticity = Authenticity()
    >>> real_features = np.random.rand(100, 100)
    >>> fake_features = np.random.rand(100, 100)
    >>> result: MetricResult = authenticity.compute(real_features, fake_features)
    """

    reference_type = ReferenceType.DATASET
    evaluation_level = [EvaluationLevel.INSTANCE, EvaluationLevel.DATASET]
    metric_group = MetricGroup.PRIVACY

    higher_is_better: bool = True
    min_value: float = 0.0
    max_value: float = 1.0

    def __init__(
        self,
        metric: str = "euclidean",
        n_workers: int = 4,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.metric = metric
        self.n_workers = n_workers

    def compute(self, real_features: np.ndarray, fake_features: np.ndarray, **kwargs) -> MetricResult:
        """Compute the Authenticity metric.

        Parameters
        ----------
        real_features : np.ndarray
            Array of shape (n_samples, n_features) containing the real features.
        fake_features : np.ndarray
            Array of shape (n_samples, n_features) containing the fake features.

        Notes
        -----
        Intermediate computations can be stored in the `context` dictionary of the `kwargs` parameter.
        Usefull when calculating multiple metrics that share the same intermediate computations.

        Returns
        -------
        result: MetricResult
            Dataset-level and instance-level results for the authenticity metric
        """
        state = kwargs.get("context", {})

        if "real_fake_distances" not in state:
            state["real_fake_distances"] = compute_pairwise_distance(
                real_features,
                fake_features,
                metric=self.metric,
                n_workers=self.n_workers,
            )

        # compute distance to closest real samples
        state["real_closest_real_distances"] = compute_nearest_neighbour_distances(
            real_features,
            nearest_k=1,
            metric=self.metric,
            n_workers=self.n_workers,
        )

        # check if any fake sample is closer to Ri than Ri is to any other Rj
        authenticity = np.logical_or(
            state["real_fake_distances"] < np.expand_dims(state["real_closest_real_distances"], axis=1),
            np.isclose(state["real_fake_distances"], np.expand_dims(state["real_closest_real_distances"], axis=1)),
        )

        # mask of the values that are considered authentic in the fake dataset
        authenticity_mask = ~authenticity.any(axis=0)

        return MetricResult(
            dataset_level={"dtype": OutputsTypes.NUMERIC, "subtype": "float", "value": authenticity_mask.mean()},
            instance_level={
                "dtype": OutputsTypes.ARRAY,
                "subtype": "int",
                "value": authenticity_mask.astype(int).tolist(),
            },
        )