about summary refs log tree commit diff
path: root/.venv/lib/python3.12/site-packages/azure/ai/ml/entities/_monitoring/thresholds.py
blob: 3e1c33b53af04d1c07d36a8ededa4caef918f2e0 (plain)
1
2
3
4
5
6
7
8
9
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
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
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
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
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
444
445
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------

# pylint: disable=unused-argument, protected-access

from typing import Any, Dict, List, Optional, Tuple

from azure.ai.ml._restclient.v2023_06_01_preview.models import (
    CategoricalDataDriftMetricThreshold,
    CategoricalDataQualityMetricThreshold,
    CategoricalPredictionDriftMetricThreshold,
    ClassificationModelPerformanceMetricThreshold,
    CustomMetricThreshold,
    DataDriftMetricThresholdBase,
    DataQualityMetricThresholdBase,
    FeatureAttributionMetricThreshold,
    GenerationSafetyQualityMetricThreshold,
    GenerationTokenStatisticsMetricThreshold,
    ModelPerformanceMetricThresholdBase,
    MonitoringThreshold,
    NumericalDataDriftMetricThreshold,
    NumericalDataQualityMetricThreshold,
    NumericalPredictionDriftMetricThreshold,
    PredictionDriftMetricThresholdBase,
)
from azure.ai.ml._utils._experimental import experimental
from azure.ai.ml._utils.utils import camel_to_snake, snake_to_camel
from azure.ai.ml.constants._monitoring import MonitorFeatureType, MonitorMetricName
from azure.ai.ml.entities._mixins import RestTranslatableMixin


class MetricThreshold(RestTranslatableMixin):
    def __init__(self, *, threshold: Optional[float] = None):
        self.data_type: Any = None
        self.metric_name: Optional[str] = None
        self.threshold = threshold


class NumericalDriftMetrics(RestTranslatableMixin):
    """Numerical Drift Metrics

    :param jensen_shannon_distance: The Jensen-Shannon distance between the two distributions
    :paramtype jensen_shannon_distance: float
    :param normalized_wasserstein_distance: The normalized Wasserstein distance between the two distributions
    :paramtype normalized_wasserstein_distance: float
    :param population_stability_index: The population stability index between the two distributions
    :paramtype population_stability_index: float
    :param two_sample_kolmogorov_smirnov_test: The two sample Kolmogorov-Smirnov test between the two distributions
    :paramtype two_sample_kolmogorov_smirnov_test: float
    """

    def __init__(
        self,
        *,
        jensen_shannon_distance: Optional[float] = None,
        normalized_wasserstein_distance: Optional[float] = None,
        population_stability_index: Optional[float] = None,
        two_sample_kolmogorov_smirnov_test: Optional[float] = None,
        metric: Optional[str] = None,
        metric_threshold: Optional[float] = None,
    ):
        self.jensen_shannon_distance = jensen_shannon_distance
        self.normalized_wasserstein_distance = normalized_wasserstein_distance
        self.population_stability_index = population_stability_index
        self.two_sample_kolmogorov_smirnov_test = two_sample_kolmogorov_smirnov_test
        self.metric = metric
        self.metric_threshold = metric_threshold

    def _find_name_and_threshold(self) -> Tuple:
        metric_name = None
        threshold = None
        if self.jensen_shannon_distance:
            metric_name = MonitorMetricName.JENSEN_SHANNON_DISTANCE
            threshold = MonitoringThreshold(value=self.jensen_shannon_distance)
        elif self.normalized_wasserstein_distance:
            metric_name = MonitorMetricName.NORMALIZED_WASSERSTEIN_DISTANCE
            threshold = MonitoringThreshold(value=self.normalized_wasserstein_distance)
        elif self.population_stability_index:
            metric_name = MonitorMetricName.POPULATION_STABILITY_INDEX
            threshold = MonitoringThreshold(value=self.population_stability_index)
        elif self.two_sample_kolmogorov_smirnov_test:
            metric_name = MonitorMetricName.TWO_SAMPLE_KOLMOGOROV_SMIRNOV_TEST
            threshold = MonitoringThreshold(value=self.two_sample_kolmogorov_smirnov_test)

        return metric_name, threshold

    @classmethod
    # pylint: disable=arguments-differ
    def _from_rest_object(cls, metric_name: str, threshold: Optional[float]) -> "NumericalDriftMetrics":  # type: ignore
        metric_name = camel_to_snake(metric_name)
        if metric_name == MonitorMetricName.JENSEN_SHANNON_DISTANCE:
            return cls(jensen_shannon_distance=threshold)
        if metric_name == MonitorMetricName.NORMALIZED_WASSERSTEIN_DISTANCE:
            return cls(normalized_wasserstein_distance=threshold)
        if metric_name == MonitorMetricName.POPULATION_STABILITY_INDEX:
            return cls(population_stability_index=threshold)
        if metric_name == MonitorMetricName.TWO_SAMPLE_KOLMOGOROV_SMIRNOV_TEST:
            return cls(two_sample_kolmogorov_smirnov_test=threshold)
        return cls()

    @classmethod
    def _get_default_thresholds(cls) -> "NumericalDriftMetrics":
        return cls(
            normalized_wasserstein_distance=0.1,
        )


