repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
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/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/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/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/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/_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/_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/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/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/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/_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/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/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/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/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/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/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 |
alibi-detect | alibi-detect-master/doc/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 11,119 | 31.138728 | 139 | py |
StarGANv2-VC | StarGANv2-VC-main/losses.py | #coding:utf-8
import os
import torch
from torch import nn
from munch import Munch
from transforms import build_transforms
import torch.nn.functional as F
import numpy as np
def compute_d_loss(nets, args, x_real, y_org, y_trg, z_trg=None, x_ref=None, use_r1_reg=True, use_adv_cls=False, use_con_reg=False):
args =... | 7,608 | 34.390698 | 132 | py |
StarGANv2-VC | StarGANv2-VC-main/optimizers.py | #coding:utf-8
import os, sys
import os.path as osp
import numpy as np
import torch
from torch import nn
from torch.optim import Optimizer
from functools import reduce
from torch.optim import AdamW
class MultiOptimizer:
def __init__(self, optimizers={}, schedulers={}):
self.optimizers = optimizers
s... | 2,460 | 32.256757 | 103 | py |
StarGANv2-VC | StarGANv2-VC-main/meldataset.py | #coding: utf-8
import os
import time
import random
import random
import torch
import torchaudio
import numpy as np
import soundfile as sf
import torch.nn.functional as F
from torch import nn
from torch.utils.data import DataLoader
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
n... | 5,161 | 32.089744 | 100 | py |
StarGANv2-VC | StarGANv2-VC-main/models.py | """
StarGAN v2
Copyright (c) 2020-present NAVER Corp.
This work is licensed under the Creative Commons Attribution-NonCommercial
4.0 International License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
Creative Commons, PO Box 1866, Mountain View, CA 94042, USA... | 13,766 | 34.3 | 124 | py |
StarGANv2-VC | StarGANv2-VC-main/train.py | #!/usr/bin/env python3
#coding:utf-8
import os
import os.path as osp
import re
import sys
import yaml
import shutil
import numpy as np
import torch
import click
import warnings
warnings.simplefilter('ignore')
from functools import reduce
from munch import Munch
from meldataset import build_dataloader
from optimizers... | 5,523 | 34.184713 | 90 | py |
StarGANv2-VC | StarGANv2-VC-main/trainer.py | # -*- coding: utf-8 -*-
import os
import os.path as osp
import sys
import time
from collections import defaultdict
import numpy as np
import torch
from torch import nn
from PIL import Image
from tqdm import tqdm
from losses import compute_d_loss, compute_g_loss
import logging
logger = logging.getLogger(__name__)
lo... | 11,715 | 40.399293 | 175 | py |
StarGANv2-VC | StarGANv2-VC-main/transforms.py | # -*- coding: utf-8 -*-
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import torchaudio
import torchaudio.functional as audio_F
import random
## 1. RandomTimeStrech
class TimeStrech(nn.Module):
def __init__(self, scale):
super(TimeStrech, self).__init__()
se... | 3,552 | 28.363636 | 106 | py |
StarGANv2-VC | StarGANv2-VC-main/Utils/JDC/model.py | """
Implementation of model from:
Kum et al. - "Joint Detection and Classification of Singing Voice Melody Using
Convolutional Recurrent Neural Networks" (2019)
Link: https://www.semanticscholar.org/paper/Joint-Detection-and-Classification-of-Singing-Voice-Kum-Nam/60a2ad4c7db43bace75805054603747fcd062c0d
"""
import tor... | 7,157 | 39.670455 | 144 | py |
StarGANv2-VC | StarGANv2-VC-main/Utils/ASR/layers.py | import math
import torch
from torch import nn
from typing import Optional, Any
from torch import Tensor
import torch.nn.functional as F
import torchaudio
import torchaudio.functional as audio_F
import random
random.seed(0)
def _get_activation_fn(activ):
if activ == 'relu':
return nn.ReLU()
elif activ... | 13,454 | 36.901408 | 143 | py |
StarGANv2-VC | StarGANv2-VC-main/Utils/ASR/models.py | import math
import torch
from torch import nn
from torch.nn import TransformerEncoder
import torch.nn.functional as F
from .layers import MFCC, Attention, LinearNorm, ConvNorm, ConvBlock
class ASRCNN(nn.Module):
def __init__(self,
input_dim=80,
hidden_dim=256,
n_t... | 7,272 | 37.893048 | 118 | py |
Signal-is-Harder | Signal-is-Harder-main/train_vanilla.py | import os
import yaml
import argparse
import wandb
import time
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
import torch.optim as optim
from data.util import get_dataset, IdxDataset
from module.util import get_model
from util import set_seed, get_optimizer, evaluate
def main():
... | 7,018 | 32.42381 | 249 | py |
Signal-is-Harder | Signal-is-Harder-main/make_dataset.py | '''Modified from https://github.com/alinlab/LfF/blob/master/util.py'''
import os
from re import A
from xmlrpc.client import Boolean
from tqdm import tqdm
import pickle
import numpy as np
import torch
from torchvision.datasets import CIFAR10, MNIST
import torchvision.transforms as T
from data.corrupted_cifar10_protoc... | 41,294 | 46.194286 | 133 | py |
Signal-is-Harder | Signal-is-Harder-main/util.py | import os
import random
import numpy as np
import torch
from tqdm import tqdm
import torch.nn as nn
import torch.nn.functional as F
import wandb
from torchvision.transforms.functional import normalize
def set_seed(seed):
"""
Set all random seeds
Args:
seed (int): integer for reproducible experim... | 28,920 | 45.646774 | 229 | py |
Signal-is-Harder | Signal-is-Harder-main/train.py | import os
import yaml
import argparse
import wandb
import time
import sys
from tqdm import tqdm
import numpy as np
from uuid import uuid4
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.transforms.functional import ... | 18,917 | 48.010363 | 285 | py |
Signal-is-Harder | Signal-is-Harder-main/module/resnet_vae.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torchvision.models import resnet18
from module.resnet import resnet20
class ResNet_VAE(nn.Module):
def __init__(self, num_classes = 10, bottleneck=512):
super(ResNet_VAE, self).__init__()
self.enco... | 5,542 | 33.216049 | 119 | py |
Signal-is-Harder | Signal-is-Harder-main/module/mlp_vae.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class MLP_VAE(nn.Module):
def __init__(self, num_classes = 10, bottleneck = 16):
super(MLP_VAE, self).__init__()
self.encoder = MLP_Encoder(bottleneck = bottleneck)
self.decoder = MLP_Decoder(bottleneck = bottleneck)
... | 2,499 | 25.041667 | 96 | py |
Signal-is-Harder | Signal-is-Harder-main/module/resnet.py | ''' From https://github.com/alinlab/LfF/blob/master/module/resnet.py '''
"""
Properly implemented ResNet-s for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the imp... | 6,138 | 27.290323 | 78 | py |
Signal-is-Harder | Signal-is-Harder-main/module/mlp.py | ''' From https://github.com/alinlab/LfF/blob/master/module/MLP.py '''
import torch
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, num_classes = 10):
super(MLP, self).__init__()
self.feature = nn.Sequential(
nn.Linear(3 * 28*28, 100),
nn.ReLU(),
n... | 721 | 25.740741 | 69 | py |
Signal-is-Harder | Signal-is-Harder-main/module/util.py | ''' Modified from https://github.com/alinlab/LfF/blob/master/module/util.py '''
import torch.nn as nn
from module.resnet import resnet20
from module.mlp import MLP
from module.mlp_vae import MLP_VAE
from module.resnet_vae import ResNet_VAE
from torchvision.models import resnet18, resnet50
def get_model(config):
m... | 2,150 | 36.736842 | 100 | py |
Signal-is-Harder | Signal-is-Harder-main/data/rotated_mnist_protocol.py | import os
from functools import partial
import torchvision.transforms.functional as F
dir_path = os.path.dirname(os.path.realpath(__file__))
def rotate(raw_image, severity, attribute_label):
if severity==0:
raise NotImplementedError("Need severity != 0")
rotation = 90/(5-severity)
if attribute_lab... | 662 | 32.15 | 76 | py |
Signal-is-Harder | Signal-is-Harder-main/data/attr_dataset.py | '''Modified from https://github.com/alinlab/LfF/blob/master/data/attr_dataset.py'''
import os
import pickle
import torch
import numpy as np
from torch.utils.data import Dataset
class AttributeDataset(Dataset):
def __init__(self, root, split, query_attr_idx=None, transform=None):
super(AttributeDataset, s... | 1,335 | 31.585366 | 83 | py |
Signal-is-Harder | Signal-is-Harder-main/data/shifted_mnist_protocol.py | import os
from functools import partial
import torchvision.transforms.functional as F
dir_path = os.path.dirname(os.path.realpath(__file__))
def shift(raw_image, severity, attribute_label):
if severity==0:
raise NotImplementedError("Need severity != 0")
translation = 8/(5-severity)
if attribute_la... | 845 | 35.782609 | 131 | py |
Signal-is-Harder | Signal-is-Harder-main/data/util.py | '''Modified from https://github.com/alinlab/LfF/blob/master/data/util.py'''
import os
import numpy as np
import torch
from torch.utils.data.dataset import Dataset, Subset
from torch.utils.data import Sampler, random_split
from torchvision import transforms as T
from data.attr_dataset import AttributeDataset
from func... | 4,488 | 29.746575 | 109 | py |
Signal-is-Harder | Signal-is-Harder-main/data/colored_mnist_protocol.py | '''Modified from https://github.com/alinlab/LfF/blob/master/data/colored_mnist_protocol.py'''
import os
import torch
import numpy as np
from functools import partial
dir_path = os.path.dirname(os.path.realpath(__file__))
colors_path = os.path.join(dir_path, "resource", "colors.th")
mean_color = torch.load(colors_path... | 742 | 31.304348 | 93 | py |
Multi2WOZ | Multi2WOZ-main/specialization/trainer_self.py | # coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | 102,647 | 46.765472 | 146 | py |
Multi2WOZ | Multi2WOZ-main/downstream/main_cl.py | from tqdm import tqdm
import torch.nn as nn
import ast
import glob
import numpy as np
import copy
# utils
from utils.config import *
from utils.utils_general import *
from utils.utils_multiwoz_cl import *
from utils.utils_oos_intent import *
from utils.utils_universal_act import *
# models
from models.BERT_DST_Pick... | 11,553 | 42.931559 | 114 | py |
Multi2WOZ | Multi2WOZ-main/downstream/tod_xlmr_pretraining.py | import argparse
import glob
import logging
import os
import pickle
import random
import re
import shutil
from typing import Tuple
import gzip
import shelve
import json
import math
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler, TensorDataset
from torch... | 44,684 | 42.595122 | 141 | py |
Multi2WOZ | Multi2WOZ-main/downstream/main_cl-continue.py | from tqdm import tqdm
import torch.nn as nn
import ast
import glob
import numpy as np
import copy
# utils
from utils.config import *
from utils.utils_general import *
from utils.utils_multiwoz_cl import *
from utils.utils_oos_intent import *
from utils.utils_universal_act import *
# models
from models.BERT_DST_Pick... | 14,594 | 46.386364 | 159 | py |
Multi2WOZ | Multi2WOZ-main/downstream/models/dual_encoder_ranking.py | import os.path
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.nn import CrossEntropyLoss
from torch.nn import CosineEmbeddingLoss
from sklearn.metrics import f1_score #, average_precision_score
import numpy as np
from transformers import *
import log... | 6,321 | 40.320261 | 132 | py |
Multi2WOZ | Multi2WOZ-main/downstream/models/BERT_DST_Picklist.py | import os.path
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from torch.nn import CosineEmbeddingLoss
import numpy as np
from transformers import *
def _gelu(x):
""" Original Implementation of the gelu activation function in Google Bert repo ... | 11,918 | 42.5 | 141 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/dataloader_nlg.py | import torch
import torch.utils.data as data
import random
from .utils_function import to_cuda, merge
# from .config import *
class Dataset_nlg(torch.utils.data.Dataset):
"""Custom data.Dataset compatible with data.DataLoader."""
def __init__(self, data_info, tokenizer, args, unified_meta, mode, max_length=5... | 7,624 | 43.590643 | 115 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/dataloader_nlu.py | import torch
import torch.utils.data as data
# from .config import *
from .utils_function import to_cuda, merge, merge_multi_response, merge_sent_and_word
class Dataset_nlu(torch.utils.data.Dataset):
"""Custom data.Dataset compatible with data.DataLoader."""
def __init__(self, data_info, tokenizer, args, unifi... | 4,513 | 37.254237 | 115 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/dataloader_dm.py | import torch
import torch.utils.data as data
# from .config import *
from .utils_function import to_cuda, merge, merge_multi_response, merge_sent_and_word
class Dataset_dm(torch.utils.data.Dataset):
"""Custom data.Dataset compatible with data.DataLoader."""
def __init__(self, data_info, tokenizer, args, unifie... | 4,048 | 37.561905 | 137 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/utils_function.py | import torch
import numpy as np
PAD_token = 0
def to_cuda(x):
if torch.cuda.is_available(): x = x.cuda()
return x
def merge(sequences, ignore_idx=None):
'''
merge from batch * sent_len to batch * max_len
'''
pad_token = PAD_token if type(ignore_idx)==type(None) else ignore_idx
lengths =... | 3,659 | 28.28 | 82 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/config.py | import os
import logging
import argparse
from tqdm import tqdm
import torch
import numpy as np
parser = argparse.ArgumentParser(description='Task-oriented Dialogue System Benchmarking')
## Training Setting
parser.add_argument(
'--do_train', action='store_true', help="do training")
parser.add_argument(
'-ep... | 10,339 | 47.093023 | 150 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/dataloader_dst.py | import torch
import numpy as np
import torch.utils.data as data
from .utils_function import to_cuda, merge, merge_multi_response, merge_sent_and_word
# SLOT_GATE = {"ptr":0, "dontcare":1, "none":2}
class Dataset_dst(torch.utils.data.Dataset):
"""Custom data.Dataset compatible with data.DataLoader."""
def __in... | 6,765 | 41.2875 | 137 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/utils_general.py | import torch
import torch.utils.data as data
import random
import math
from .dataloader_dst import *
from .dataloader_nlg import *
from .dataloader_nlu import *
from .dataloader_dm import *
from .dataloader_usdl import *
def get_loader(args, mode, tokenizer, datasets, unified_meta, shuffle=False):
task = args["ta... | 3,348 | 39.349398 | 122 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/dataloader_usdl.py | import torch
import torch.utils.data as data
from .utils_function import to_cuda, merge, merge_multi_response, merge_sent_and_word
class Dataset_usdl(torch.utils.data.Dataset):
"""Custom data.Dataset compatible with data.DataLoader."""
def __init__(self, data_info, tokenizer, args, unified_meta, mode, max_leng... | 5,245 | 38.742424 | 118 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/utils_domain.py | import torch
import torch.utils.data as data
import random
import math
from .dataloader_dst import *
from .dataloader_nlg import *
from .dataloader_nlu import *
from .dataloader_dm import *
from .dataloader_usdl import *
def get_loader(args, mode, tokenizer, datasets, unified_meta, shuffle=False):
task = args["ta... | 3,348 | 39.349398 | 122 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/multiwoz/fix_label.py |
def fix_general_label_error(labels, type, slots, ontology_version=""):
label_dict = dict([ (l[0], l[1]) for l in labels]) if type else dict([ (l["slots"][0][0], l["slots"][0][1]) for l in labels])
GENERAL_TYPO = {
# type
"guesthouse":"guest house","guesthouses":"guest house","guest":"guest ho... | 24,598 | 59.439803 | 167 | py |
Multi2WOZ | Multi2WOZ-main/downstream/utils/loss_function/masked_cross_entropy.py | import torch
from torch.nn import functional
from torch.autograd import Variable
from utils.config import *
import torch.nn as nn
import numpy as np
def sequence_mask(sequence_length, max_len=None):
if max_len is None:
max_len = sequence_length.data.max()
batch_size = sequence_length.size(0)
seq_ra... | 6,501 | 36.802326 | 92 | py |
custom-diffusion | custom-diffusion-main/sample.py | # This code is built from the Stable Diffusion repository: https://github.com/CompVis/stable-diffusion.
# Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors.
# CreativeML Open RAIL-M
#
# ==========================================================================================
#
# Adobe’s modifications... | 27,272 | 62.131944 | 1,097 | py |
custom-diffusion | custom-diffusion-main/train.py | # This code is built from the Stable Diffusion repository: https://github.com/CompVis/stable-diffusion.
# Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors.
# CreativeML Open RAIL-M
#
# ==========================================================================================
#
# Adobe’s modifications... | 48,845 | 48.389282 | 1,097 | py |
custom-diffusion | custom-diffusion-main/src/diffusers_model_pipeline.py | # This code is built from the Huggingface repository: https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py, and
# https://github.com/huggingface/diffusers/blob/main/examples/textual_inversion/textual_inversion.py
# Copyright 2022- The Hugging Face team. All rights reserved.
# ... | 25,547 | 50.198397 | 149 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.