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 |
|---|---|---|---|---|---|---|
text-classification-cnn-rnn | text-classification-cnn-rnn-master/helper/__init__.py | 0 | 0 | 0 | py | |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/data/cnews_loader.py | # coding: utf-8
import sys
from collections import Counter
import numpy as np
import tensorflow.keras as kr
if sys.version_info[0] > 2:
is_py3 = True
else:
reload(sys)
sys.setdefaultencoding("utf-8")
is_py3 = False
def native_word(word, encoding='utf-8'):
"""如果在python2下面使用python3训练的模型,可考虑调用此函数转... | 3,386 | 25.255814 | 92 | py |
text-classification-cnn-rnn | text-classification-cnn-rnn-master/data/__init__.py | 0 | 0 | 0 | py | |
graph-ismorphism | graph-ismorphism-master/assets/time-complexity.py | """
alganal.py
Description:
A utility program to plot algorithmic time complexity of a function.
Author: Mahesh Venkitachalam
Website: electronut.in
"""
from matplotlib import pyplot
import numpy as np
import timeit
from functools import partial
import random
def fconst(N):
"""
O(1) function
"""
x ... | 1,480 | 17.283951 | 68 | py |
graph-ismorphism | graph-ismorphism-master/program/main.py | #! /usr/bin/python2.7
"""
Main logic
"""
from tester import Tester
if __name__ == "__main__":
"""
Command line handling
"""
tester = Tester()
# tester.test_1() # Search
# tester.test_2() # Search
# tester.test_3() # Search
# tester.test_4() # Search
# tester.test_5() # Run Sat Sol... | 869 | 25.363636 | 64 | py |
graph-ismorphism | graph-ismorphism-master/program/gi.py | #! /usr/bin/python2.7
"""
Logic for generating and timing graphs using Traces package
"""
import datetime
import re
import signal
from handlers.exceptionhandler import signal_handler, TimeoutError
from handlers.filehandler import FileHandler
from handlers.processhandler import ProcessHandler
import networkx as nx
imp... | 11,302 | 33.045181 | 104 | py |
graph-ismorphism | graph-ismorphism-master/program/tester.py | #! /usr/bin/python2.7
"""
Main logic
"""
from sat import Sat
from gi import Gi
from main_logic import Main
from handlers.filehandler import FileHandler
from handlers.plothandler import PlotHandler
from handlers.processhandler import ProcessHandler
# Tests
class Tester(object):
def test_1(self):
"""
... | 9,480 | 27.905488 | 118 | py |
graph-ismorphism | graph-ismorphism-master/program/main_logic.py | #! /usr/bin/python2.7
"""
Main logic
"""
from sat import Sat
from gi import Gi
from handlers.filehandler import FileHandler
from handlers.plothandler import PlotHandler
from handlers.processhandler import ProcessHandler
class Main(object):
def generate_systems(self, **kwargs):
"""
Generate insta... | 7,368 | 30.762931 | 112 | py |
graph-ismorphism | graph-ismorphism-master/program/__init__.py | 0 | 0 | 0 | py | |
graph-ismorphism | graph-ismorphism-master/program/sat.py | #! /usr/bin/python2.7
"""
Logic for producing uniquely satisfiable instances using Cryptominisat package
"""
import random
from pycryptosat import Solver
from handlers.filehandler import FileHandler
from handlers.processhandler import ProcessHandler
import timeit
import numpy as np
import networkx as nx
import matplo... | 23,485 | 31.847552 | 115 | py |
graph-ismorphism | graph-ismorphism-master/program/tests/papercode.py | """Writing logic from Prof. Dawars handout
"""
# Set of variables (including negations)
X = []
for i in range(-4, 5):
X.append(i)
# Set of clauses
phi = []
c1 = [1, 2, 3]
c2 = [-3, 4, 5]
c3 = [-2, 1, 3]
phi = [c1, c2]
# Satisfiable assignment
# -4, -3, -2, -1, 0, 1, 2, 3, 4
T = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# S... | 584 | 17.870968 | 42 | py |
graph-ismorphism | graph-ismorphism-master/program/tests/tester.py | from program.handlers.filehandler import FileHandler
from program.sat import Sat
fh = FileHandler()
sat = Sat()
system = fh.read_from_file("./../../assets/systems/2600_6900")
print sat.is_system_uniquely_satisfiable(system, 2600) | 231 | 28 | 62 | py |
graph-ismorphism | graph-ismorphism-master/program/handlers/plothandler.py | #! /usr/bin/python2.7
"""
Logic that handles the plotting of data into graphs
"""
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import operator
class PlotHandler(object):
de... | 8,463 | 27.402685 | 97 | py |
graph-ismorphism | graph-ismorphism-master/program/handlers/processhandler.py | #! /usr/bin/python2.7
"""
Logic that handles running system processes
"""
import os
import subprocess
import timeit
class ProcessHandler(object):
def run_command(self, command):
"""
Run a command and return a list
Good for single lined commands
:param command:
:return:
... | 2,079 | 25.329114 | 92 | py |
graph-ismorphism | graph-ismorphism-master/program/handlers/filehandler.py | #! /usr/bin/python2.7
"""
Logic that deals with file I/O
"""
import os
import os.path
import operator
import json
import datetime
from processhandler import ProcessHandler
class FileHandler(object):
def append_to_file(self, path, line):
"""
Add a string to the end of a file
:param path: ... | 5,502 | 26.653266 | 99 | py |
graph-ismorphism | graph-ismorphism-master/program/handlers/__init__.py | 0 | 0 | 0 | py | |
graph-ismorphism | graph-ismorphism-master/program/handlers/exceptionhandler.py | #! /usr/bin/python2.7
"""
Exception handlers
"""
class TimeoutError(Exception):
pass
def signal_handler(signum, frame):
raise TimeoutError() | 151 | 12.818182 | 34 | py |
CTDGMR | CTDGMR-master/reduction.py | import os
import pickle
import pyreadr
import argparse
import numpy as np
from CTDGMR.minCTD import GMR_CTD
from CTDGMR.optGMR import GMR_opt_BFGS
# stop the warning message in initialization
from warnings import simplefilter
from sklearn.exceptions import ConvergenceWarning
simplefilter("ignore", category=ConvergenceW... | 2,700 | 31.154762 | 100 | py |
CTDGMR | CTDGMR-master/CTDGMR/greedy.py | import ot
import time
import numpy as np
from scipy import linalg
from .distance import GMM_L2, GMM_CTD
def moment_preserving_merge(w1, mu1, cov1, w2, mu2, cov2):
w11, w21 = w1 / (w1 + w2), w2 / (w1 + w2)
mu = w11 * mu1 + w21 * mu2
cov = w11 * cov1 + w21 * cov2 + w11 * w21 * (mu1 - mu2).dot((mu1 - mu2).T)... | 4,889 | 37.503937 | 79 | py |
CTDGMR | CTDGMR-master/CTDGMR/optGMR.py | import ot
import time
import warnings
import numpy as np
from scipy import linalg
from scipy import optimize
from scipy.special import logsumexp, softmax
from scipy.stats import multivariate_normal
from numpy.linalg import det
from cvxopt import matrix
from cvxopt import solvers
from sklearn.cluster import KMeans
from ... | 29,228 | 38.713315 | 106 | py |
CTDGMR | CTDGMR-master/CTDGMR/utils.py | import ot
import numpy as np
from scipy import linalg
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from sklearn.utils import check_random_state
from scipy.stats import norm
def log_normal(diffs, covs, prec=False):
"""
log normal density of a matrix X
evaluated for multiple multiva... | 3,028 | 28.696078 | 77 | py |
CTDGMR | CTDGMR-master/CTDGMR/__init__.py | 0 | 0 | 0 | py | |
CTDGMR | CTDGMR-master/CTDGMR/barycenter.py | import numpy as np
from scipy import linalg
from scipy import optimize
# from scipy.optimize import minimize, fsolve, root, newton_krylov
from .distance import Gaussian_distance
from .utils import log_normal
from .optGMR import GMR_opt_BFGS
def barycenter(means, covs, lambdas=None, tol=1e-7, mean_init=None, cov_init=... | 11,073 | 43.296 | 105 | py |
CTDGMR | CTDGMR-master/CTDGMR/minCTD.py | import ot
import time
import warnings
import numpy as np
from scipy import linalg
from scipy import optimize
from scipy.special import logsumexp
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from .distance import GMM_L2, GMM_CTD, Gaussian_distance
from .greedy import *
from .utils impor... | 10,180 | 35.102837 | 100 | py |
CTDGMR | CTDGMR-master/CTDGMR/distance.py | import ot
import numpy as np
from scipy import linalg
from .utils import log_normal
from scipy.stats import multivariate_normal
"""
Distance functions
Part I: distance between Gaussians
Part II: distance between Gaussian mixtures
"""
def Gaussian_distance(mu1, mu2, Sigma1, Sigma2, which='W2'):
"""
Compute dis... | 11,638 | 31.878531 | 82 | py |
alibi-detect | alibi-detect-master/setup.py | from setuptools import find_packages, setup
def readme():
with open("README.md", encoding="utf-8") as f:
return f.read()
# read version file
exec(open("alibi_detect/version.py").read())
extras_require = {
"prophet": [
"prophet>=1.1.0, <2.0.0",
],
"torch": [
"torch>=1.7.0, <1... | 2,931 | 33.494118 | 118 | py |
alibi-detect | alibi-detect-master/testing/test_notebooks.py | """
This script is an example of using `jupytext` to execute notebooks for testing instead of relying on `nbmake`
plugin. This approach may be more flexible if our requirements change in the future.
"""
import glob
from pathlib import Path
import shutil
import pytest
from jupytext.cli import jupytext
try:
from fb... | 2,694 | 38.632353 | 109 | py |
alibi-detect | alibi-detect-master/alibi_detect/base.py | from abc import ABC, abstractmethod
import os
import copy
import json
import numpy as np
from typing import Dict, Any, Optional, Union
from typing_extensions import Protocol, runtime_checkable
from alibi_detect.version import __version__
DEFAULT_META: Dict = {
"name": None,
"online": None, # true or false
... | 8,321 | 29.708487 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/exceptions.py | """This module defines the Alibi Detect exception hierarchy and common exceptions used across the library."""
from typing_extensions import Literal
from typing import Callable
from abc import ABC
from functools import wraps
class AlibiDetectException(Exception, ABC):
def __init__(self, message: str) -> None:
... | 2,130 | 32.296875 | 110 | py |
alibi-detect | alibi-detect-master/alibi_detect/version.py | # Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = "0.11.5dev"
| 217 | 30.142857 | 60 | py |
alibi-detect | alibi-detect-master/alibi_detect/datasets.py | import io
import logging
from io import BytesIO
from typing import List, Tuple, Type, Union
from xml.etree import ElementTree
import dill
import numpy as np
import pandas as pd
import requests
from alibi_detect.utils.data import Bunch
from alibi_detect.utils.url import _join_url
from requests import RequestException
f... | 18,577 | 35.427451 | 117 | py |
alibi-detect | alibi-detect-master/alibi_detect/__init__.py | from . import ad, cd, models, od, utils, saving
from .version import __version__ # noqa F401
__all__ = ["ad", "cd", "models", "od", "utils", "saving"]
| 153 | 29.8 | 57 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/base.py | from alibi_detect.utils.missing_optional_dependency import import_optional
from typing import Union
from typing_extensions import Literal, Protocol, runtime_checkable
# Use Protocols instead of base classes for the backend associated objects. This is a bit more flexible and allows us to
# avoid the torch/tensorflow ... | 2,818 | 36.092105 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/vaegmm.py | import logging
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from typing import Callable, Dict, Tuple
from alibi_detect.models.tensorflow.autoencoder import VAEGMM, eucl_cosim_features
from alibi_detect.models.tensorflow.gmm import gmm_energy, gmm_params
from alibi_detect.models.tensor... | 9,744 | 37.98 | 107 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/_svm.py | from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
import numpy as np
from alibi_detect.base import (BaseDetector, FitMixin, ThresholdMixin,
outlier_prediction_dict)
from alibi_detect.exceptions import _catch_error as catch_error
from alibi_detect.od.pytorch import SgdS... | 10,687 | 41.923695 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/sr.py | import enum
import logging
import numpy as np
from typing import Dict
from alibi_detect.base import BaseDetector, ThresholdMixin, outlier_prediction_dict
from alibi_detect.utils._types import Literal
logger = logging.getLogger(__name__)
# numerical stability for division
EPSILON = 1e-8
class Padding(str, enum.Enum)... | 15,789 | 37.512195 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/_lof.py | from typing import Callable, Union, Optional, Dict, Any, List, Tuple
from typing import TYPE_CHECKING
from typing_extensions import Literal
import numpy as np
from alibi_detect.base import outlier_prediction_dict
from alibi_detect.exceptions import _catch_error as catch_error
from alibi_detect.od.base import Transfor... | 9,133 | 40.899083 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/seq2seq.py | import logging
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, InputLayer
from typing import Dict, Tuple, Union
from alibi_detect.models.tensorflow.autoencoder import Seq2Seq, EncoderLSTM, DecoderLSTM
from alibi_detect.models.tensorflow.trainer import trainer
from alibi_detect.base... | 13,595 | 40.075529 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/_mahalanobis.py | from typing import Union, Optional, Dict, Any
from typing import TYPE_CHECKING
from alibi_detect.exceptions import _catch_error as catch_error
from typing_extensions import Literal
import numpy as np
from alibi_detect.base import BaseDetector, FitMixin, ThresholdMixin, outlier_prediction_dict
from alibi_detect.od.pyt... | 6,935 | 37.966292 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/isolationforest.py | import logging
import numpy as np
from sklearn.ensemble import IsolationForest
from typing import Dict, Union
from alibi_detect.base import BaseDetector, FitMixin, ThresholdMixin, outlier_prediction_dict
logger = logging.getLogger(__name__)
class IForest(BaseDetector, FitMixin, ThresholdMixin):
def __init__(sel... | 5,012 | 32.871622 | 109 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/vae.py | import logging
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from typing import Dict, Tuple
from alibi_detect.models.tensorflow.autoencoder import VAE
from alibi_detect.models.tensorflow.trainer import trainer
from alibi_detect.models.tensorflow.losses import elbo
from alibi_detect.bas... | 11,444 | 37.15 | 112 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/_pca.py | from typing import Union, Optional, Callable, Dict, Any
from typing import TYPE_CHECKING
from typing_extensions import Literal
import numpy as np
from alibi_detect.base import outlier_prediction_dict
from alibi_detect.base import BaseDetector, ThresholdMixin, FitMixin
from alibi_detect.od.pytorch import KernelPCATorc... | 8,089 | 37.160377 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/_knn.py | from typing import Callable, Union, Optional, Dict, Any, List, Tuple
from typing import TYPE_CHECKING
from typing_extensions import Literal
import numpy as np
from alibi_detect.base import outlier_prediction_dict
from alibi_detect.exceptions import _catch_error as catch_error
from alibi_detect.od.base import Transfor... | 9,117 | 40.634703 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/llr.py | from functools import partial
import logging
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow_probability.python.distributions.distribution import Distribution
from typing import Callable, Dict, Tuple, Union
from alibi_detect.... | 14,091 | 36.280423 | 109 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/prophet.py | from prophet import Prophet
import logging
import pandas as pd
from typing import Dict, List, Union
from alibi_detect.base import BaseDetector, FitMixin, outlier_prediction_dict
logger = logging.getLogger(__name__)
class OutlierProphet(BaseDetector, FitMixin):
def __init__(self,
threshold: floa... | 8,498 | 41.283582 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/aegmm.py | import logging
import numpy as np
import tensorflow as tf
from typing import Callable, Dict, Tuple
from alibi_detect.models.tensorflow.autoencoder import AEGMM, eucl_cosim_features
from alibi_detect.models.tensorflow.gmm import gmm_energy, gmm_params
from alibi_detect.models.tensorflow.losses import loss_aegmm
from ali... | 7,829 | 35.933962 | 107 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/ae.py | import logging
import numpy as np
import tensorflow as tf
from typing import Dict, Tuple
from alibi_detect.models.tensorflow.autoencoder import AE
from alibi_detect.models.tensorflow.trainer import trainer
from alibi_detect.base import BaseDetector, FitMixin, ThresholdMixin, outlier_prediction_dict
from alibi_detect.ut... | 9,396 | 35.003831 | 109 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/_gmm.py | from typing import Union, Optional, Dict, Any, TYPE_CHECKING
import numpy as np
from alibi_detect.utils._types import Literal
from alibi_detect.base import outlier_prediction_dict
from alibi_detect.base import BaseDetector, ThresholdMixin, FitMixin
from alibi_detect.od.pytorch import GMMTorch
from alibi_detect.od.skl... | 9,837 | 41.042735 | 170 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
from .isolationforest import IForest
from .mahalanobis import Mahalanobis
from .sr import SpectralResidual
OutlierAEGMM = import_optional('alibi_detect.od.aegmm', names=['OutlierAEGMM'])
OutlierAE = import_optional('alibi_detect.od.ae', names... | 929 | 32.214286 | 85 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/mahalanobis.py | import logging
import numpy as np
from scipy.linalg import eigh
from typing import Dict, Optional
from alibi_detect.utils.discretizer import Discretizer
from alibi_detect.utils.distance import abdm, mvdm, multidim_scaling
from alibi_detect.utils.mapping import ohe2ord, ord2num
from alibi_detect.base import BaseDetector... | 14,294 | 39.495751 | 116 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_mahalanobis.py | from itertools import product
import numpy as np
import pytest
from sklearn.datasets import load_iris
from alibi_detect.od import Mahalanobis
from alibi_detect.version import __version__
threshold = [None, 5.]
n_components = [2, 3]
std_clip = [2, 3]
start_clip = [10, 1000]
max_n = [None, 50]
threshold_perc = [75., 95.... | 1,958 | 36.673077 | 97 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_aegmm.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, InputLayer
from alibi_detect.od import OutlierAEGMM
from alibi_detect.version import __version__
threshold = [None, 5.]
n_gmm = [1, 2]
w_energy = [.1, .5]
threshold_perc = [90.]
return_inst... | 3,007 | 31.695652 | 96 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_llr.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input, LSTM
from alibi_detect.od import LLR
from alibi_detect.version import __version__
input_dim = 5
hidden_dim = 20
shape = (1000, 6)
X_train = np.zeros(shape, dtype=np.int32)
X_train[:... | 3,587 | 34.524752 | 101 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_ae.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 alibi_detect.od import OutlierAE
from alibi_detect.version import __version__
threshold = [None, 5.]
threshold_perc = [90.]
return_ins... | 3,537 | 33.349515 | 114 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_vae.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 alibi_detect.od import OutlierVAE
from alibi_detect.models.tensorflow.losses import elbo
from alibi_detect.version import __version__
... | 3,862 | 33.801802 | 94 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_iforest.py | from itertools import product
import pytest
from sklearn.datasets import load_iris
from alibi_detect.od import IForest
from alibi_detect.version import __version__
threshold = [None, 0.]
threshold_perc = [75., 95.]
return_instance_score = [True, False]
tests = list(product(threshold, threshold_perc, return_instance_s... | 1,583 | 39.615385 | 98 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_seq2seq.py | from itertools import product
import numpy as np
import pytest
from alibi_detect.od import OutlierSeq2Seq
from alibi_detect.utils.perturbation import inject_outlier_ts
from alibi_detect.version import __version__
n_features = [1, 2]
seq_len = [20, 50]
threshold = [None, 5.]
threshold_perc = [90.]
return_instance_score... | 3,525 | 38.617978 | 117 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_ensemble.py | import pytest
import torch
from alibi_detect.od.pytorch import ensemble
from alibi_detect.exceptions import NotFittedError
def test_pval_normalizer():
"""Test the PValNormalizer
- Test the PValNormalizer correctly normalizes data passed to it
- Test the PValNormalizer throws the correct errors if not fi... | 7,122 | 34.08867 | 113 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_prophet.py | import datetime
from itertools import product
import numpy as np
import pandas as pd
import pytest
from alibi_detect.od import OutlierProphet
from alibi_detect.version import __version__
growth = ['linear', 'logistic']
return_instance_score = [True, False]
return_forecast = [True, False]
d_fit = {
'ds': pd.date_r... | 2,197 | 35.032787 | 104 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_sr.py | import pytest
import numpy as np
from alibi_detect.od import SpectralResidual
from alibi_detect.version import __version__
@pytest.fixture(scope='module')
def signal():
np.random.seed(0)
# create normal time series and one with perturbations
t = np.linspace(0, 0.5, 1000)
X = np.sin(40 * 2 * np.pi * t... | 4,371 | 40.245283 | 116 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test_vaegmm.py | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.layers import Dense, InputLayer
from alibi_detect.od import OutlierVAEGMM
from alibi_detect.version import __version__
threshold = [None, 5.]
n_gmm = [1, 2]
w_energy = [.1, .5]
w_recon = [0., 1e-7]
samples = [1... | 3,175 | 32.083333 | 106 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__gmm/test__gmm_sklearn_backend.py | import pytest
import numpy as np
from alibi_detect.od.sklearn.gmm import GMMSklearn
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
def test_gmm_sklearn_scoring():
"""Test GMM detector sklearn scoring method.
Tests the scoring method of the GMM sklearn backend detector.
"""... | 3,185 | 33.258065 | 98 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__gmm/test__gmm_pytorch_backend.py | import pytest
import numpy as np
import torch
from alibi_detect.od.pytorch.gmm import GMMTorch
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
def test_gmm_pytorch_scoring():
"""Test GMM detector pytorch scoring method.
Tests the scoring method of the GMMTorch pytorch backend d... | 3,906 | 33.575221 | 96 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__gmm/test__gmm.py | import pytest
import numpy as np
import torch
from alibi_detect.od._gmm import GMM
from alibi_detect.exceptions import NotFittedError
from sklearn.datasets import make_moons
@pytest.mark.parametrize('backend', ['pytorch', 'sklearn'])
def test_unfitted_gmm_score(backend):
"""Test GMM detector raises exceptions w... | 4,890 | 34.963235 | 102 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__lof/test__lof_backend.py | import pytest
import torch
from alibi_detect.od.pytorch.lof import LOFTorch
from alibi_detect.utils.pytorch.kernels import GaussianRBF
from alibi_detect.od.pytorch.ensemble import Ensembler, PValNormalizer, AverageAggregator
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
@pytest.fixtur... | 7,975 | 35.090498 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__lof/test__lof.py | import pytest
import numpy as np
import torch
from alibi_detect.od._lof import LOF
from alibi_detect.od.pytorch.ensemble import AverageAggregator, TopKAggregator, MaxAggregator, \
MinAggregator, ShiftAndScaleNormalizer, PValNormalizer
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
f... | 10,349 | 37.333333 | 112 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__knn/test__knn.py | import pytest
import numpy as np
import torch
from alibi_detect.od._knn import KNN
from alibi_detect.od.pytorch.ensemble import AverageAggregator, TopKAggregator, MaxAggregator, \
MinAggregator, ShiftAndScaleNormalizer, PValNormalizer
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
f... | 10,379 | 37.161765 | 112 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__knn/test__knn_backend.py | import pytest
import torch
from alibi_detect.od.pytorch.knn import KNNTorch
from alibi_detect.utils.pytorch.kernels import GaussianRBF
from alibi_detect.od.pytorch.ensemble import Ensembler, PValNormalizer, AverageAggregator
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
@pytest.fixtur... | 7,995 | 35.180995 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__pca/test__pca.py | import pytest
import numpy as np
import torch
from alibi_detect.utils.pytorch.kernels import GaussianRBF
from alibi_detect.od._pca import PCA
from alibi_detect.exceptions import NotFittedError
from sklearn.datasets import make_moons
def fit_PCA_detector(detector):
pca_detector = detector()
x_ref = np.random.... | 6,603 | 35.893855 | 106 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__pca/test__pca_backend.py | import pytest
import torch
import numpy as np
from alibi_detect.utils.pytorch.kernels import GaussianRBF
from alibi_detect.od.pytorch.pca import LinearPCATorch, KernelPCATorch
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
@pytest.mark.parametrize('backend_detector', [
lambda: Line... | 4,470 | 34.768 | 101 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__svm/test__svm_pytorch_backend.py | import pytest
import numpy as np
import torch
from alibi_detect.utils.pytorch.kernels import GaussianRBF
from alibi_detect.od.pytorch.svm import BgdSVMTorch, SgdSVMTorch
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
@pytest.mark.parametrize('backend_cls', [BgdSVMTorch, SgdSVMTorch])
d... | 5,250 | 36.241135 | 111 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__svm/test__svm.py | import pytest
import numpy as np
import torch
from alibi_detect.od._svm import SVM
from alibi_detect.exceptions import NotFittedError
from alibi_detect.utils.pytorch import GaussianRBF
from sklearn.datasets import make_moons
@pytest.mark.parametrize('optimization', ['sgd', 'bgd'])
def test_unfitted_svm_score(optimiz... | 7,983 | 32.974468 | 119 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__mahalanobis/test__mahalanobis.py | import pytest
import numpy as np
import torch
from alibi_detect.od._mahalanobis import Mahalanobis
from alibi_detect.exceptions import NotFittedError
from sklearn.datasets import make_moons
def make_mahalanobis_detector():
mahalanobis_detector = Mahalanobis()
x_ref = np.random.randn(100, 2)
mahalanobis_d... | 4,177 | 35.973451 | 102 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/tests/test__mahalanobis/test__mahalanobis_backend.py | import pytest
import torch
import numpy as np
from alibi_detect.od.pytorch.mahalanobis import MahalanobisTorch
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
def test_mahalanobis_linear_scoring():
"""Test Mahalanobis detector linear scoring method.
Test that the Mahalanobis de... | 3,764 | 36.277228 | 104 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/sklearn/base.py | from typing import List, Union, Optional, Dict
from dataclasses import dataclass, asdict
from abc import ABC, abstractmethod
from typing_extensions import Self
import numpy as np
from alibi_detect.exceptions import NotFittedError, ThresholdNotInferredError
@dataclass
class SklearnOutlierDetectorOutput:
"""Outpu... | 6,383 | 28.018182 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/sklearn/gmm.py | import numpy as np
from typing import Dict
from sklearn.mixture import GaussianMixture
from alibi_detect.od.sklearn.base import SklearnOutlierDetector
class GMMSklearn(SklearnOutlierDetector):
def __init__(
self,
n_components: int,
):
"""sklearn backend for the Gaussian Mixture Model ... | 3,928 | 30.432 | 117 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/sklearn/__init__.py | from alibi_detect.od.sklearn.gmm import GMMSklearn # noqa: F401
| 65 | 32 | 64 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/svm.py | import warnings
from typing import Callable, Dict, Optional, Tuple, Union
import numpy as np
import torch
from sklearn.linear_model import SGDOneClassSVM
from sklearn.utils.extmath import safe_sparse_dot
from tqdm import tqdm
from typing_extensions import Literal, Self
from alibi_detect.od.pytorch.base import TorchOu... | 15,972 | 34.416851 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/base.py | from typing import List, Union, Optional, Dict
from typing_extensions import Literal
from dataclasses import dataclass, fields
from abc import ABC, abstractmethod
import numpy as np
import torch
from alibi_detect.od.pytorch.ensemble import FitMixinTorch
from alibi_detect.utils.pytorch.misc import get_device
from alib... | 8,752 | 32.408397 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/knn.py | from typing import Optional, Union, List, Tuple
from typing_extensions import Literal
import numpy as np
import torch
from alibi_detect.od.pytorch.ensemble import Ensembler
from alibi_detect.od.pytorch.base import TorchOutlierDetector
class KNNTorch(TorchOutlierDetector):
def __init__(
self,
... | 3,635 | 34.647059 | 107 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/gmm.py | from typing import Optional, Union, Dict, Type
from typing_extensions import Literal
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from alibi_detect.utils.pytorch.data import TorchDataset
from alibi_detect.od.pytorch.base import TorchOutlierDetector
from alibi_detect.models.pytorch.gmm imp... | 6,651 | 31.291262 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/pca.py | from typing import Optional, Union, Callable
from typing_extensions import Literal
import torch
from alibi_detect.od.pytorch.base import TorchOutlierDetector
class PCATorch(TorchOutlierDetector):
ensemble = False
def __init__(
self,
n_components: int,
device: Optional[Un... | 8,313 | 30.255639 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
KNNTorch = import_optional('alibi_detect.od.pytorch.knn', ['KNNTorch'])
LOFTorch = import_optional('alibi_detect.od.pytorch.lof', ['LOFTorch'])
MahalanobisTorch = import_optional('alibi_detect.od.pytorch.mahalanobis', ['MahalanobisTorch'])
Kern... | 691 | 68.2 | 117 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/ensemble.py | from abc import ABC, abstractmethod
from typing import Optional
from typing_extensions import Self
import torch
import numpy as np
from torch.nn import Module
from alibi_detect.exceptions import NotFittedError
class BaseTransformTorch(Module):
def __init__(self):
"""Base Transform class.
provid... | 9,337 | 28.644444 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/mahalanobis.py | from typing import Optional, Union
from typing_extensions import Literal
import torch
from alibi_detect.od.pytorch.base import TorchOutlierDetector
class MahalanobisTorch(TorchOutlierDetector):
ensemble = False
def __init__(
self,
min_eigenvalue: float = 1e-6,
device: Opt... | 3,162 | 27.495495 | 115 | py |
alibi-detect | alibi-detect-master/alibi_detect/od/pytorch/lof.py | from typing import Optional, Union, List, Tuple
from typing_extensions import Literal
import numpy as np
import torch
from alibi_detect.od.pytorch.ensemble import Ensembler
from alibi_detect.od.pytorch.base import TorchOutlierDetector
class LOFTorch(TorchOutlierDetector):
def __init__(
self,
... | 6,709 | 39.666667 | 107 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/__init__.py | 0 | 0 | 0 | py | |
alibi-detect | alibi-detect-master/alibi_detect/models/pytorch/embedding.py | from functools import partial
import torch
import torch.nn as nn
from transformers import AutoModel, AutoConfig
from typing import Dict, List
def hidden_state_embedding(hidden_states: torch.Tensor, layers: List[int],
use_cls: bool, reduce_mean: bool = True) -> torch.Tensor:
"""
Extr... | 2,138 | 38.611111 | 108 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/pytorch/gmm.py | from torch import nn
import torch
class GMMModel(nn.Module):
def __init__(self, n_components: int, dim: int) -> None:
"""Gaussian Mixture Model (GMM).
Parameters
----------
n_components
The number of mixture components.
dim
The dimensionality of the... | 1,402 | 31.627907 | 106 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/pytorch/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
TransformerEmbedding = import_optional(
'alibi_detect.models.pytorch.embedding',
names=['TransformerEmbedding'])
trainer = import_optional(
'alibi_detect.models.pytorch.trainer',
names=['trainer'])
__all__ = [
"Transforme... | 349 | 20.875 | 74 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/pytorch/trainer.py | import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from typing import Callable, Union
def trainer(
model: Union[nn.Module, nn.Sequential],
loss_fn: Callable,
dataloader: DataLoader,
device: torch.device,
optimizer: Callable = torch.... | 2,027 | 30.6875 | 106 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/pytorch/tests/test_trainer_pt.py | 0 | 0 | 0 | py | |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/embedding.py | from functools import partial
import tensorflow as tf
from transformers import TFAutoModel, AutoConfig
from typing import Dict, List
def hidden_state_embedding(hidden_states: tf.Tensor, layers: List[int],
use_cls: bool, reduce_mean: bool = True) -> tf.Tensor:
"""
Extract embeddings ... | 3,718 | 40.322222 | 108 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/pixelcnn.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import numpy as np
import warnings
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.bijectors import bijector
from tensorflow_probability.python.distributions import categor... | 48,470 | 45.383732 | 120 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/losses.py | from typing import Optional
import tensorflow as tf
from tensorflow.keras.layers import Flatten
from tensorflow.keras.losses import kld, categorical_crossentropy
import tensorflow_probability as tfp
from alibi_detect.models.tensorflow.gmm import gmm_params, gmm_energy
def elbo(y_true: tf.Tensor,
y_pred: tf.... | 8,256 | 29.925094 | 111 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/resnet.py | # implementation adopted from https://github.com/tensorflow/models
# TODO: proper train-val-test split
import argparse
import numpy as np
import os
from pathlib import Path
import tensorflow as tf
from tensorflow.keras.callbacks import Callback, ModelCheckpoint
from tensorflow.keras.initializers import RandomNormal
fro... | 15,500 | 28.469582 | 92 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/gmm.py | import numpy as np
import tensorflow as tf
from typing import Tuple
def gmm_params(z: tf.Tensor,
gamma: tf.Tensor) \
-> Tuple[tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor]:
"""
Compute parameters of Gaussian Mixture Model.
Parameters
----------
z
Observatio... | 3,268 | 29.839623 | 87 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/autoencoder.py | import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Bidirectional, Concatenate, Dense, Flatten, Layer, LSTM
from typing import Callable, List, Tuple
from alibi_detect.utils.tensorflow.distance import relative_euclidean_distance
class Sampling(Layer):
""" Reparametrization trick. Uses (z... | 14,709 | 31.472406 | 110 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/__init__.py | from alibi_detect.utils.missing_optional_dependency import import_optional
AE, AEGMM, VAE, VAEGMM, Seq2Seq, eucl_cosim_features = import_optional(
'alibi_detect.models.tensorflow.autoencoder',
names=['AE', 'AEGMM', 'VAE', 'VAEGMM', 'Seq2Seq', 'eucl_cosim_features'])
TransformerEmbedding = import_optional(
... | 1,242 | 24.895833 | 83 | py |
alibi-detect | alibi-detect-master/alibi_detect/models/tensorflow/trainer.py | from functools import partial
import numpy as np
import tensorflow as tf
from typing import Callable, Tuple
def trainer(
model: tf.keras.Model,
loss_fn: tf.keras.losses,
x_train: np.ndarray,
y_train: np.ndarray = None,
dataset: tf.keras.utils.Sequence = None,
optimizer:... | 4,358 | 37.919643 | 103 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.