forked from SeldonIO/alibi-detect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschemas.py
1249 lines (1054 loc) · 48.1 KB
/
schemas.py
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Pydantic models used by :func:`~alibi_detect.utils.validate.validate_config` to validate configuration dictionaries.
The `resolved` kwarg of :func:`~alibi_detect.utils.validate.validate_config` determines whether the *unresolved* or
*resolved* pydantic models are used:
- The *unresolved* models expect any artefacts specified within it to not yet have been resolved.
The artefacts are still string references to local filepaths or registries (e.g. `x_ref = 'x_ref.npy'`).
- The *resolved* models expect all artefacts to be have been resolved into runtime objects. For example, `x_ref`
should have been resolved into an `np.ndarray`.
.. note::
For detector pydantic models, the fields match the corresponding detector's args/kwargs. Refer to the
detector's api docs for a full description of each arg/kwarg.
"""
from typing import Callable, Dict, List, Optional, Type, Union, Any
# TODO - conditional checks depending on backend etc
# TODO - consider validating output of get_config calls
import numpy as np
from pydantic import BaseModel, validator
from alibi_detect.cd.tensorflow import UAE as UAE_tf
from alibi_detect.cd.tensorflow import HiddenOutput as HiddenOutput_tf
from alibi_detect.utils._types import Literal, NDArray
from alibi_detect.utils.frameworks import has_tensorflow, has_pytorch
# Define supported models for each optional dependency
SupportedModels_tf, SupportedModels_torch, SupportedModels_sklearn = (), (), () # type: ignore
if has_tensorflow:
import tensorflow as tf
SupportedModels_tf = (tf.keras.Model, UAE_tf, HiddenOutput_tf) # type: ignore
if has_pytorch:
# import torch
SupportedModels_torch = () # type: ignore # TODO - fill
# import sklearn
# SupportedModels_sklearn = () # type: ignore # TODO - fill
# Build SupportedModels - a tuple of all possible models for use in isinstance() etc.
SupportedModels = SupportedModels_tf + SupportedModels_torch + SupportedModels_sklearn
# TODO - could define a Union with fwdrefs here, for use in mypy type annotations in saving.py etc
# Custom validators (defined here for reuse in multiple pydantic models)
def coerce_int2list(value: int) -> List[int]:
"""Validator to coerce int to list (pydantic doesn't do this by default)."""
if isinstance(value, int):
return [value]
else:
return value
def validate_model(model: Callable, values: dict) -> Callable:
"""Validator to check the model is compatible with the given backend"""
backend = values['backend']
if backend == 'tensorflow' and not isinstance(model, SupportedModels_tf):
raise ValueError('A TensorFlow backend is not available for this model')
elif backend == 'pytorch' and not isinstance(model, SupportedModels_torch):
raise ValueError('A PyTorch backend is not available for this model')
elif backend == 'sklearn' and not isinstance(model, SupportedModels_sklearn):
raise ValueError('A sklearn backend is not available for this model')
return model
# TODO - we could add another validator to check given "backend" against what optional deps are installed?
# Custom BaseModel so that we can set default config
class CustomBaseModel(BaseModel):
"""
Base pydantic model schema. The default pydantic settings are set here.
"""
class Config:
arbitrary_types_allowed = True # since we have np.ndarray's etc
extra = 'forbid' # Forbid extra fields so that we catch misspelled fields
# Custom BaseModel with additional kwarg's allowed
class CustomBaseModelWithKwargs(BaseModel):
"""
Base pydantic model schema. The default pydantic settings are set here.
"""
class Config:
arbitrary_types_allowed = True # since we have np.ndarray's etc
extra = 'allow' # Allow extra fields
class MetaData(CustomBaseModel):
version: str
config_spec: str
version_warning: bool = False
class DetectorConfig(CustomBaseModel):
"""
Base detector config schema. Only fields universal across all detectors are defined here.
"""
name: str
"Name of the detector e.g. `MMDDrift`."
backend: Literal['tensorflow', 'pytorch', 'sklearn', 'keops'] = 'tensorflow'
"The detector backend."
meta: Optional[MetaData] = None
"Config metadata. Should not be edited."
# Note: Although not all detectors have a backend, we define in base class as `backend` also determines
# whether tf or torch models used for preprocess_fn.
class ModelConfig(CustomBaseModel):
"""
Unresolved schema for (ML) models. Note that the model "backend" e.g. 'tensorflow', 'pytorch', 'sklearn', is set
by `backend` in :class:`DetectorConfig`.
Examples
--------
A TensorFlow classifier model stored in the `model/` directory, with the softmax layer extracted:
.. code-block :: toml
[model]
src = "model/"
layer = -1
"""
src: str
"""
Filepath to directory storing the model (relative to the `config.toml` file, or absolute). At present,
TensorFlow models must be stored in
`H5 format <https://www.tensorflow.org/guide/keras/save_and_serialize#keras_h5_format>`_.
"""
custom_objects: Optional[dict] = None
"""
Dictionary of custom objects. Passed to the tensorflow
`load_model <https://www.tensorflow.org/api_docs/python/tf/keras/models/load_model>`_ function. This can be
used to pass custom registered functions and classes to a model.
"""
layer: Optional[int] = None
"""
Optional index of hidden layer to extract. If not `None`, a
:class:`~alibi_detect.cd.tensorflow.preprocess.HiddenOutput` model is returned.
"""
class EmbeddingConfig(CustomBaseModel):
"""
Unresolved schema for text embedding models. Currently, only pre-trained
`HuggingFace transformer <https://github.com/huggingface/transformers>`_ models are supported.
Examples
--------
Using the hidden states at the output of each layer of the
`BERT base <https://huggingface.co/bert-base-cased>`_ model as text embeddings:
.. code-block :: toml
[embedding]
src = "bert-base-cased"
type = "hidden_state"
layers = [-1, -2, -3, -4, -5, -6, -7, -8]
"""
type: Literal['pooler_output', 'last_hidden_state', 'hidden_state', 'hidden_state_cls']
"""
The type of embedding to be loaded. See `embedding_type` in
:class:`~alibi_detect.models.tensorflow.embedding.TransformerEmbedding`.
"""
layers: Optional[List[int]] = None
"List specifying the hidden layers to be used to extract the embedding."
# TODO - add check conditional on embedding type (see docstring in above)
src: str
"""
Model name e.g. `"bert-base-cased"`, or a filepath to directory storing the model to extract embeddings from
(relative to the `config.toml` file, or absolute).
"""
class TokenizerConfig(CustomBaseModel):
"""
Unresolved schema for text tokenizers. Currently, only pre-trained
`HuggingFace tokenizer <https://github.com/huggingface/tokenizers>`_ models are supported.
Examples
--------
`BERT base <https://huggingface.co/bert-base-cased>`_ tokenizer with additional keyword arguments passed to the
HuggingFace :meth:`~transformers.AutoTokenizer.from_pretrained` method:
.. code-block :: toml
[tokenizer]
src = "bert-base-cased"
[tokenizer.kwargs]
use_fast = false
force_download = true
"""
src: str
"""
Model name e.g. `"bert-base-cased"`, or a filepath to directory storing the tokenizer model (relative to the
`config.toml` file, or absolute). Passed to passed to :meth:`transformers.AutoTokenizer.from_pretrained`.
"""
kwargs: Optional[dict] = {}
"Dictionary of keyword arguments to pass to :meth:`transformers.AutoTokenizer.from_pretrained`."
class PreprocessConfig(CustomBaseModel):
"""
Unresolved schema for drift detector preprocess functions, to be passed to a detector's `preprocess_fn` kwarg.
Once loaded, the function is wrapped in a :func:`~functools.partial`, to be evaluated within the detector.
If `src` specifies a generic Python function, the dictionary specified by `kwargs` is passed to it. Otherwise,
if `src` specifies :func:`~alibi_detect.cd.tensorflow.preprocess.preprocess_drift`
(`src='@cd.tensorflow.preprocess.preprocess_drift'`), all fields (except `kwargs`) are passed to it.
Examples
--------
Preprocessor with a `model`, text `embedding` and `tokenizer` passed to
:func:`~alibi_detect.cd.tensorflow.preprocess.preprocess_drift`:
.. code-block :: toml
[preprocess_fn]
src = "@cd.tensorflow.preprocess.preprocess_drift"
batch_size = 32
max_len = 100
tokenizer.src = "tokenizer/" # TokenizerConfig
[preprocess_fn.model]
# ModelConfig
src = "model/"
[preprocess_fn.embedding]
# EmbeddingConfig
src = "embedding/"
type = "hidden_state"
layers = [-1, -2, -3, -4, -5, -6, -7, -8]
A serialized Python function with keyword arguments passed to it:
.. code-block :: toml
[preprocess_fn]
src = 'myfunction.dill'
kwargs = {'kwarg1'=0.7, 'kwarg2'=true}
"""
src: str = "@cd.tensorflow.preprocess.preprocess_drift"
"""
The preprocessing function. A string referencing a filepath to a serialized function in `dill` format, or an
object registry reference.
"""
# Below kwargs are only passed if src == @preprocess_drift
model: Optional[Union[str, ModelConfig]] = None
"""
Model used for preprocessing. Either an object registry reference, or a
:class:`~alibi_detect.utils.schemas.ModelConfig`.
"""
# TODO - make model required field when src is preprocess_drift
embedding: Optional[Union[str, EmbeddingConfig]] = None
"""
A text embedding model. Either a string referencing a HuggingFace transformer model name, an object registry
reference, or a :class:`~alibi_detect.utils.schemas.EmbeddingConfig`. If `model=None`, the `embedding` is passed to
:func:`~alibi_detect.cd.tensorflow.preprocess.preprocess_drift` as `model`. Otherwise, the `model` is chained to
the output of the `embedding` as an additional preprocessing step.
"""
tokenizer: Optional[Union[str, TokenizerConfig]] = None
"""
Optional tokenizer for text drift. Either a string referencing a HuggingFace tokenizer model name, or a
:class:`~alibi_detect.utils.schemas.TokenizerConfig`.
"""
device: Optional[Literal['cpu', 'cuda']] = None
"""
Device type used. The default `None` tries to use the GPU and falls back on CPU if needed. Only relevant if
`src='@cd.torch.preprocess.preprocess_drift'`
"""
preprocess_batch_fn: Optional[str] = None
"""
Optional batch preprocessing function. For example to convert a list of objects to a batch which can be processed
by the `model`.
"""
max_len: Optional[int] = None
"Optional max token length for text drift."
batch_size: Optional[int] = int(1e10)
"Batch size used during prediction."
dtype: str = 'np.float32'
"Model output type, e.g. `'tf.float32'`"
# Additional kwargs
kwargs: dict = {}
"""
Dictionary of keyword arguments to be passed to the function specified by `src`. Only used if `src` specifies a
generic Python function.
"""
class KernelConfig(CustomBaseModelWithKwargs):
"""
Unresolved schema for kernels, to be passed to a detector's `kernel` kwarg.
If `src` specifies a :class:`~alibi_detect.utils.tensorflow.GaussianRBF` kernel, the `sigma`, `trainable` and
`init_sigma_fn` fields are passed to it. Otherwise, all fields except `src` are passed as kwargs.
Examples
--------
A :class:`~alibi_detect.utils.tensorflow.GaussianRBF` kernel, with three different bandwidths:
.. code-block :: toml
[kernel]
src = "@alibi_detect.utils.tensorflow.GaussianRBF"
trainable = false
sigma = [0.1, 0.2, 0.3]
A serialized kernel with keyword arguments passed:
.. code-block :: toml
[kernel]
src = "mykernel.dill"
sigma = 0.42
custom_setting = "xyz"
"""
src: str
"A string referencing a filepath to a serialized kernel in `.dill` format, or an object registry reference."
# Below kwargs are only passed if kernel == @GaussianRBF
sigma: Optional[NDArray[np.float32]] = None
"""
Bandwidth used for the kernel. Needn’t be specified if being inferred or trained. Can pass multiple values to eval
kernel with and then average.
"""
trainable: bool = False
"Whether or not to track gradients w.r.t. sigma to allow it to be trained."
init_sigma_fn: Optional[str] = None
"""
Function used to compute the bandwidth `sigma`. Used when `sigma` is to be inferred. The function's signature
should match :py:func:`~alibi_detect.utils.tensorflow.kernels.sigma_median`. If `None`, it is set to
:func:`~alibi_detect.utils.tensorflow.kernels.sigma_median`.
"""
class DeepKernelConfig(CustomBaseModel):
"""
Unresolved schema for :class:`~alibi_detect.utils.tensorflow.kernels.DeepKernel`'s.
Examples
--------
A :class:`~alibi_detect.utils.tensorflow.DeepKernel`, with a trainable
:class:`~alibi_detect.utils.tensorflow.GaussianRBF` kernel applied to the projected inputs and a custom
serialized kernel applied to the raw inputs:
.. code-block :: toml
[kernel]
eps = 0.01
[kernel.kernel_a]
src = "@utils.tensorflow.kernels.GaussianRBF"
trainable = true
[kernel.kernel_b]
src = "custom_kernel.dill"
sigma = [ 1.2,]
trainable = false
[kernel.proj]
src = "model/"
"""
proj: Union[str, ModelConfig]
"""
The projection to be applied to the inputs before applying `kernel_a`. This should be a Tensorflow or PyTorch
model, specified as an object registry reference, or a :class:`~alibi_detect.utils.schemas.ModelConfig`.
"""
kernel_a: Union[str, KernelConfig] = "@utils.tensorflow.kernels.GaussianRBF"
"""
The kernel to apply to the projected inputs. Defaults to a
:class:`~alibi_detect.utils.tensorflow.kernels.GaussianRBF` with trainable bandwidth.
"""
kernel_b: Optional[Union[str, KernelConfig]] = "@utils.tensorflow.kernels.GaussianRBF"
"""
The kernel to apply to the raw inputs. Defaults to a :class:`~alibi_detect.utils.tensorflow.kernels.GaussianRBF`
with trainable bandwidth. Set to `None` in order to use only the deep component (i.e. `eps=0`).
"""
eps: Union[float, str] = 'trainable'
"""
The proportion (in [0,1]) of weight to assign to the kernel applied to raw inputs. This can be either specified or
set to `'trainable'`. Only relevant is `kernel_b` is not `None`.
"""
class OptimizerConfig(CustomBaseModelWithKwargs):
"""
Unresolved schema for optimizers. Note that the model "backend" e.g. 'tensorflow', 'pytorch', 'sklearn', is set
by `backend` in :class:`DetectorConfig`. If `backend='tensorflow'`, the `optimizer` dictionary is expected to be
a configuration dictionary compatible with
`tf.keras.optimizers.deserialize <https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/deserialize>`_.
Examples
--------
A TensorFlow Adam optimizer:
.. code-block :: toml
[optimizer]
class_name = "Adam"
[optimizer.config]
name = "Adam"
learning_rate = 0.001
decay = 0.0
"""
class_name: str
config: Dict[str, Any]
class DriftDetectorConfig(DetectorConfig):
"""
Unresolved base schema for drift detectors.
"""
# args/kwargs shared by all drift detectors
x_ref: str
"Data used as reference distribution. Should be a string referencing a NumPy `.npy` file."
preprocess_fn: Optional[Union[str, PreprocessConfig]] = None
"""
Function to preprocess the data before computing the data drift metrics. A string referencing a serialized function
in `.dill` format, an object registry reference, or a :class:`~alibi_detect.utils.schemas.PreprocessConfig`.
"""
input_shape: Optional[tuple] = None
"Optionally pass the shape of the input data. Used when saving detectors."
data_type: Optional[str] = None
"Specify data type added to the metadata. E.g. `‘tabular’`or `‘image’`."
x_ref_preprocessed: bool = False
"""
Whether the given reference data `x_ref` has been preprocessed yet. If `x_ref_preprocessed=True`, only the test
data `x` will be preprocessed at prediction time. If `x_ref_preprocessed=False`, the reference data will also be
preprocessed.
"""
class DriftDetectorConfigResolved(DetectorConfig):
"""
Resolved base schema for drift detectors.
"""
# args/kwargs shared by all drift detectors
x_ref: Union[np.ndarray, list]
"Data used as reference distribution."
preprocess_fn: Optional[Callable] = None
"Function to preprocess the data before computing the data drift metrics."
input_shape: Optional[tuple] = None
"Optionally pass the shape of the input data. Used when saving detectors."
data_type: Optional[str] = None
"Specify data type added to the metadata. E.g. `‘tabular’` or `‘image’`."
x_ref_preprocessed: bool = False
"""
Whether the given reference data `x_ref` has been preprocessed yet. If `x_ref_preprocessed=True`, only the test
data `x` will be preprocessed at prediction time. If `x_ref_preprocessed=False`, the reference data will also be
preprocessed.
"""
class KSDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`KSDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/ksdrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.KSDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
alternative: Literal['two-sided', 'greater', 'less'] = 'two-sided'
n_features: Optional[int] = None
class KSDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`KSDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/ksdrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.KSDrift` documentation for a description of each field.
Resolved schema for the :class:`~alibi_detect.cd.KSDrift` detector.
"""
p_val: float = .05
preprocess_at_init: bool = True # Note: Duplication needed to avoid mypy error (unless we allow reassignment)
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
alternative: Literal['two-sided', 'greater', 'less'] = 'two-sided'
n_features: Optional[int] = None
class ChiSquareDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`ChiSquareDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/chisquaredrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.ChiSquareDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
categories_per_feature: Dict[int, Union[int, List[int]]] = None
n_features: Optional[int] = None
class ChiSquareDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`ChiSquareDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/chisquaredrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.ChiSquareDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: str = 'bonferroni'
categories_per_feature: Dict[int, Union[int, List[int]]] = None
n_features: Optional[int] = None
class TabularDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`TabularDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/tabulardrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.TabularDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
categories_per_feature: Dict[int, Optional[Union[int, List[int]]]] = None
alternative: Literal['two-sided', 'greater', 'less'] = 'two-sided'
n_features: Optional[int] = None
class TabularDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`TabularDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/tabulardrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.TabularDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
categories_per_feature: Dict[int, Optional[Union[int, List[int]]]] = None
alternative: Literal['two-sided', 'greater', 'less'] = 'two-sided'
n_features: Optional[int] = None
class CVMDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`CVMDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/cvmdrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.CVMDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
n_features: Optional[int] = None
class CVMDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`CVMDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/cvmdrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.CVMDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: str = 'bonferroni'
n_features: Optional[int] = None
class FETDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`FETDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/fetdrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.FETDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
alternative: Literal['two-sided', 'greater', 'less'] = 'two-sided'
n_features: Optional[int] = None
class FETDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`FETDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/fetdrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.FETDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
correction: Literal['bonferroni', 'fdr'] = 'bonferroni'
alternative: Literal['two-sided', 'greater', 'less'] = 'two-sided'
n_features: Optional[int] = None
class MMDDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`MMDDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/mmddrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.MMDDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
kernel: Optional[Union[str, KernelConfig]] = None
sigma: Optional[NDArray[np.float32]] = None
configure_kernel_from_x_ref: bool = True
n_permutations: int = 100
batch_size_permutations: int = 1000000
device: Optional[Literal['cpu', 'cuda']] = None
class MMDDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`MMDDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/mmddrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.MMDDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
kernel: Optional[Callable] = None
sigma: Optional[NDArray[np.float32]] = None
configure_kernel_from_x_ref: bool = True
n_permutations: int = 100
batch_size_permutations: int = 1000000
device: Optional[Literal['cpu', 'cuda']] = None
class LSDDDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`LSDDDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/lsdddrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.LSDDDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
sigma: Optional[NDArray[np.float32]] = None
n_permutations: int = 100
n_kernel_centers: Optional[int] = None
lambda_rd_max: float = 0.2
device: Optional[Literal['cpu', 'cuda']] = None
class LSDDDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`LSDDDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/lsdddrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.LSDDDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
sigma: Optional[NDArray[np.float32]] = None
n_permutations: int = 100
n_kernel_centers: Optional[int] = None
lambda_rd_max: float = 0.2
device: Optional[Literal['cpu', 'cuda']] = None
class ClassifierDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`ClassifierDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/classifierdrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.ClassifierDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
model: Union[str, ModelConfig]
preds_type: Literal['probs', 'logits'] = 'probs'
binarize_preds: bool = False
reg_loss_fn: Optional[str] = None
train_size: Optional[float] = .75
n_folds: Optional[int] = None
retrain_from_scratch: bool = True
seed: int = 0
optimizer: Optional[Union[str, OptimizerConfig]] = None
learning_rate: float = 1e-3
batch_size: int = 32
preprocess_batch_fn: Optional[str] = None
epochs: int = 3
verbose: int = 0
train_kwargs: Optional[dict] = None
dataset: Optional[str] = None
device: Optional[Literal['cpu', 'cuda']] = None
dataloader: Optional[str] = None # TODO: placeholder, will need to be updated for pytorch implementation
use_calibration: bool = False
calibration_kwargs: Optional[dict] = None
use_oob: bool = False
class ClassifierDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`ClassifierDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/classifierdrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.ClassifierDrift` documentation for a description of each field.
"""
p_val: float = .05
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
model: Optional[Callable] = None
preds_type: Literal['probs', 'logits'] = 'probs'
binarize_preds: bool = False
reg_loss_fn: Optional[Callable] = None
train_size: Optional[float] = .75
n_folds: Optional[int] = None
retrain_from_scratch: bool = True
seed: int = 0
optimizer: Optional['tf.keras.optimizers.Optimizer'] = None
learning_rate: float = 1e-3
batch_size: int = 32
preprocess_batch_fn: Optional[Callable] = None
epochs: int = 3
verbose: int = 0
train_kwargs: Optional[dict] = None
dataset: Optional[Callable] = None
device: Optional[Literal['cpu', 'cuda']] = None
dataloader: Optional[Callable] = None # TODO: placeholder, will need to be updated for pytorch implementation
use_calibration: bool = False
calibration_kwargs: Optional[dict] = None
use_oob: bool = False
# validators
_validate_model = validator('model', allow_reuse=True, pre=True)(validate_model)
class SpotTheDiffDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`SpotTheDiffDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/spotthediffdrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.SpotTheDiffDrift` documentation for a description of each field.
"""
p_val: float = .05
binarize_preds: bool = False
train_size: Optional[float] = .75
n_folds: Optional[int] = None
retrain_from_scratch: bool = True
seed: int = 0
optimizer: Optional[Union[str, OptimizerConfig]] = None
learning_rate: float = 1e-3
batch_size: int = 32
preprocess_batch_fn: Optional[str] = None
epochs: int = 3
verbose: int = 0
train_kwargs: Optional[dict] = None
dataset: Optional[str] = None
kernel: Optional[Union[str, KernelConfig]] = None
n_diffs: int = 1
initial_diffs: Optional[str] = None
l1_reg: float = 0.01
device: Optional[Literal['cpu', 'cuda']] = None
dataloader: Optional[str] = None # TODO: placeholder, will need to be updated for pytorch implementation
class SpotTheDiffDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`SpotTheDiffDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/spotthediffdrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.SpotTheDiffDrift` documentation for a description of each field.
"""
p_val: float = .05
binarize_preds: bool = False
train_size: Optional[float] = .75
n_folds: Optional[int] = None
retrain_from_scratch: bool = True
seed: int = 0
optimizer: Optional['tf.keras.optimizers.Optimizer'] = None
learning_rate: float = 1e-3
batch_size: int = 32
preprocess_batch_fn: Optional[Callable] = None
epochs: int = 3
verbose: int = 0
train_kwargs: Optional[dict] = None
dataset: Optional[Callable] = None
kernel: Optional[Callable] = None
n_diffs: int = 1
initial_diffs: Optional[np.ndarray] = None
l1_reg: float = 0.01
device: Optional[Literal['cpu', 'cuda']] = None
dataloader: Optional[Callable] = None # TODO: placeholder, will need to be updated for pytorch implementation
class LearnedKernelDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`LearnedKernelDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/learnedkerneldrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.LearnedKernelDrift` documentation for a description of each field.
"""
p_val: float = .05
kernel: Union[str, DeepKernelConfig]
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
n_permutations: int = 100
batch_size_permutations: int = 1000000
var_reg: float = 1e-5
reg_loss_fn: Optional[str] = None
train_size: Optional[float] = .75
retrain_from_scratch: bool = True
optimizer: Optional[Union[str, OptimizerConfig]] = None
learning_rate: float = 1e-3
batch_size: int = 32
batch_size_predict: int = 1000000
preprocess_batch_fn: Optional[str] = None
epochs: int = 3
verbose: int = 0
train_kwargs: Optional[dict] = None
dataset: Optional[str] = None
device: Optional[Literal['cpu', 'cuda']] = None
dataloader: Optional[str] = None # TODO: placeholder, will need to be updated for pytorch implementation
class LearnedKernelDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`LearnedKernelDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/learnedkerneldrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.LearnedKernelDrift` documentation for a description of each field.
"""
p_val: float = .05
kernel: Optional[Callable] = None
preprocess_at_init: bool = True
update_x_ref: Optional[Dict[str, int]] = None
n_permutations: int = 100
batch_size_permutations: int = 1000000
var_reg: float = 1e-5
reg_loss_fn: Optional[Callable] = None
train_size: Optional[float] = .75
retrain_from_scratch: bool = True
optimizer: Optional['tf.keras.optimizers.Optimizer'] = None
learning_rate: float = 1e-3
batch_size: int = 32
batch_size_predict: int = 1000000
preprocess_batch_fn: Optional[Callable] = None
epochs: int = 3
verbose: int = 0
train_kwargs: Optional[dict] = None
dataset: Optional[Callable] = None
device: Optional[Literal['cpu', 'cuda']] = None
dataloader: Optional[Callable] = None # TODO: placeholder, will need to be updated for pytorch implementation
class ContextMMDDriftConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`ContextMMDDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/contextmmddrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.ContextMMDDrift` documentation for a description of each field.
"""
p_val: float = .05
c_ref: str
preprocess_at_init: bool = True
update_ref: Optional[Dict[str, int]] = None
x_kernel: Optional[Union[str, KernelConfig]] = None
c_kernel: Optional[Union[str, KernelConfig]] = None
n_permutations: int = 100
prop_c_held: float = 0.25
n_folds: int = 5
batch_size: Optional[int] = 256
verbose: bool = False
device: Optional[Literal['cpu', 'cuda']] = None
class ContextMMDDriftConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`MMDDrift <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/mmddrift.html>`_ detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.MMDDrift` documentation for a description of each field.
"""
p_val: float = .05
c_ref: np.ndarray
preprocess_at_init: bool = True
update_ref: Optional[Dict[str, int]] = None
x_kernel: Optional[Callable] = None
c_kernel: Optional[Callable] = None
n_permutations: int = 100
prop_c_held: float = 0.25
n_folds: int = 5
batch_size: Optional[int] = 256
verbose: bool = False
device: Optional[Literal['cpu', 'cuda']] = None
class MMDDriftOnlineConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`MMDDriftOnline <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/onlinemmddrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.MMDDriftOnline` documentation for a description of each field.
"""
ert: float
window_size: int
kernel: Optional[Union[str, KernelConfig]] = None
sigma: Optional[np.ndarray] = None
n_bootstraps: int = 1000
device: Optional[Literal['cpu', 'cuda']] = None
verbose: bool = True
class MMDDriftOnlineConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`MMDDriftOnline <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/onlinemmddrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.MMDDriftOnline` documentation for a description of each field.
"""
ert: float
window_size: int
kernel: Optional[Callable] = None
sigma: Optional[np.ndarray] = None
n_bootstraps: int = 1000
device: Optional[Literal['cpu', 'cuda']] = None
verbose: bool = True
class LSDDDriftOnlineConfig(DriftDetectorConfig):
"""
Unresolved schema for the
`LSDDDriftOnline <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/onlinelsdddrift.html>`_
detector.
Except for the `name` and `meta` fields, the fields match the detector's args and kwargs. Refer to the
:class:`~alibi_detect.cd.LSDDDriftOnline` documentation for a description of each field.
"""
ert: float
window_size: int
sigma: Optional[np.ndarray] = None
n_bootstraps: int = 1000
n_kernel_centers: Optional[int] = None
lambda_rd_max: float = 0.2
device: Optional[Literal['cpu', 'cuda']] = None
verbose: bool = True
class LSDDDriftOnlineConfigResolved(DriftDetectorConfigResolved):
"""
Resolved schema for the
`LSDDDriftOnline <https://docs.seldon.io/projects/alibi-detect/en/stable/cd/methods/onlinelsdddrift.html>`_
detector.