class CategoricalDriftMetrics(RestTranslatableMixin):
    """Categorical Drift Metrics

    :param jensen_shannon_distance: The Jensen-Shannon distance between the two distributions
    :paramtype jensen_shannon_distance: float
    :param population_stability_index: The population stability index between the two distributions
    :paramtype population_stability_index: float
    :param pearsons_chi_squared_test: The Pearson's Chi-Squared test between the two distributions
    :paramtype pearsons_chi_squared_test: float
    """

    def __init__(
        self,
        *,
        jensen_shannon_distance: Optional[float] = None,
        population_stability_index: Optional[float] = None,
        pearsons_chi_squared_test: Optional[float] = None,
    ):
        self.jensen_shannon_distance = jensen_shannon_distance
        self.population_stability_index = population_stability_index
        self.pearsons_chi_squared_test = pearsons_chi_squared_test

    def _find_name_and_threshold(self) -> Tuple:
        metric_name = None
        threshold = None
        if self.jensen_shannon_distance:
            metric_name = MonitorMetricName.JENSEN_SHANNON_DISTANCE
            threshold = MonitoringThreshold(value=self.jensen_shannon_distance)
        if self.population_stability_index and threshold is None:
            metric_name = MonitorMetricName.POPULATION_STABILITY_INDEX
            threshold = MonitoringThreshold(value=self.population_stability_index)
        if self.pearsons_chi_squared_test and threshold is None:
            metric_name = MonitorMetricName.PEARSONS_CHI_SQUARED_TEST
            threshold = MonitoringThreshold(value=self.pearsons_chi_squared_test)

        return metric_name, threshold

    @classmethod
    # pylint: disable=arguments-differ
    def _from_rest_object(  # type: ignore
        cls, metric_name: str, threshold: Optional[float]
    ) -> "CategoricalDriftMetrics":
        metric_name = camel_to_snake(metric_name)
        if metric_name == MonitorMetricName.JENSEN_SHANNON_DISTANCE:
            return cls(jensen_shannon_distance=threshold)
        if metric_name == MonitorMetricName.POPULATION_STABILITY_INDEX:
            return cls(population_stability_index=threshold)
        if metric_name == MonitorMetricName.PEARSONS_CHI_SQUARED_TEST:
            return cls(pearsons_chi_squared_test=threshold)
        return cls()

    @classmethod
    def _get_default_thresholds(cls) -> "CategoricalDriftMetrics":
        return cls(
            jensen_shannon_distance=0.1,
        )


class DataDriftMetricThreshold(MetricThreshold):
    """Data drift metric threshold

    :param numerical: Numerical drift metrics
    :paramtype numerical: ~azure.ai.ml.entities.NumericalDriftMetrics
    :param categorical: Categorical drift metrics
    :paramtype categorical: ~azure.ai.ml.entities.CategoricalDriftMetrics
    """

    def __init__(
        self,
        *,
        data_type: Optional[MonitorFeatureType] = None,
        threshold: Optional[float] = None,
        metric: Optional[str] = None,
        numerical: Optional[NumericalDriftMetrics] = None,
        categorical: Optional[CategoricalDriftMetrics] = None,
    ):
        super().__init__(threshold=threshold)
        self.data_type = data_type
        self.metric = metric
        self.numerical = numerical
        self.categorical = categorical

    def _to_rest_object(self) -> DataDriftMetricThresholdBase:
        thresholds = []
        if self.numerical:
            num_metric_name, num_threshold = self.numerical._find_name_and_threshold()
            thresholds.append(
                NumericalDataDriftMetricThreshold(
                    metric=snake_to_camel(num_metric_name),
                    threshold=num_threshold,
                )
            )
        if self.categorical:
            cat_metric_name, cat_threshold = self.categorical._find_name_and_threshold()
            thresholds.append(
                CategoricalDataDriftMetricThreshold(
                    metric=snake_to_camel(cat_metric_name),
                    threshold=cat_threshold,
                )
            )

        return thresholds

    @classmethod
    def _from_rest_object(cls, obj: DataDriftMetricThresholdBase) -> "DataDriftMetricThreshold":
        num = None
        cat = None
        for threshold in obj:
            if threshold.data_type == "Numerical":
                num = NumericalDriftMetrics()._from_rest_object(  # pylint: disable=protected-access
                    threshold.metric, threshold.threshold.value if threshold.threshold else None
                )
            elif threshold.data_type == "Categorical":
                cat = CategoricalDriftMetrics()._from_rest_object(  # pylint: disable=protected-access
                    threshold.metric, threshold.threshold.value if threshold.threshold else None
                )

        return cls(
            numerical=num,
            categorical=cat,
        )

    @classmethod
    def _get_default_thresholds(cls) -> "DataDriftMetricThreshold":
        return cls(
            numerical=NumericalDriftMetrics._get_default_thresholds(),
            categorical=CategoricalDriftMetrics._get_default_thresholds(),
        )

    def __eq__(self, other: Any) -> bool:
        if not isinstance(other, DataDriftMetricThreshold):
            return NotImplemented
        return self.numerical == other.numerical and self.categorical == other.categorical


