repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/test_classifier_pt.py | from itertools import product
import numpy as np
import pytest
import torch
import torch.nn as nn
from typing import Union
from alibi_detect.cd.pytorch.classifier import ClassifierDriftTorch
n = 100
class MyModel(nn.Module):
def __init__(self, n_features: int, softmax: bool = False):
super().__init__()
... | 2,921 | 28.515152 | 85 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/conftest.py | import pytest
@pytest.fixture
def seed(pytestconfig):
"""
Returns the random seed set by pytest-randomly.
"""
return pytestconfig.getoption("randomly_seed")
| 175 | 16.6 | 51 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/test_spot_the_diff_pt.py | from itertools import product
import numpy as np
import pytest
import torch
import torch.nn as nn
from typing import Union
from alibi_detect.cd.pytorch.spot_the_diff import SpotTheDiffDriftTorch
n = 100
class MyKernel(nn.Module):
def __init__(self, n_features: int):
super().__init__()
self.dense ... | 2,440 | 27.057471 | 96 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/test_lsdd_online_pt.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import torch
import torch.nn as nn
from typing import Callable, List
from alibi_detect.cd.pytorch.lsdd_online import LSDDDriftOnlineTorch
from alibi_detect.cd.pytorch.preprocess import HiddenOutput, preprocess_drift
from alibi_... | 5,861 | 34.96319 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/test_preprocess_pt.py | from itertools import product
import numpy as np
import pytest
import torch
import torch.nn as nn
from alibi_detect.cd.pytorch import HiddenOutput
n, dim1, dim2, n_classes, latent_dim, n_hidden = 100, 2, 3, 5, 2, 7
n_features = dim1 * dim2
shape = (n, dim1, dim2)
X = np.random.rand(n * n_features).reshape(shape).astyp... | 1,651 | 28.5 | 99 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/test_contextmmd_pt.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import torch
import torch.nn as nn
from typing import Callable, List
from alibi_detect.cd.pytorch.context_aware import ContextMMDDriftTorch
from alibi_detect.cd.pytorch.preprocess import HiddenOutput, preprocess_drift
class M... | 4,034 | 36.71028 | 102 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/test_lsdd_pt.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import torch
import torch.nn as nn
from typing import Callable, List
from alibi_detect.cd.pytorch.lsdd import LSDDDriftTorch
from alibi_detect.cd.pytorch.preprocess import HiddenOutput, preprocess_drift
n, n_hidden, n_classes ... | 3,599 | 34.643564 | 101 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/pytorch/tests/test_mmd_online_pt.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import torch
import torch.nn as nn
from typing import Callable, List
from alibi_detect.cd.pytorch.mmd_online import MMDDriftOnlineTorch
from alibi_detect.cd.pytorch.preprocess import HiddenOutput, preprocess_drift
from alibi_de... | 5,847 | 34.877301 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/learned_kernel.py | from functools import partial
import numpy as np
import tensorflow as tf
from typing import Callable, Dict, Optional, Tuple, Union
from alibi_detect.cd.base import BaseLearnedKernelDrift
from alibi_detect.utils.tensorflow.data import TFDataset
from alibi_detect.utils.tensorflow.misc import clone_model
from alibi_detect... | 11,206 | 46.28692 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/mmd.py | import logging
import numpy as np
import tensorflow as tf
from typing import Callable, Dict, Optional, Tuple, Union
from alibi_detect.cd.base import BaseMMDDrift
from alibi_detect.utils.tensorflow.distance import mmd2_from_kernel_matrix
from alibi_detect.utils.tensorflow.kernels import GaussianRBF
from alibi_detect.uti... | 6,034 | 44.719697 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/utils.py | from typing import Callable
from functools import partial
def activate_train_mode_for_all_layers(model: Callable) -> Callable:
model.trainable = False # type: ignore
model = partial(model, training=True) # Note this affects batchnorm etc also
return model
| 272 | 29.333333 | 81 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/classifier.py | from functools import partial
import numpy as np
import tensorflow as tf
from tensorflow.keras.losses import BinaryCrossentropy
from scipy.special import softmax
from typing import Callable, Dict, Optional, Tuple, Union
from alibi_detect.cd.base import BaseClassifierDrift
from alibi_detect.models.tensorflow.trainer imp... | 10,298 | 48.514423 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/lsdd_online.py | from tqdm import tqdm
import numpy as np
import tensorflow as tf
from typing import Any, Callable, Optional, Union
from alibi_detect.cd.base_online import BaseMultiDriftOnline
from alibi_detect.utils.tensorflow import GaussianRBF, quantile, permed_lsdds
from alibi_detect.utils.frameworks import Framework
class LSDDDr... | 10,963 | 46.258621 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/spot_the_diff.py | import logging
import numpy as np
import tensorflow as tf
from typing import Callable, Dict, Optional, Union
from alibi_detect.cd.tensorflow.classifier import ClassifierDriftTF
from alibi_detect.utils.tensorflow.data import TFDataset
from alibi_detect.utils.tensorflow import GaussianRBF
from alibi_detect.utils.tensorfl... | 10,788 | 46.528634 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/mmd_online.py | from tqdm import tqdm
import numpy as np
import tensorflow as tf
from typing import Any, Callable, Optional, Union
from alibi_detect.cd.base_online import BaseMultiDriftOnline
from alibi_detect.utils.tensorflow.kernels import GaussianRBF
from alibi_detect.utils.tensorflow import zero_diag, quantile, subset_matrix
from ... | 10,418 | 46.144796 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/context_aware.py | import logging
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from typing import Callable, Dict, Optional, Tuple, Union, List
from alibi_detect.cd.base import BaseContextMMDDrift
from alibi_detect.utils.tensorflow.kernels import GaussianRBF
from alibi_detect.utils.warnings import deprec... | 13,836 | 45.589226 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
HiddenOutput, UAE, preprocess_drift = import_optional(
'alibi_detect.cd.tensorflow.preprocess',
names=['HiddenOutput', 'UAE', 'preprocess_drift']
)
__all__ = [
"HiddenOutput",
"UAE",
"preprocess_drift"
]
| 301 | 22.230769 | 74 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/lsdd.py | import numpy as np
import tensorflow as tf
from typing import Callable, Dict, Optional, Tuple, Union
from alibi_detect.cd.base import BaseLSDDDrift
from alibi_detect.utils.tensorflow.kernels import GaussianRBF
from alibi_detect.utils.tensorflow.distance import permed_lsdds
from alibi_detect.utils.warnings import deprec... | 7,873 | 47.306748 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/preprocess.py | from typing import Callable, Dict, Optional, Type, Union
import numpy as np
import tensorflow as tf
from alibi_detect.utils.tensorflow.prediction import (
predict_batch, predict_batch_transformer)
from tensorflow.keras.layers import Dense, Flatten, Input, InputLayer
from tensorflow.keras.models import Model
clas... | 4,509 | 36.272727 | 111 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_contextmmd_tf.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, InputLayer
from typing import Callable, List
from alibi_detect.cd.tensorflow.context_aware import ContextMMDDriftTF
from alibi_detect.cd.tensorflow.prepr... | 4,514 | 37.262712 | 102 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_classifier_tf.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input
from typing import Union
from alibi_detect.cd.tensorflow.classifier import ClassifierDriftTF
n = 100
def mymodel(shape, softmax: bool = True):
x_in = Input(shape=shape)
x = ... | 2,729 | 28.354839 | 85 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/conftest.py | import pytest
@pytest.fixture
def seed(pytestconfig):
"""
Returns the random seed set by pytest-randomly.
"""
return pytestconfig.getoption("randomly_seed")
| 175 | 16.6 | 51 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_lsdd_tf.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, InputLayer
from typing import Callable, List
from alibi_detect.cd.tensorflow.lsdd import LSDDDriftTF
from alibi_detect.cd.tensorflow.preprocess import Hi... | 4,088 | 35.508929 | 101 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_lsdd_online_tf.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, InputLayer
from typing import Callable, List
from alibi_detect.cd.tensorflow.lsdd_online import LSDDDriftOnlineTF
from alibi_detect.cd.tensorflow.preproc... | 6,400 | 35.787356 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_spot_the_diff_tf.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense
from typing import Union
from alibi_detect.cd.tensorflow.spot_the_diff import SpotTheDiffDriftTF
n = 100
class MyKernel(tf.keras.Model): # TODO: Support then test models using keras funct... | 2,674 | 27.157895 | 96 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_mmd_tf.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, InputLayer
from typing import Callable, List
from alibi_detect.cd.tensorflow.mmd import MMDDriftTF
from alibi_detect.cd.tensorflow.preprocess import Hidd... | 3,983 | 35.218182 | 96 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_mmd_online_tf.py | from functools import partial
from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, InputLayer
from typing import Callable, List
from alibi_detect.cd.tensorflow.mmd_online import MMDDriftOnlineTF
from alibi_detect.cd.tensorflow.preproces... | 6,434 | 35.771429 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_preprocess_tf.py | import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, InputLayer
from alibi_detect.cd.tensorflow import UAE, HiddenOutput
n, n_features, n_classes, latent_dim = 100, 10, 5, 2
X_uae = np.random.rand(n * n_features).reshape(n, n_features).astype('float32')
encoder_ne... | 2,732 | 29.707865 | 100 | py |
alibi-detect | alibi-detect-master/alibi_detect/cd/tensorflow/tests/test_learned_kernel_tf.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense
from typing import Union
from alibi_detect.cd.tensorflow.learned_kernel import LearnedKernelDriftTF
n = 100
class MyKernel(tf.keras.Model): # TODO: Support then test models using keras fu... | 2,479 | 26.555556 | 92 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/missing_optional_dependency.py | """Functionality for optional importing
This module provides a way to import optional dependencies. In the case that the user imports some functionality from
alibi-detect that is not usable due to missing optional dependencies this code is used to allow the import but replace
it with an object that throws an error on u... | 5,347 | 41.110236 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/url.py | from typing import Union, List
from urllib.parse import urljoin, quote_plus
def _join_url(base: str, parts: Union[str, List[str]]) -> str:
"""
Constructs a full (“absolute”) URL by combining a “base URL” (base) with additional relative URL parts.
The behaviour is similar to os.path.join() on linux, but al... | 913 | 34.153846 | 107 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/_types.py | """
Defining types compatible with different Python versions and defining custom types.
"""
import sys
from sklearn.base import BaseEstimator # import here (instead of later) since sklearn currently a core dep
from alibi_detect.utils.frameworks import has_tensorflow, has_pytorch
from typing import Union, Type
# Liter... | 1,719 | 42 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/warnings.py | """
This module defines custom warnings and exceptions used across the Alibi Detect library.
"""
import functools
import warnings
from typing import Dict, Any, Callable
def deprecated_alias(**aliases: str) -> Callable:
"""
Function decorator to warn about deprecated kwargs (and replace them).
"""
def ... | 1,119 | 32.939394 | 94 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/prediction.py | import numpy as np
from typing import Callable, Union
def tokenize_transformer(x: Union[list, np.ndarray], tokenizer: Callable, max_len: int, backend: str) -> dict:
"""
Batch tokenizer for transformer models.
Parameters
----------
x
Batch of instances.
tokenizer
Tokenizer for ... | 593 | 22.76 | 110 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/perturbation.py | import random
from io import BytesIO
from typing import List, Tuple, Union
import cv2
import numpy as np
import skimage as sk
from alibi_detect.utils.data import Bunch
from alibi_detect.utils.discretizer import Discretizer
from alibi_detect.utils.distance import abdm, multidim_scaling
from alibi_detect.utils.mapping i... | 30,754 | 31.036458 | 114 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/misc.py | import numpy as np
def quantile(sample: np.ndarray, p: float, type: int = 7,
sorted: bool = False, interpolate: bool = True) -> float:
"""
Estimate a desired quantile of a univariate distribution from a vector of samples
Parameters
----------
sample
A 1D vector of values
... | 1,556 | 28.377358 | 93 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/data.py | import numpy as np
import pandas as pd
from typing import Tuple, Union
class Bunch(dict):
"""
Container object for internal datasets
Dictionary-like object that exposes its keys as attributes.
"""
def __init__(self, **kwargs):
super().__init__(kwargs)
def __setattr__(self, key, value... | 1,920 | 26.442857 | 91 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/sampling.py | import numpy as np
import random
def reservoir_sampling(X_ref: np.ndarray,
X: np.ndarray,
reservoir_size: int,
n: int) -> np.ndarray:
"""
Apply reservoir sampling.
Parameters
----------
X_ref
Current instances in reservo... | 1,126 | 24.044444 | 58 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/statstest.py | import numpy as np
from typing import Callable, Tuple, Union
def permutation_test(x: np.ndarray, y: np.ndarray, metric: Callable, n_permutations: int = 100,
**kwargs) -> Tuple[float, float, np.ndarray]:
"""
Apply a permutation test to samples x and y.
Parameters
----------
x
... | 2,318 | 32.608696 | 95 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/_random.py | """
This submodule contains utility functions to manage random number generator (RNG) seeds. It may change
depending on how we decide to handle randomisation in tests (and elsewhere) going forwards. See
https://github.com/SeldonIO/alibi-detect/issues/250.
"""
from contextlib import contextmanager
import random
import n... | 2,127 | 24.035294 | 111 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/frameworks.py | from .missing_optional_dependency import ERROR_TYPES
from typing import Optional, List, Dict, Iterable
from enum import Enum
class Framework(str, Enum):
PYTORCH = 'pytorch'
TENSORFLOW = 'tensorflow'
KEOPS = 'keops'
SKLEARN = 'sklearn'
try:
import tensorflow as tf # noqa
import tensorflow_pr... | 5,128 | 40.699187 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/discretizer.py | import numpy as np
from typing import Dict, Callable, List
class Discretizer(object):
def __init__(self, data: np.ndarray, categorical_features: List[int], feature_names: List[str],
percentiles: List[int] = [25, 50, 75]) -> None:
"""
Initialize the discretizer.
Parameter... | 2,719 | 33 | 109 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/metrics.py | import numpy as np
def accuracy(y_true: np.ndarray, y_pred: np.ndarray) -> float:
y_true_class = np.argmax(y_true, axis=1) if len(y_true.shape) > 1 else np.round(y_true)
y_pred_class = np.argmax(y_pred, axis=1) if len(y_pred.shape) > 1 else np.round(y_pred)
return (y_true_class == y_pred_class).mean()
| 317 | 38.75 | 91 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/__init__.py | 0 | 0 | 0 | py | |
alibi-detect | alibi-detect-master/alibi_detect/utils/visualize.py | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import roc_curve, auc
from typing import Dict, Union
import warnings
def plot_instance_score(preds: Dict,
target: np.ndarray,
labels: np.ndarray,
threshol... | 11,959 | 31.588556 | 111 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/distance.py | import numpy as np
from sklearn.manifold import MDS
from typing import Any, Dict, Tuple
def norm(x: np.ndarray, p: int) -> np.ndarray:
"""
Compute p-norm across the features of a batch of instances.
Parameters
----------
x
Batch of instances of shape [N, features].
p
Power of ... | 10,244 | 35.589286 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/mapping.py | import numpy as np
from typing import Tuple, List
def ohe2ord_shape(shape: tuple, cat_vars: dict = None, is_ohe: bool = False) -> tuple:
"""
Infer shape of instance if the categorical variables have ordinal instead of on-hot encoding.
Parameters
----------
shape
Instance shape, starting w... | 4,684 | 28.651899 | 106 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/saving/saving.py | # This submodule provides a link for the legacy alibi_detect.utils.saving location of load_detector and save_detector.
# TODO: Remove in future
from alibi_detect.saving import load_detector as _load_detector, save_detector as _save_detector
from alibi_detect.base import ConfigurableDetector, Detector
from typing impor... | 1,576 | 32.553191 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/saving/__init__.py | from alibi_detect.utils.saving.saving import save_detector, load_detector # noqa
| 82 | 40.5 | 81 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_data.py | from itertools import product
import numpy as np
import pytest
from alibi_detect.utils.data import create_outlier_batch, Bunch
N, F = 1000, 4
X = np.random.rand(N, F)
y = np.zeros(N,)
y[:int(.5 * N)] = 1
n_samples = [50, 100]
perc_outlier = [10, 50]
tests = list(product(n_samples, perc_outlier))
n_tests = len(tests)... | 875 | 26.375 | 77 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_distance.py | import numpy as np
from scipy.spatial.distance import cityblock
from itertools import product
import pytest
from alibi_detect.utils.distance import pairwise_distance, abdm, cityblock_batch, mvdm, multidim_scaling
n_features = [2, 5]
n_instances = [(100, 100), (100, 75)]
tests_pairwise = list(product(n_features, n_inst... | 4,041 | 31.861789 | 104 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_saving_legacy.py | """
Tests for saving/loading of detectors with legacy .dill state_dict. As legacy save/load functionality becomes
deprecated, these tests will be removed, and more tests will be added to test_saving.py.
"""
from alibi_detect.utils.missing_optional_dependency import MissingDependency
from functools import partial
import... | 10,367 | 40.806452 | 112 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/conftest.py | import pytest
@pytest.fixture
def seed(pytestconfig):
"""
Returns the random seed set by pytest-randomly.
"""
return pytestconfig.getoption("randomly_seed")
| 175 | 16.6 | 51 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_mapping.py | import numpy as np
import alibi_detect.utils.mapping as mp
X_ohe = np.array([[0, 1, 0.1, 1, 0, 0.2]]).astype(np.float32)
shape_ohe = X_ohe.shape
cat_vars_ohe = {0: 2, 3: 2}
is_ohe = True
X_ord = np.array([[1., 0.1, 0., 0.2]]).astype(np.float32)
shape_ord = X_ord.shape
cat_vars_ord = {0: 2, 2: 2}
dist = {0: np.array(... | 1,095 | 28.621622 | 80 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_sampling.py | from itertools import product
import numpy as np
import pytest
from alibi_detect.utils.sampling import reservoir_sampling
n_X_ref = [5, 10, 100]
n_X = [2, 5, 100]
reservoir_size = [10, 500]
n = [100, 1000]
n_features = 5
tests_sampling = list(product(n_X_ref, n_X, reservoir_size, n))
n_tests = len(tests_sampling)
@p... | 1,108 | 31.617647 | 80 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_discretize.py | from itertools import product
import numpy as np
import pytest
from alibi_detect.utils.discretizer import Discretizer
x = np.random.rand(10, 4)
n_features = x.shape[1]
feature_names = [str(_) for _ in range(n_features)]
categorical_features = [[], [1, 3]]
percentiles = [list(np.arange(25, 100, 25)), list(np.arange(10... | 1,195 | 30.473684 | 85 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_random.py | from alibi_detect.utils._random import set_seed, get_seed, fixed_seed
import numpy as np
import tensorflow as tf
import torch
def test_set_get_seed(seed):
"""
Tests the set_seed and get_seed fuctions.
"""
# Check initial seed within test is the one set by pytest-randomly
current_seed = get_seed()
... | 1,848 | 28.822581 | 90 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_backend_verify.py | import pytest
from alibi_detect.utils.missing_optional_dependency import ERROR_TYPES
from alibi_detect.utils.frameworks import BackendValidator, HAS_BACKEND
class TestBackendValidator:
"""Test the BackendValidator class."""
def setup_method(self):
# mock missing dependency error for non existent modu... | 3,234 | 47.283582 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/mocked_opt_dep.py | import non_existent_module # noqa: F401
class MockedClassMissingRequiredDeps:
def __init__(self):
self.opt_dep = "opt_dep"
def mocked_function_missing_required_deps():
pass
class MockedClassMissingMultipleRequiredDeps:
def __init__(self):
pass
| 279 | 16.5 | 45 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_import_optional.py | import pytest
from alibi_detect.utils.missing_optional_dependency import import_optional, MissingDependency, ERROR_TYPES
class TestImportOptional:
"""Test the import_optional function."""
def setup_method(self):
# mock missing dependency error for non existent module
ERROR_TYPES['non_existen... | 2,918 | 46.852459 | 116 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_perturbation.py | from functools import reduce
from itertools import product
from operator import mul
import numpy as np
import pytest
from alibi_detect.utils.data import Bunch
from alibi_detect.utils.perturbation import apply_mask, inject_outlier_ts
from alibi_detect.utils.tensorflow.perturbation import mutate_categorical
x = np.rando... | 3,642 | 35.79798 | 92 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tests/test_statstest.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from alibi_detect.utils.tensorflow import GaussianRBF, mmd2
from alibi_detect.utils.statstest import fdr, permutation_test
q_val = [.05, .1, .25]
n_p = 1000
p_vals = [
{'is_below': True, 'p_val': np.zeros(n_p)},
{'is_below':... | 2,191 | 30.768116 | 95 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/state/state.py | import os
from pathlib import Path
import logging
from abc import ABC
from typing import Union, Tuple
import numpy as np
from alibi_detect.utils.frameworks import Framework
from alibi_detect.utils.state._pytorch import save_state_dict as _save_state_dict_pt,\
load_state_dict as _load_state_dict_pt
logger = logging... | 3,881 | 32.756522 | 116 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/state/__init__.py | from alibi_detect.utils.state.state import StateMixin, _save_state_dict, _load_state_dict
__all__ = [
"StateMixin",
"_save_state_dict",
"_load_state_dict",
]
| 171 | 20.5 | 89 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/state/_pytorch/state.py | """
Submodule to handle saving and loading of detector state dictionaries when the dictionaries contain `torch.Tensor`'s.
"""
from pathlib import Path
import torch
def save_state_dict(state_dict: dict, filepath: Path):
"""
Utility function to save a detector's state dictionary to a filepath using `torch.save`... | 870 | 22.540541 | 117 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/state/_pytorch/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
save_state_dict, load_state_dict = import_optional(
'alibi_detect.utils.state._pytorch.state',
names=['save_state_dict', 'load_state_dict']
)
__all__ = [
"save_state_dict",
"load_state_dict",
]
| 288 | 21.230769 | 74 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/keops/kernels.py | from pykeops.torch import LazyTensor
import torch
import torch.nn as nn
from typing import Callable, Optional, Union
from alibi_detect.utils.frameworks import Framework
from alibi_detect.utils._types import Literal
from copy import deepcopy
def sigma_mean(x: LazyTensor, y: LazyTensor, dist: LazyTensor, n_min: int = 1... | 9,448 | 42.543779 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/keops/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
GaussianRBF, DeepKernel = import_optional(
'alibi_detect.utils.keops.kernels',
names=['GaussianRBF', 'DeepKernel']
)
__all__ = [
"GaussianRBF",
"DeepKernel"
]
| 253 | 18.538462 | 74 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/keops/tests/test_kernels_keops.py | from itertools import product
import numpy as np
from alibi_detect.utils.frameworks import has_keops
import pytest
import torch
import torch.nn as nn
if has_keops:
from pykeops.torch import LazyTensor
from alibi_detect.utils.keops import DeepKernel, GaussianRBF
sigma = [None, np.array([1.]), np.array([1., 2.])... | 4,889 | 39.081967 | 90 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/fetching/fetching.py | import logging
import os
from io import BytesIO
from pathlib import Path
from typing import Union, TYPE_CHECKING, Tuple
import dill
import requests
from requests import RequestException
import tensorflow as tf
from tensorflow.python.keras import backend
from alibi_detect.models.tensorflow import PixelCNN
from alibi_... | 16,646 | 30.115888 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/fetching/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
fetch_detector, fetch_tf_model = import_optional('alibi_detect.utils.fetching.fetching',
names=['fetch_detector', 'fetch_tf_model'])
__all__ = ['fetch_tf_model', 'fetch_detector']
| 306 | 42.857143 | 92 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/losses.py | import torch
def hinge_loss(preds: torch.Tensor) -> torch.Tensor:
"L(pred) = max(0, 1-pred) averaged over multiple preds"
linear_inds = preds < 1
return (((1 - preds)*linear_inds).sum(0))/len(preds)
| 213 | 25.75 | 59 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/kernels.py | import numpy as np
import torch
from torch import nn
from . import distance
from typing import Optional, Union, Callable
from alibi_detect.utils.frameworks import Framework
def sigma_median(x: torch.Tensor, y: torch.Tensor, dist: torch.Tensor) -> torch.Tensor:
"""
Bandwidth estimation using the median heurist... | 7,088 | 37.737705 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/prediction.py | from functools import partial
from typing import Callable, Optional, Type, Union
import numpy as np
import torch
import torch.nn as nn
from alibi_detect.utils.pytorch.misc import get_device
from alibi_detect.utils.prediction import tokenize_transformer
def predict_batch(x: Union[list, np.ndarray, torch.Tensor], mode... | 4,639 | 42.364486 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/misc.py | import logging
from typing import Optional, Union, Type
import torch
logger = logging.getLogger(__name__)
def zero_diag(mat: torch.Tensor) -> torch.Tensor:
"""
Set the diagonal of a matrix to 0
Parameters
----------
mat
A 2D square matrix
Returns
-------
A 2D square matrix ... | 3,133 | 26.017241 | 112 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/data.py | import numpy as np
import torch
from typing import Tuple, Union
Indexable = Union[np.ndarray, torch.Tensor, list]
class TorchDataset(torch.utils.data.Dataset):
def __init__(self, *indexables: Union[Tuple[Indexable, ...], Indexable]) -> None:
self.indexables = indexables
def __getitem__(self, idx: in... | 565 | 30.444444 | 85 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
TorchDataset = import_optional(
'alibi_detect.utils.pytorch.data',
names=['TorchDataset']
)
mmd2, mmd2_from_kernel_matrix, squared_pairwise_distance, permed_lsdds, batch_compute_kernel_matrix = import_optional(
'alibi_detect.utils... | 1,218 | 26.088889 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/distance.py | import logging
import torch
from torch import nn
import numpy as np
from typing import Callable, List, Tuple, Optional, Union
logger = logging.getLogger(__name__)
@torch.jit.script
def squared_pairwise_distance(x: torch.Tensor, y: torch.Tensor, a_min: float = 1e-30) -> torch.Tensor:
"""
PyTorch pairwise squa... | 8,767 | 36.470085 | 110 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/tests/test_data_pt.py | import numpy as np
import pytest
from alibi_detect.utils.pytorch.data import TorchDataset
# test on numpy array and list
n, f = 100, 5
shape = (n, f)
tests_ds = [list, np.ndarray]
n_tests_ds = len(tests_ds)
@pytest.fixture
def ds_params(request):
return tests_ds[request.param]
@pytest.mark.parametrize('ds_para... | 692 | 22.896552 | 77 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/tests/test_distance_pt.py | import numpy as np
from itertools import product
import pytest
import torch
from alibi_detect.utils.pytorch import GaussianRBF, mmd2, mmd2_from_kernel_matrix, permed_lsdds
from alibi_detect.utils.pytorch import squared_pairwise_distance, batch_compute_kernel_matrix
n_features = [2, 5]
n_instances = [(100, 100), (100, ... | 5,181 | 32.869281 | 101 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/tests/test_misc_pt.py | from itertools import product
import pytest
import torch
import numpy as np
from alibi_detect.utils.pytorch import zero_diag, quantile
def test_zero_diag():
ones = torch.ones(10, 10)
ones_zd = zero_diag(ones)
assert ones_zd.shape == (10, 10)
assert float(ones_zd.trace()) == 0
assert float(ones_zd.... | 1,317 | 29.651163 | 103 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/tests/test_prediction_pt.py | import numpy as np
import pytest
import torch
import torch.nn as nn
from typing import Tuple, Union
from alibi_detect.utils.pytorch import predict_batch
n, n_features, n_classes, latent_dim = 100, 10, 5, 2
x = np.zeros((n, n_features), dtype=np.float32)
class MyModel(nn.Module):
def __init__(self, multi_out: boo... | 2,498 | 33.232877 | 106 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/pytorch/tests/test_kernels_pt.py | from itertools import product
import numpy as np
import pytest
import torch
from torch import nn
from alibi_detect.utils.pytorch import GaussianRBF, DeepKernel
sigma = [None, np.array([1.]), np.array([1., 2.])]
n_features = [5, 10]
n_instances = [(100, 100), (100, 75)]
trainable = [True, False]
tests_gk = list(product... | 3,294 | 38.22619 | 90 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/kernels.py | import tensorflow as tf
import numpy as np
from . import distance
from typing import Optional, Union, Callable
from scipy.special import logit
from alibi_detect.utils.frameworks import Framework
def sigma_median(x: tf.Tensor, y: tf.Tensor, dist: tf.Tensor) -> tf.Tensor:
"""
Bandwidth estimation using the medi... | 7,226 | 38.708791 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/prediction.py | from functools import partial
from typing import Callable, Type, Union
import numpy as np
import tensorflow as tf
from alibi_detect.utils.prediction import tokenize_transformer
def predict_batch(x: Union[list, np.ndarray, tf.Tensor], model: Union[Callable, tf.keras.Model],
batch_size: int = int(1e1... | 3,418 | 36.988889 | 112 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/perturbation.py | import numpy as np
import tensorflow as tf
def mutate_categorical(X: np.ndarray,
rate: float = None,
seed: int = 0,
feature_range: tuple = (0, 255)) -> tf.Tensor:
"""
Randomly change integer feature values to values within a set range
wi... | 1,214 | 24.851064 | 85 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/misc.py | import tensorflow as tf
def zero_diag(mat: tf.Tensor) -> tf.Tensor:
"""
Set the diagonal of a matrix to 0
Parameters
----------
mat
A 2D square matrix
Returns
-------
A 2D square matrix with zeros along the diagonal
"""
return mat - tf.linalg.diag(tf.linalg.diag_part(... | 2,661 | 26.163265 | 93 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/data.py | import numpy as np
import tensorflow as tf
from typing import Tuple, Union
Indexable = Union[np.ndarray, tf.Tensor, list]
class TFDataset(tf.keras.utils.Sequence):
def __init__(
self, *indexables: Indexable, batch_size: int = int(1e10), shuffle: bool = True,
) -> None:
self.indexables = i... | 1,105 | 34.677419 | 96 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
mmd2, mmd2_from_kernel_matrix, batch_compute_kernel_matrix, relative_euclidean_distance, squared_pairwise_distance, \
permed_lsdds = import_optional(
'alibi_detect.utils.tensorflow.distance',
names=['mmd2', 'mmd2_from_kernel... | 1,505 | 24.965517 | 117 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/distance.py | import logging
import numpy as np
import tensorflow as tf
from typing import Callable, Tuple, List, Optional, Union
logger = logging.getLogger(__name__)
def squared_pairwise_distance(x: tf.Tensor, y: tf.Tensor, a_min: float = 1e-30, a_max: float = 1e30) -> tf.Tensor:
"""
TensorFlow pairwise squared Euclidean... | 9,181 | 36.024194 | 118 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/tests/test_data_tf.py | from itertools import product
import numpy as np
import pytest
from alibi_detect.utils.tensorflow.data import TFDataset
# test on numpy array and list
n, f = 100, 5
shape = (n, f)
xtype = [list, np.ndarray]
shuffle = [True, False]
batch_size = [2, 10]
tests_ds = list(product(xtype, batch_size, shuffle))
n_tests_ds = l... | 1,094 | 27.076923 | 77 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/tests/test_prediction_tf.py | import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, InputLayer
from typing import Tuple, Union
from alibi_detect.utils.tensorflow import predict_batch
n, n_features, n_classes, latent_dim = 100, 10, 5, 2
x = np.zeros((n, n_features), dtype=np.float32)
class MyModel(tf.... | 2,557 | 32.657895 | 106 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/tests/test_misc_tf.py | from itertools import product
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, InputLayer
import numpy as np
from alibi_detect.utils.tensorflow import zero_diag, quantile, subset_matrix
from alibi_detect.utils.tensorflow.misc import clone_model
def test_zero_diag():
ones = t... | 3,046 | 29.168317 | 103 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/tests/test_kernels_tf.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input
from alibi_detect.utils.tensorflow import GaussianRBF, DeepKernel
sigma = [None, np.array([1.]), np.array([1., 2.])]
n_features = [5, 10]
n_instances = [(100, 100), (100, 75)]
trainab... | 3,271 | 38.421687 | 92 | py |
alibi-detect | alibi-detect-master/alibi_detect/utils/tensorflow/tests/test_distance_tf.py | import numpy as np
from itertools import product
import pytest
import tensorflow as tf
from alibi_detect.utils.tensorflow import GaussianRBF, mmd2, mmd2_from_kernel_matrix, permed_lsdds
from alibi_detect.utils.tensorflow import relative_euclidean_distance, squared_pairwise_distance
from alibi_detect.utils.tensorflow im... | 5,789 | 34.304878 | 105 | py |
alibi-detect | alibi-detect-master/alibi_detect/ad/model_distillation.py | import logging
from typing import Callable, Dict, Tuple, Union, cast
import numpy as np
import tensorflow as tf
from alibi_detect.base import (BaseDetector, FitMixin, ThresholdMixin,
adversarial_prediction_dict)
from alibi_detect.models.tensorflow.losses import loss_distillation
from ali... | 7,963 | 34.238938 | 111 | py |
alibi-detect | alibi-detect-master/alibi_detect/ad/adversarialae.py | import logging
from typing import Callable, Dict, List, Tuple, Union, cast
import numpy as np
import tensorflow as tf
from alibi_detect.base import (BaseDetector, FitMixin, ThresholdMixin,
adversarial_correction_dict,
adversarial_prediction_dict)
from alibi... | 13,401 | 36.858757 | 114 | py |
alibi-detect | alibi-detect-master/alibi_detect/ad/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
AdversarialAE = import_optional('alibi_detect.ad.adversarialae', names=['AdversarialAE'])
ModelDistillation = import_optional('alibi_detect.ad.model_distillation', names=['ModelDistillation'])
__all__ = [
"AdversarialAE",
"ModelDistill... | 329 | 32 | 102 | py |
alibi-detect | alibi-detect-master/alibi_detect/ad/tests/test_admd.py | from itertools import product
import numpy as np
import pytest
from sklearn.datasets import load_iris
import tensorflow as tf
from tensorflow.keras.utils import to_categorical
from alibi_detect.ad import ModelDistillation
from alibi_detect.version import __version__
threshold = [None, 5.]
loss_type = ['kld', 'xent']
t... | 2,717 | 33.405063 | 104 | py |
alibi-detect | alibi-detect-master/alibi_detect/ad/tests/test_adae.py | from itertools import product
import numpy as np
import pytest
from sklearn.datasets import load_iris
import tensorflow as tf
from tensorflow.keras.layers import Dense, InputLayer
from tensorflow.keras.utils import to_categorical
from alibi_detect.ad import AdversarialAE
from alibi_detect.version import __version__
th... | 3,044 | 31.741935 | 101 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.