class PredictionDriftMetricThreshold(MetricThreshold):
    """Prediction drift metric threshold

    :param numerical: Numerical drift metrics
    :paramtype numerical: ~azure.ai.ml.entities.NumericalDriftMetrics
    :param categorical: Categorical drift metrics
    :paramtype categorical: ~azure.ai.ml.entities.CategoricalDriftMetrics
    """

    def __init__(
        self,
        *,
        data_type: Optional[MonitorFeatureType] = None,
        threshold: Optional[float] = None,
        numerical: Optional[NumericalDriftMetrics] = None,
        categorical: Optional[CategoricalDriftMetrics] = None,
    ):
        super().__init__(threshold=threshold)
        self.data_type = data_type
        self.numerical = numerical
        self.categorical = categorical

    def _to_rest_object(self) -> PredictionDriftMetricThresholdBase:
        thresholds = []
        if self.numerical:
            num_metric_name, num_threshold = self.numerical._find_name_and_threshold()
            thresholds.append(
                NumericalPredictionDriftMetricThreshold(
                    metric=snake_to_camel(num_metric_name),
                    threshold=num_threshold,
                )
            )
        if self.categorical:
            cat_metric_name, cat_threshold = self.categorical._find_name_and_threshold()
            thresholds.append(
                CategoricalPredictionDriftMetricThreshold(
                    metric=snake_to_camel(cat_metric_name),
                    threshold=cat_threshold,
                )
            )

        return thresholds

    @classmethod
    def _from_rest_object(cls, obj: PredictionDriftMetricThresholdBase) -> "PredictionDriftMetricThreshold":
        num = None
        cat = None
        for threshold in obj:
            if threshold.data_type == "Numerical":
                num = NumericalDriftMetrics()._from_rest_object(  # pylint: disable=protected-access
                    threshold.metric, threshold.threshold.value if threshold.threshold else None
                )
            elif threshold.data_type == "Categorical":
                cat = CategoricalDriftMetrics()._from_rest_object(  # pylint: disable=protected-access
                    threshold.metric, threshold.threshold.value if threshold.threshold else None
                )

        return cls(
            numerical=num,
            categorical=cat,
        )

    @classmethod
    def _get_default_thresholds(cls) -> "PredictionDriftMetricThreshold":
        return cls(
            numerical=NumericalDriftMetrics._get_default_thresholds(),
            categorical=CategoricalDriftMetrics._get_default_thresholds(),
        )

    def __eq__(self, other: Any) -> bool:
        if not isinstance(other, PredictionDriftMetricThreshold):
            return NotImplemented
        return (
            self.data_type == other.data_type
            and self.metric_name == other.metric_name
            and self.threshold == other.threshold
        )


class DataQualityMetricsNumerical(RestTranslatableMixin):
    """Data Quality Numerical Metrics

    :param null_value_rate: The null value rate
    :paramtype null_value_rate: float
    :param data_type_error_rate: The data type error rate
    :paramtype data_type_error_rate: float
    :param out_of_bounds_rate: The out of bounds rate
    :paramtype out_of_bounds_rate: float
    """

    def __init__(
        self,
        *,
        null_value_rate: Optional[float] = None,
        data_type_error_rate: Optional[float] = None,
        out_of_bounds_rate: Optional[float] = None,
    ):
        self.null_value_rate = null_value_rate
        self.data_type_error_rate = data_type_error_rate
        self.out_of_bounds_rate = out_of_bounds_rate

    def _to_rest_object(self) -> List[NumericalDataQualityMetricThreshold]:
        metric_thresholds = []
        if self.null_value_rate is not None:
            metric_name = MonitorMetricName.NULL_VALUE_RATE
            threshold = MonitoringThreshold(value=self.null_value_rate)
            metric_thresholds.append(
                NumericalDataQualityMetricThreshold(metric=snake_to_camel(metric_name), threshold=threshold)
            )
        if self.data_type_error_rate is not None:
            metric_name = MonitorMetricName.DATA_TYPE_ERROR_RATE
            threshold = MonitoringThreshold(value=self.data_type_error_rate)
            metric_thresholds.append(
                NumericalDataQualityMetricThreshold(metric=snake_to_camel(metric_name), threshold=threshold)
            )
        if self.out_of_bounds_rate is not None:
            metric_name = MonitorMetricName.OUT_OF_BOUND_RATE
            threshold = MonitoringThreshold(value=self.out_of_bounds_rate)
            metric_thresholds.append(
                NumericalDataQualityMetricThreshold(metric=snake_to_camel(metric_name), threshold=threshold)
            )

        return metric_thresholds

    @classmethod
    def _from_rest_object(cls, obj: List) -> "DataQualityMetricsNumerical":
        null_value_rate_val = None
        data_type_error_rate_val = None
        out_of_bounds_rate_val = None
        for thresholds in obj:
            if thresholds.metric in ("NullValueRate" "nullValueRate"):
                null_value_rate_val = thresholds.threshold.value
            if thresholds.metric in ("DataTypeErrorRate", "dataTypeErrorRate"):
                data_type_error_rate_val = thresholds.threshold.value
            if thresholds.metric in ("OutOfBoundsRate", "outOfBoundsRate"):
                out_of_bounds_rate_val = thresholds.threshold.value
        return cls(
            null_value_rate=null_value_rate_val,
            data_type_error_rate=data_type_error_rate_val,
            out_of_bounds_rate=out_of_bounds_rate_val,
        )

    @classmethod
    def _get_default_thresholds(cls) -> "DataQualityMetricsNumerical":
        return cls(
            null_value_rate=0.0,
            data_type_error_rate=0.0,
            out_of_bounds_rate=0.0,
        )


class DataQualityMetricsCategorical(RestTranslatableMixin):
    """Data Quality Categorical Metrics

    :param null_value_rate: The null value rate
    :paramtype null_value_rate: float
    :param data_type_error_rate: The data type error rate
    :paramtype data_type_error_rate: float
    :param out_of_bounds_rate: The out of bounds rate
    :paramtype out_of_bounds_rate: float
    """

    def __init__(
        self,
        *,
        null_value_rate: Optional[float] = None,
        data_type_error_rate: Optional[float] = None,
        out_of_bounds_rate: Optional[float] = None,
    ):
        self.null_value_rate = null_value_rate
        self.data_type_error_rate = data_type_error_rate
        self.out_of_bounds_rate = out_of_bounds_rate

    def _to_rest_object(self) -> List[CategoricalDataQualityMetricThreshold]:
        metric_thresholds = []
        if self.null_value_rate is not None:
            metric_name = MonitorMetricName.NULL_VALUE_RATE
            threshold = MonitoringThreshold(value=self.null_value_rate)
            metric_thresholds.append(
                CategoricalDataQualityMetricThreshold(metric=snake_to_camel(metric_name), threshold=threshold)
            )
        if self.data_type_error_rate is not None:
            metric_name = MonitorMetricName.DATA_TYPE_ERROR_RATE
            threshold = MonitoringThreshold(value=self.data_type_error_rate)
            metric_thresholds.append(
                CategoricalDataQualityMetricThreshold(metric=snake_to_camel(metric_name), threshold=threshold)
            )
        if self.out_of_bounds_rate is not None:
            metric_name = MonitorMetricName.OUT_OF_BOUND_RATE
            threshold = MonitoringThreshold(value=self.out_of_bounds_rate)
            metric_thresholds.append(
                CategoricalDataQualityMetricThreshold(metric=snake_to_camel(metric_name), threshold=threshold)
            )

        return metric_thresholds

    @classmethod
    def _from_rest_object(cls, obj: List) -> "DataQualityMetricsCategorical":
        null_value_rate_val = None
        data_type_error_rate_val = None
        out_of_bounds_rate_val = None
        for thresholds in obj:
            if thresholds.metric in ("NullValueRate" "nullValueRate"):
                null_value_rate_val = thresholds.threshold.value
            if thresholds.metric in ("DataTypeErrorRate", "dataTypeErrorRate"):
                data_type_error_rate_val = thresholds.threshold.value
            if thresholds.metric in ("OutOfBoundsRate", "outOfBoundsRate"):
                out_of_bounds_rate_val = thresholds.threshold.value
        return cls(
            null_value_rate=null_value_rate_val,
            data_type_error_rate=data_type_error_rate_val,
            out_of_bounds_rate=out_of_bounds_rate_val,
        )

    @classmethod
    def _get_default_thresholds(cls) -> "DataQualityMetricsCategorical":
        return cls(
            null_value_rate=0.0,
            data_type_error_rate=0.0,
            out_of_bounds_rate=0.0,
        )


class DataQualityMetricThreshold(MetricThreshold):
    """Data quality metric threshold

    :param numerical: Numerical data quality metrics
    :paramtype numerical: ~azure.ai.ml.entities.DataQualityMetricsNumerical
    :param categorical: Categorical data quality metrics
    :paramtype categorical: ~azure.ai.ml.entities.DataQualityMetricsCategorical
    """

    def __init__(
        self,
        *,
        data_type: Optional[MonitorFeatureType] = None,
        threshold: Optional[float] = None,
        metric_name: Optional[str] = None,
        numerical: Optional[DataQualityMetricsNumerical] = None,
        categorical: Optional[DataQualityMetricsCategorical] = None,
    ):
        super().__init__(threshold=threshold)
        self.data_type = data_type
        self.metric_name = metric_name
        self.numerical = numerical
        self.categorical = categorical

    def _to_rest_object(self) -> DataQualityMetricThresholdBase:
        thresholds: list = []
        if self.numerical:
            thresholds = thresholds + (
                DataQualityMetricsNumerical(  # pylint: disable=protected-access
                    null_value_rate=self.numerical.null_value_rate,
                    data_type_error_rate=self.numerical.data_type_error_rate,
                    out_of_bounds_rate=self.numerical.out_of_bounds_rate,
                )._to_rest_object()
            )
        if self.categorical:
            thresholds = (
                thresholds
                + (
                    DataQualityMetricsCategorical(  # pylint: disable=protected-access
                        null_value_rate=self.numerical.null_value_rate,
                        data_type_error_rate=self.numerical.data_type_error_rate,
                        out_of_bounds_rate=self.numerical.out_of_bounds_rate,
                    )._to_rest_object()
                )
                if self.numerical is not None
                else thresholds
            )
        return thresholds

    @classmethod
    def _from_rest_object(cls, obj: DataQualityMetricThresholdBase) -> "DataQualityMetricThreshold":
        num = []
        cat = []
        for threshold in obj:
            if threshold.data_type == "Numerical":
                num.append(threshold)
            elif threshold.data_type == "Categorical":
                cat.append(threshold)

        num_from_rest = DataQualityMetricsNumerical()._from_rest_object(num)  # pylint: disable=protected-access
        cat_from_rest = DataQualityMetricsCategorical()._from_rest_object(cat)  # pylint: disable=protected-access
        return cls(
            numerical=num_from_rest,
            categorical=cat_from_rest,
        )

    @classmethod
    def _get_default_thresholds(cls) -> "DataQualityMetricThreshold":
        return cls(
            numerical=DataQualityMetricsNumerical()._get_default_thresholds(),  # pylint: disable=protected-access
            categorical=DataQualityMetricsCategorical()._get_default_thresholds(),  # pylint: disable=protected-access
        )

    def __eq__(self, other: Any) -> bool:
        if not isinstance(other, DataQualityMetricThreshold):
            return NotImplemented
        return (
            self.data_type == other.data_type
            and self.metric_name == other.metric_name
            and self.threshold == other.threshold
        )


@experimental
class FeatureAttributionDriftMetricThreshold(MetricThreshold):
    """Feature attribution drift metric threshold

    :param normalized_discounted_cumulative_gain: The threshold value for metric.
    :paramtype normalized_discounted_cumulative_gain: float
    """

    def __init__(
        self, *, normalized_discounted_cumulative_gain: Optional[float] = None, threshold: Optional[float] = None
    ):
        super().__init__(threshold=threshold)
        self.data_type = MonitorFeatureType.ALL_FEATURE_TYPES
        self.metric_name = MonitorMetricName.NORMALIZED_DISCOUNTED_CUMULATIVE_GAIN
        self.normalized_discounted_cumulative_gain = normalized_discounted_cumulative_gain

    def _to_rest_object(self) -> FeatureAttributionMetricThreshold:
        return FeatureAttributionMetricThreshold(
            metric=snake_to_camel(self.metric_name),
            threshold=(
                MonitoringThreshold(value=self.normalized_discounted_cumulative_gain)
                if self.normalized_discounted_cumulative_gain
                else None
            ),
        )

    @classmethod
    def _from_rest_object(cls, obj: FeatureAttributionMetricThreshold) -> "FeatureAttributionDriftMetricThreshold":
        return cls(normalized_discounted_cumulative_gain=obj.threshold.value if obj.threshold else None)


@experimental
class ModelPerformanceClassificationThresholds(RestTranslatableMixin):
    def __init__(
        self,
        *,
        accuracy: Optional[float] = None,
        precision: Optional[float] = None,
        recall: Optional[float] = None,
    ):
        self.accuracy = accuracy
        self.precision = precision
        self.recall = recall

    def _to_str_object(self, **kwargs):
        thresholds = []
        if self.accuracy:
            thresholds.append(
                '{"modelType":"classification","metric":"Accuracy","threshold":{"value":' + f"{self.accuracy}" + "}}"
            )
        if self.precision:
            thresholds.append(
                '{"modelType":"classification","metric":"Precision","threshold":{"value":' + f"{self.precision}" + "}}"
            )
        if self.recall:
            thresholds.append(
                '{"modelType":"classification","metric":"Recall","threshold":{"value":' + f"{self.recall}" + "}}"
            )

        if not thresholds:
            return None

        return ", ".join(thresholds)

    @classmethod
    def _from_rest_object(cls, obj) -> "ModelPerformanceClassificationThresholds":
        return cls(
            accuracy=obj.threshold.value if obj.threshold else None,
        )


@experimental
class ModelPerformanceRegressionThresholds(RestTranslatableMixin):
    def __init__(
        self,
        *,
        mean_absolute_error: Optional[float] = None,
        mean_squared_error: Optional[float] = None,
        root_mean_squared_error: Optional[float] = None,
    ):
        self.mean_absolute_error = mean_absolute_error
        self.mean_squared_error = mean_squared_error
        self.root_mean_squared_error = root_mean_squared_error

    def _to_str_object(self, **kwargs):
        thresholds = []
        if self.mean_absolute_error:
            thresholds.append(
                '{"modelType":"regression","metric":"MeanAbsoluteError","threshold":{"value":'
                + f"{self.mean_absolute_error}"
                + "}}"
            )
        if self.mean_squared_error:
            thresholds.append(
                '{"modelType":"regression","metric":"MeanSquaredError","threshold":{"value":'
                + f"{self.mean_squared_error}"
                + "}}"
            )
        if self.root_mean_squared_error:
            thresholds.append(
                '{"modelType":"regression","metric":"RootMeanSquaredError","threshold":{"value":'
                + f"{self.root_mean_squared_error}"
                + "}}"
            )

        if not thresholds:
            return None

        return ", ".join(thresholds)


@experimental
class ModelPerformanceMetricThreshold(RestTranslatableMixin):
    def __init__(
        self,
        *,
        classification: Optional[ModelPerformanceClassificationThresholds] = None,
        regression: Optional[ModelPerformanceRegressionThresholds] = None,
    ):
        self.classification = classification
        self.regression = regression

    def _to_str_object(self, **kwargs):
        thresholds = []
        if self.classification:
            thresholds.append(self.classification._to_str_object(**kwargs))
        if self.regression:
            thresholds.append(self.regression._to_str_object(**kwargs))

        if not thresholds:
            return None
        if len(thresholds) == 2:
            result = "[" + ", ".join(thresholds) + "]"
        else:
            result = "[" + thresholds[0] + "]"
        return result

    def _to_rest_object(self, **kwargs) -> ModelPerformanceMetricThresholdBase:
        threshold = MonitoringThreshold(value=0.9)
        return ClassificationModelPerformanceMetricThreshold(
            metric="Accuracy",
            threshold=threshold,
        )

    @classmethod
    def _from_rest_object(cls, obj: ModelPerformanceMetricThresholdBase) -> "ModelPerformanceMetricThreshold":
        return cls(
            classification=ModelPerformanceClassificationThresholds._from_rest_object(obj),
            regression=None,
        )


@experimental
class CustomMonitoringMetricThreshold(MetricThreshold):
    """Feature attribution drift metric threshold

    :param metric_name: The metric to calculate
    :type metric_name: str
    :param threshold: The threshold value. If None, a default value will be set
        depending on the selected metric.
    :type threshold: float
    """

    def __init__(
        self,
        *,
        metric_name: Optional[str],
        threshold: Optional[float] = None,
    ):
        super().__init__(threshold=threshold)
        self.metric_name = metric_name

    def _to_rest_object(self) -> CustomMetricThreshold:
        return CustomMetricThreshold(
            metric=self.metric_name,
            threshold=MonitoringThreshold(value=self.threshold) if self.threshold is not None else None,
        )

    @classmethod
    def _from_rest_object(cls, obj: CustomMetricThreshold) -> "CustomMonitoringMetricThreshold":
        return cls(metric_name=obj.metric, threshold=obj.threshold.value if obj.threshold else None)


@experimental
class GenerationSafetyQualityMonitoringMetricThreshold(RestTranslatableMixin):  # pylint: disable=name-too-long
    """Generation safety quality metric threshold

    :param groundedness: The groundedness metric threshold
    :paramtype groundedness: Dict[str, float]
    :param relevance: The relevance metric threshold
    :paramtype relevance: Dict[str, float]
    :param coherence: The coherence metric threshold
    :paramtype coherence: Dict[str, float]
    :param fluency: The fluency metric threshold
    :paramtype fluency: Dict[str, float]
    :param similarity: The similarity metric threshold
    :paramtype similarity: Dict[str, float]
    """

    def __init__(
        self,
        *,
        groundedness: Optional[Dict[str, float]] = None,
        relevance: Optional[Dict[str, float]] = None,
        coherence: Optional[Dict[str, float]] = None,
        fluency: Optional[Dict[str, float]] = None,
        similarity: Optional[Dict[str, float]] = None,
    ):
        self.groundedness = groundedness
        self.relevance = relevance
        self.coherence = coherence
        self.fluency = fluency
        self.similarity = similarity

    def _to_rest_object(self) -> GenerationSafetyQualityMetricThreshold:
        metric_thresholds = []
        if self.groundedness:
            if "acceptable_groundedness_score_per_instance" in self.groundedness:
                acceptable_threshold = MonitoringThreshold(
                    value=self.groundedness["acceptable_groundedness_score_per_instance"]
                )
            else:
                acceptable_threshold = MonitoringThreshold(value=3)
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AcceptableGroundednessScorePerInstance", threshold=acceptable_threshold
                )
            )
            aggregated_threshold = MonitoringThreshold(value=self.groundedness["aggregated_groundedness_pass_rate"])
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AggregatedGroundednessPassRate", threshold=aggregated_threshold
                )
            )
        if self.relevance:
            if "acceptable_relevance_score_per_instance" in self.relevance:
                acceptable_threshold = MonitoringThreshold(
                    value=self.relevance["acceptable_relevance_score_per_instance"]
                )
            else:
                acceptable_threshold = MonitoringThreshold(value=3)
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AcceptableRelevanceScorePerInstance", threshold=acceptable_threshold
                )
            )
            aggregated_threshold = MonitoringThreshold(value=self.relevance["aggregated_relevance_pass_rate"])
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AggregatedRelevancePassRate", threshold=aggregated_threshold
                )
            )
        if self.coherence:
            if "acceptable_coherence_score_per_instance" in self.coherence:
                acceptable_threshold = MonitoringThreshold(
                    value=self.coherence["acceptable_coherence_score_per_instance"]
                )
            else:
                acceptable_threshold = MonitoringThreshold(value=3)
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AcceptableCoherenceScorePerInstance", threshold=acceptable_threshold
                )
            )
            aggregated_threshold = MonitoringThreshold(value=self.coherence["aggregated_coherence_pass_rate"])
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AggregatedCoherencePassRate", threshold=aggregated_threshold
                )
            )
        if self.fluency:
            if "acceptable_fluency_score_per_instance" in self.fluency:
                acceptable_threshold = MonitoringThreshold(value=self.fluency["acceptable_fluency_score_per_instance"])
            else:
                acceptable_threshold = MonitoringThreshold(value=3)
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AcceptableFluencyScorePerInstance", threshold=acceptable_threshold
                )
            )
            aggregated_threshold = MonitoringThreshold(value=self.fluency["aggregated_fluency_pass_rate"])
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AggregatedFluencyPassRate", threshold=aggregated_threshold
                )
            )
        if self.similarity:
            if "acceptable_similarity_score_per_instance" in self.similarity:
                acceptable_threshold = MonitoringThreshold(
                    value=self.similarity["acceptable_similarity_score_per_instance"]
                )
            else:
                acceptable_threshold = MonitoringThreshold(value=3)
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AcceptableSimilarityScorePerInstance", threshold=acceptable_threshold
                )
            )
            aggregated_threshold = MonitoringThreshold(value=self.similarity["aggregated_similarity_pass_rate"])
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="AggregatedSimilarityPassRate", threshold=aggregated_threshold
                )
            )
        return metric_thresholds

    @classmethod
    def _from_rest_object(
        cls, obj: GenerationSafetyQualityMetricThreshold
    ) -> "GenerationSafetyQualityMonitoringMetricThreshold":
        groundedness = {}
        relevance = {}
        coherence = {}
        fluency = {}
        similarity = {}

        for threshold in obj:
            if threshold.metric == "AcceptableGroundednessScorePerInstance":
                groundedness["acceptable_groundedness_score_per_instance"] = threshold.threshold.value
            if threshold.metric == "AcceptableRelevanceScorePerInstance":
                relevance["acceptable_relevance_score_per_instance"] = threshold.threshold.value
            if threshold.metric == "AcceptableCoherenceScorePerInstance":
                coherence["acceptable_coherence_score_per_instance"] = threshold.threshold.value
            if threshold.metric == "AcceptableFluencyScorePerInstance":
                fluency["acceptable_fluency_score_per_instance"] = threshold.threshold.value
            if threshold.metric == "AcceptableSimilarityScorePerInstance":
                similarity["acceptable_similarity_score_per_instance"] = threshold.threshold.value
            if threshold.metric == "AggregatedGroundednessPassRate":
                groundedness["aggregated_groundedness_pass_rate"] = threshold.threshold.value
            if threshold.metric == "AggregatedRelevancePassRate":
                relevance["aggregated_relevance_pass_rate"] = threshold.threshold.value
            if threshold.metric == "AggregatedCoherencePassRate":
                coherence["aggregated_coherence_pass_rate"] = threshold.threshold.value
            if threshold.metric == "AggregatedFluencyPassRate":
                fluency["aggregated_fluency_pass_rate"] = threshold.threshold.value
            if threshold.metric == "AggregatedSimilarityPassRate":
                similarity["aggregated_similarity_pass_rate"] = threshold.threshold.value

        return cls(
            groundedness=groundedness if groundedness else None,
            relevance=relevance if relevance else None,
            coherence=coherence if coherence else None,
            fluency=fluency if fluency else None,
            similarity=similarity if similarity else None,
        )


@experimental
class GenerationTokenStatisticsMonitorMetricThreshold(RestTranslatableMixin):  # pylint: disable=name-too-long
    """Generation token statistics metric threshold definition.

    All required parameters must be populated in order to send to Azure.

    :ivar metric: Required. [Required] Gets or sets the feature attribution metric to calculate.
     Possible values include: "TotalTokenCount", "TotalTokenCountPerGroup".
    :vartype metric: str or
     ~azure.mgmt.machinelearningservices.models.GenerationTokenStatisticsMetric
    :ivar threshold: Gets or sets the threshold value.
     If null, a default value will be set depending on the selected metric.
    :vartype threshold: ~azure.mgmt.machinelearningservices.models.MonitoringThreshold
    """

    def __init__(
        self,
        *,
        totaltoken: Optional[Dict[str, float]] = None,
    ):
        self.totaltoken = totaltoken

    def _to_rest_object(self) -> GenerationSafetyQualityMetricThreshold:
        metric_thresholds = []
        if self.totaltoken:
            if "total_token_count" in self.totaltoken:
                acceptable_threshold = MonitoringThreshold(value=self.totaltoken["total_token_count"])
            else:
                acceptable_threshold = MonitoringThreshold(value=3)
            metric_thresholds.append(
                GenerationTokenStatisticsMetricThreshold(metric="TotalTokenCount", threshold=acceptable_threshold)
            )
            acceptable_threshold_per_group = MonitoringThreshold(value=self.totaltoken["total_token_count_per_group"])
            metric_thresholds.append(
                GenerationSafetyQualityMetricThreshold(
                    metric="TotalTokenCountPerGroup", threshold=acceptable_threshold_per_group
                )
            )
        return metric_thresholds

    @classmethod
    def _from_rest_object(
        cls, obj: GenerationTokenStatisticsMetricThreshold
    ) -> "GenerationTokenStatisticsMonitorMetricThreshold":
        totaltoken = {}
        for threshold in obj:
            if threshold.metric == "TotalTokenCount":
                totaltoken["total_token_count"] = threshold.threshold.value
            if threshold.metric == "TotalTokenCountPerGroup":
                totaltoken["total_token_count_per_group"] = threshold.threshold.value

        return cls(
            totaltoken=totaltoken if totaltoken else None,
        )

    @classmethod
    def _get_default_thresholds(cls) -> "GenerationTokenStatisticsMonitorMetricThreshold":
        return cls(totaltoken={"total_token_count": 0, "total_token_count_per_group": 0})