python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
import matplotlib.pyplot as plt import numpy as np import scipy.sparse as sparse from metal.utils import convert_labels ############################################################ # Label Matrix Plotting ############################################################ def view_label_matrix(L, colorbar=True): """Di...
metal-master
metal/contrib/visualization/analysis.py
metal-master
metal/contrib/visualization/__init__.py
class Featurizer(object): def fit(self, input): """ Args: input: An iterable of raw data of the appropriate type to be featurized, where input[i] corresponds to item i. """ raise NotImplementedError def transform(self, input): """ Args...
metal-master
metal/contrib/featurizers/featurizer.py
metal-master
metal/contrib/featurizers/__init__.py
import itertools from collections import Counter import torch from torch.nn.utils.rnn import pad_sequence from torchtext.vocab import Vocab from metal.contrib.featurizers.featurizer import Featurizer class EmbeddingFeaturizer(Featurizer): """Converts lists of tokens into a padded Tensor of embedding indices."""...
metal-master
metal/contrib/featurizers/embedding_featurizer.py
import nltk from sklearn.feature_extraction.text import CountVectorizer from metal.contrib.featurizers.featurizer import Featurizer class RelationNgramFeaturizer(Featurizer): """A featurizer for relations that preprocesses and extracts ngrams This featurizer operates on RelationMention objects Args: ...
metal-master
metal/contrib/featurizers/ngram_featurizer.py
import os from collections import Counter import numpy as np import torch from torch.utils.data import Dataset from metal.contrib.info_extraction.utils import mark_entities class SnorkelDataset(Dataset): """ Self-contained wrapper class for Snorkel 0.7 database instance. Suitable for datasets that fit e...
metal-master
metal/contrib/backends/wrapper.py
metal-master
metal/contrib/backends/__init__.py
metal-master
metal/contrib/info_extraction/__init__.py
def mark_entities(tokens, positions, markers=[], style="insert"): """Adds special markers around tokens at specific positions (e.g., entities) Args: tokens: A list of tokens (the sentence) positions: 1) A list of inclusive ranges (tuples) corresponding to the token range...
metal-master
metal/contrib/info_extraction/utils.py
import numpy as np class EntityMention(object): """A mention of an entity (span of text) in a document Args: doc_id: a unique identifier for the document text: a single string of text corresponding to the document char_start: the integer offset of the first character in the entity ...
metal-master
metal/contrib/info_extraction/mentions.py
from metal.contrib.modules.sparse_linear_module import SparseLinearModule from metal.end_model import EndModel from metal.utils import recursive_merge_dicts class SparseLogisticRegression(EndModel): """A _sparse_ logistic regression classifier for a single-task problem Args: input_dim: The maximum le...
metal-master
metal/contrib/baselines/sparse_logreg.py
from .lstm_module import EmbeddingsEncoder, Encoder, LSTMModule from .resnet_cifar10 import ResNetModule from .sparse_linear_module import SparseLinearModule __all__ = [ "LSTMModule", "Encoder", "EmbeddingsEncoder", "ResNetModule", "SparseLinearModule", ]
metal-master
metal/contrib/modules/__init__.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.rnn as rnn_utils from metal.utils import set_seed class Encoder(nn.Module): """The Encoder implements the encode() method, which maps a batch of data to encoded output of dimension [batch_size, max_seq_len, encoded_size]...
metal-master
metal/contrib/modules/lstm_module.py
import math import torch import torch.nn as nn class SparseLinearModule(nn.Module): def __init__(self, embed_size, vocab_size, padding_idx=0): super().__init__() self.vocab_size = vocab_size self.padding_idx = padding_idx self.W = nn.Embedding( vocab_size, embed_size, ...
metal-master
metal/contrib/modules/sparse_linear_module.py
"""ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 """ import torch import torch.nn as nn import torch.nn.functional as F class BasicBlock(nn.Module): expansion...
metal-master
metal/contrib/modules/resnet_cifar10.py
from collections import Counter from functools import partial from itertools import chain, product import numpy as np import torch import torch.nn as nn from scipy.sparse import issparse from torch.utils.data import DataLoader from metal.classifier import Classifier from metal.label_model.graph_utils import get_cliqu...
metal-master
metal/label_model/label_model.py
import numpy as np from metal.label_model.label_model import LabelModel class RandomVoter(LabelModel): """ A class that votes randomly among the available labels """ def train_model(self, *args, **kwargs): pass def predict_proba(self, L): """ Args: L: An [n, ...
metal-master
metal/label_model/baselines.py
from itertools import product import numpy as np import torch from torch import nn, optim class ClassBalanceModel(nn.Module): """A model for learning the class balance, P(Y=y), given a subset of LFs which are *conditionally independent*, i.e. \lambda_i \perp \lambda_j | Y, for i != j. Learns the mo...
metal-master
metal/label_model/class_balance.py
import networkx as nx def get_clique_tree(nodes, edges): """Given a set of int nodes i and edges (i,j), returns an nx.Graph object G which is a clique tree, where: - G.node[i]['members'] contains the set of original nodes in the ith maximal clique - G[i][j]['members'] contains the ...
metal-master
metal/label_model/graph_utils.py
lm_default_config = { # GENERAL "seed": None, "verbose": True, "show_plots": True, # Device (default GPU) "device": "cpu", # TRAIN "train_config": { # Dataloader "data_loader_config": {"batch_size": 1000, "num_workers": 1}, # Classifier # Class balance (if...
metal-master
metal/label_model/lm_defaults.py
from .baselines import MajorityClassVoter, MajorityLabelVoter, RandomVoter from .label_model import LabelModel __all__ = ["MajorityClassVoter", "MajorityLabelVoter", "RandomVoter", "LabelModel"]
metal-master
metal/label_model/__init__.py
import numpy as np def compute_mu(L_aug, Y, k, p): """Given label matrix L_aug and labels Y, compute the true mu params. Args: L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix Y: (np.array int) [n] The true labels in {1,...,k} k: (int) Cardinality p: (np.array...
metal-master
metal/label_model/utils.py
import numpy as np from scipy.sparse import issparse from metal.label_model import LabelModel from metal.label_model.lm_defaults import lm_default_config from metal.multitask import MTClassifier from metal.multitask.task_graph import TaskGraph from metal.utils import recursive_merge_dicts class MTLabelModel(MTClassi...
metal-master
metal/multitask/mt_label_model.py
import numpy as np from metal.classifier import Classifier from metal.metrics import metric_score from metal.multitask.utils import MultiXYDataset, MultiYDataset class MTClassifier(Classifier): """Simple abstract base class for a *multi-class* probabilistic classifier. The main contribution of children clas...
metal-master
metal/multitask/mt_classifier.py
import copy from collections import defaultdict import torch import torch.nn as nn import torch.nn.functional as F from metal.end_model import EndModel from metal.end_model.em_defaults import em_default_config from metal.end_model.identity_module import IdentityModule from metal.end_model.loss import SoftCrossEntropy...
metal-master
metal/multitask/mt_end_model.py
from .mt_classifier import MTClassifier from .mt_end_model import MTEndModel from .mt_label_model import MTLabelModel from .task_graph import TaskGraph, TaskHierarchy from .utils import MultiXYDataset, MultiYDataset __all__ = [ "MultiXYDataset", "MultiYDataset", "TaskGraph", "TaskHierarchy", "MTCla...
metal-master
metal/multitask/__init__.py
import itertools import networkx as nx import numpy as np class TaskGraph(object): """A directed graph defining dependencies between tasks In the MTLabelModel, the TaskGraph is used to define a feasible subset of all t-dimensional label vectors Y = [Y_1,...,Y_t]; for example, in a mutually exclusive...
metal-master
metal/multitask/task_graph.py
import numpy as np from scipy.sparse import issparse from torch.utils.data import Dataset class MultiYDataset(Dataset): """A dataset that group each item in X with its labels for t tasks from Y Args: X: an n-dim iterable of inputs Y: a t-length list of n-dim iterables corresponding to labels ...
metal-master
metal/multitask/utils.py
mt_em_default_config = { "task_head_layers": "top", # Optionally specify the layers that each head should attach to # For single-task settings, this is always 'top' # 'top': connect all heads to the final (top) layer # [list]: specify explicitly the layer for each head "pass_predictions": Fa...
metal-master
metal/multitask/mt_em_defaults.py
import os import torch class Checkpointer(object): def __init__(self, config, verbose=True): """Saves checkpoints as applicable based on a reported metric. Args: checkpoint_runway (int): don't save any checkpoints for the first this many iterations checkpo...
metal-master
metal/logging/checkpointer.py
from .checkpointer import Checkpointer from .logger import Logger, Timer from .tensorboard import TensorBoardWriter from .writer import LogWriter __all__ = ["Checkpointer", "Logger", "LogWriter", "TensorBoardWriter", "Timer"]
metal-master
metal/logging/__init__.py
import time from collections import defaultdict from metal.metrics import METRICS as standard_metric_names, metric_score class Logger(object): """Tracks when it is time to calculate train/valid metrics and logs them""" def __init__(self, config, writer={}, epoch_size=None, verbose=True): # Strip spl...
metal-master
metal/logging/logger.py
def split_full_metric(full_metric): """Splits a full metric name (split/name or task/split/label/name) into pieces""" pieces = full_metric.split("/") if len(pieces) == 2: # Single-task metric split, name = pieces return split, name elif len(pieces) == 4: # Mmtl metric task, pay...
metal-master
metal/logging/utils.py
import copy import json import os from collections import defaultdict from subprocess import check_output from time import strftime from metal.utils import recursive_transform class LogWriter(object): """Class for writing simple JSON logs at end of runs, with interface for storing per-iter data as well. ...
metal-master
metal/logging/writer.py
import json import warnings import numpy as np from tensorboardX import SummaryWriter from metal.logging.writer import LogWriter class TensorBoardWriter(LogWriter): """Class for logging to Tensorboard during runs, as well as writing simple JSON logs at end of runs. Stores logs in log_dir/{YYYY}_{MM}_{D...
metal-master
metal/logging/tensorboard.py
metal-master
tests/__init__.py
import os import pickle import unittest import GPUtil from metal.end_model import EndModel from metal.label_model import LabelModel from metal.utils import split_data # Making sure we're using GPU 0 os.environ["CUDA_VISIBLE_DEVICES"] = "0" class GPUTest(unittest.TestCase): @unittest.skipIf( "TRAVIS" in...
metal-master
tests/gpu/test_gpu.py
import unittest from collections import Counter import numpy as np import scipy.sparse as sparse import torch from metal.utils import pred_to_prob, rargmax, recursive_merge_dicts, split_data class UtilsTest(unittest.TestCase): def test_rargmax(self): x = np.array([2, 1, 2]) np.random.seed(1) ...
metal-master
tests/metal/test_utils.py
import unittest import numpy as np import torch from metal.metrics import ( accuracy_score, coverage_score, f1_score, fbeta_score, metric_score, precision_score, recall_score, roc_auc_score, ) class MetricsTest(unittest.TestCase): def test_accuracy_basic(self): gold = [1,...
metal-master
tests/metal/test_metrics.py
import unittest import numpy as np import scipy.sparse as sparse from metal.analysis import ( error_buckets, label_conflict, label_coverage, label_overlap, lf_conflicts, lf_coverages, lf_empirical_accuracies, lf_overlaps, ) class AnalysisTest(unittest.TestCase): @classmethod ...
metal-master
tests/metal/test_analysis.py
metal-master
tests/metal/__init__.py
metal-master
tests/metal/end_model/__init__.py
import os import unittest import numpy as np import torch import torch.nn as nn from metal.end_model import EndModel, LogisticRegression from metal.end_model.identity_module import IdentityModule from metal.metrics import METRICS class EndModelTest(unittest.TestCase): @classmethod def setUpClass(cls): ...
metal-master
tests/metal/end_model/test_end_model.py
import unittest import torch import torch.nn as nn from metal.end_model.loss import SoftCrossEntropyLoss from metal.utils import pred_to_prob class LossTest(unittest.TestCase): @classmethod def setUpClass(cls): torch.manual_seed(1) def test_sce_equals_ce(self): # All correct predictions...
metal-master
tests/metal/end_model/test_loss.py
import unittest from collections import defaultdict import numpy as np import torch import torch.nn as nn from metal.mmtl.data import MmtlDataLoader, MmtlDataset from metal.mmtl.metal_model import MetalModel from metal.mmtl.payload import Payload from metal.mmtl.task import ClassificationTask from metal.mmtl.trainer ...
metal-master
tests/metal/mmtl/test_mmtl.py
import json import unittest from shutil import rmtree import numpy as np import torch from metal.end_model import EndModel from metal.logging import LogWriter from metal.tuners.random_tuner import RandomSearchTuner class RandomSearchModelTunerTest(unittest.TestCase): @classmethod def setUpClass(cls): ...
metal-master
tests/metal/tuners/test_random_search_tuner.py
metal-master
tests/metal/tuners/__init__.py
import unittest from metal.tuners.hyperband_tuner import HyperbandTuner class HyperbandTunerModelTunerTest(unittest.TestCase): def test_hyperband_schedule_correctness(self): # Test the default schedule that is generated by the hyperband tuner # (which at the moment is budget=200, eta=3) h...
metal-master
tests/metal/tuners/test_hyperband_tuner.py
import numpy as np import torch from metal.end_model import SparseLogisticRegression def test_sparselogreg(self): """Confirm sparse logreg can overfit, works on padded data""" F = 1000 # total number of possible features N = 50 # number of data points S = [10, 100] # range of features per data poi...
metal-master
tests/metal/contrib/test_baselines.py
import json import unittest from shutil import rmtree import numpy as np import torch from metal.contrib.modules import EmbeddingsEncoder, LSTMModule from metal.end_model import EndModel from metal.logging import LogWriter from metal.tuners.random_tuner import RandomSearchTuner n = 1000 SEQ_LEN = 5 MAX_INT = 8 cla...
metal-master
tests/metal/contrib/test_lstm.py
import sys import unittest from itertools import product import numpy as np import torch from metal.label_model.class_balance import ClassBalanceModel sys.path.append("../synthetic") class ClassBalanceModelTest(unittest.TestCase): def _set_seed(self, seed): torch.manual_seed(seed) np.random.see...
metal-master
tests/metal/label_model/test_class_balance.py
import sys import unittest import numpy as np from metal.label_model.baselines import MajorityLabelVoter from metal.label_model.label_model import LabelModel from synthetic.generate import SingleTaskTreeDepsGenerator sys.path.append("../synthetic") # TODO: Put in tests for LabelModel baselines again! class LabelMo...
metal-master
tests/metal/label_model/test_label_model.py
metal-master
tests/metal/label_model/__init__.py
metal-master
tests/metal/multitask/__init__.py
import unittest from metal.multitask.task_graph import TaskGraph class TaskGraphTest(unittest.TestCase): def test_binary_tree(self): cardinalities = [2, 2, 2] edges = [(0, 1), (0, 2)] tg = TaskGraph(cardinalities, edges) self.assertTrue(tg.parents[0] == []) self.assertTrue...
metal-master
tests/metal/multitask/test_task_graph.py
import sys import unittest import numpy as np from metal.multitask import MTLabelModel from synthetic.generate import HierarchicalMultiTaskTreeDepsGenerator sys.path.append("../synthetic") class MTLabelModelTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.n_iters = 1 cls.n = 1...
metal-master
tests/metal/multitask/test_mt_label_model.py
import unittest import numpy as np import torch import torch.nn as nn from metal.end_model.identity_module import IdentityModule from metal.metrics import METRICS from metal.multitask import MTEndModel from metal.multitask.task_graph import TaskGraph, TaskHierarchy class MTEndModelTest(unittest.TestCase): @clas...
metal-master
tests/metal/multitask/test_mt_end_model.py
import json import os import unittest from shutil import rmtree import numpy as np import torch from metal.end_model import EndModel class LogWriterTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2)) ...
metal-master
tests/metal/logging/test_writer.py
import copy import os import unittest from shutil import rmtree import numpy as np import torch from metal.end_model import EndModel class CheckpointerTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2...
metal-master
tests/metal/logging/test_checkpointer.py
import unittest import numpy as np import torch class LoggerTest(unittest.TestCase): @classmethod def setUpClass(cls): # Set seed np.random.seed(1) n = 2000 X = np.random.random((n, 2)) * 2 - 1 Y = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1 X = torch.tensor(...
metal-master
tests/metal/logging/test_logger.py
metal-master
tests/synthetic/__init__.py
metal-master
tests/travis/__init__.py
import unittest import numpy as np class TravisTest(unittest.TestCase): def test_sanity(self): self.assertTrue(1 + 1 == 2) # Confirm import of third-party package also works self.assertTrue(int(np.array([1]) + np.array([1])) == 2) if __name__ == "__main__": unittest.main()
metal-master
tests/travis/test_travis.py
from collections import defaultdict import numpy as np import torch from numpy.random import choice, random from scipy.sparse import csr_matrix from metal.multitask.task_graph import TaskHierarchy from synthetic.words1k import vocab1k def singletask_synthetic(n, m, k, **kwargs): data = SingleTaskTreeDepsGenerat...
metal-master
synthetic/generate.py
metal-master
synthetic/__init__.py
vocab1k = [ "a", "ability", "able", "about", "above", "accept", "according", "account", "across", "act", "action", "activity", "actually", "add", "address", "administration", "admit", "adult", "affect", "after", "again", "against", ...
metal-master
synthetic/words1k.py
""" This tutorial script runs a simple ResNet to classify the CIFAR-10 dataset using MeTaL. The purpose of this particular tutorial is to demonstrate how a standard machine learning task can be run using MeTaL utilities. Running this script with settings in run_CIFAR_Tutorial.sh should give performance on the order of...
metal-master
tutorials/CIFAR_Tutorial.py
mongoose-master
mongoose_reformer/__init__.py
import random import math import numpy as np import torch import argparse import time import os from reformer_lib.reformer_pytorch import ReformerLM,ReformerLM_tune from reformer_lib.generative_tools import TrainingWrapper from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataP...
mongoose-master
mongoose_reformer/train_reformer.py
from functools import partial import torch from torch import nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from reformer_lib.reformer_pytorch import ReformerLM,ReformerLM_tune from reformer_lib.autopadder import Autopadder def top_p(logits, thres = 0.9): sorted_logits, sorted_indic...
mongoose-master
mongoose_reformer/reformer_lib/generative_tools.py
import math import torch from torch import nn import torch.nn.functional as F from reformer_lib.reformer_pytorch import Reformer, ReformerLM, LSHSelfAttention,ReformerLM_tune,Reformer_tune def pad_to_multiple(tensor, seqlen, multiple, dim=-1): m = seqlen / multiple if m.is_integer(): return tensor ...
mongoose-master
mongoose_reformer/reformer_lib/autopadder.py
import re from torch import nn from reformer_lib.reformer_pytorch import ReformerLM from reformer_lib.generative_tools import TrainingWrapper ENC_PREFIX = 'enc_' DEC_PREFIX = 'dec_' def group_dict_by_key(cond, d): return_val = [dict(),dict()] for key in d.keys(): match = bool(cond(key)) ind = ...
mongoose-master
mongoose_reformer/reformer_lib/reformer_enc_dec.py
import torch import torch.nn as nn from torch.autograd.function import Function from torch.utils.checkpoint import get_device_states, set_device_states # following example for saving and setting rng here https://pytorch.org/docs/stable/_modules/torch/utils/checkpoint.html class Deterministic(nn.Module): def __init...
mongoose-master
mongoose_reformer/reformer_lib/reversible.py
from torch import nn from reformer_lib import LSHAttention, LSHSelfAttention from collections import defaultdict class Recorder(nn.Module): def __init__(self, net): super().__init__() self.iter = 0 self.recordings = defaultdict(list) self.net = net self.on = True sel...
mongoose-master
mongoose_reformer/reformer_lib/recorder.py
from reformer_lib.reformer_pytorch import LSHAttention, LSHSelfAttention, Reformer, ReformerLM from reformer_lib.reformer_enc_dec import ReformerEncDec from reformer_lib.recorder import Recorder from reformer_lib.autopadder import Autopadder
mongoose-master
mongoose_reformer/reformer_lib/__init__.py
import torch from mongoose_slide.slide_lib.simHash import SimHash class Scheduler: def __init__(self, data, D, k=1, l=10, thresh=0.01): self.thresh_hash = SimHash(D, k, l) self.hash_codes = self.thresh_hash.hash(data) self.thresh = thresh def detect_change(self, updated_data): ...
mongoose-master
mongoose_reformer/reformer_lib/scheduler.py
import math import torch import torch.nn as nn from torch.nn import Identity import torch.nn.functional as F from torch.autograd import Function from functools import partial, reduce, wraps from itertools import chain from operator import mul from local_attention import LocalAttention from axial_positional_embedding i...
mongoose-master
mongoose_reformer/reformer_lib/reformer_pytorch.py
mongoose-master
mongoose_slide/__init__.py
import os import sys import numpy as np import torch from torch.utils.data import Dataset, DataLoader class MultiLabelDataset(Dataset): def __init__(self, filename): self.build(filename) def build(self, filename): with open(filename) as f: metadata = f.readline().split() ...
mongoose-master
mongoose_slide/slide_lib/lazy_parser.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from mongoose_slide.slide_lib.simHash import SimHash from mongoose_slide.slide_lib.lsh import LSH import time use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "c...
mongoose-master
mongoose_slide/slide_lib/lsh_softmax.py
import torch from mongoose_slide.slide_lib.cupy_kernel import cupyKernel import numpy as np use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") kernel = ''' extern "C" __global__ void fingerprint(const float* src, const int k, const int L, long* fp) { // product (N x ...
mongoose-master
mongoose_slide/slide_lib/simHash.py
mongoose-master
mongoose_slide/slide_lib/__init__.py
import collections import os import sys import math import random import numpy as np import numpy.random import scipy as sp import scipy.stats import torch import os from clsh import pyLSH # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"]=config.gpu use_cuda = tor...
mongoose-master
mongoose_slide/slide_lib/lsh.py
import cupy as cp from cupy.cuda import function from cupy.cuda import device from pynvrtc.compiler import Program from collections import namedtuple # CUDA Stream Stream = namedtuple('Stream', ['ptr']) class cupyKernel: def __init__(self, kernel, func_name): self.kernel = kernel self.title = func...
mongoose-master
mongoose_slide/slide_lib/cupy_kernel.py
import numpy as np import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import Dataset from mongoose_slide.slide_lib.simHash import SimHash from mongoose_slide.slide_lib.lsh import LSH use_cuda = torch.cuda.is_available() device = tor...
mongoose-master
mongoose_slide/slide_lib/network.py
import torch import torch.nn as nn import torch.nn.functional as F use_cuda = torch.cuda.is_available() device = torch.device("cuda:0" if use_cuda else "cpu") class TripletNet(nn.Module): def __init__(self, margin, K, L, layer_size): super(TripletNet, self).__init__() self.K = K self.L = L self.dense1 = nn.Li...
mongoose-master
mongoose_slide/slide_lib/triplet_network.py
import math import torch from torch.optim import Optimizer class Adam(Optimizer): """Implements Adam algorithm. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups ...
mongoose-master
mongoose_slide/slide_lib/adam_base.py
from setuptools import setup from setuptools.extension import Extension from Cython.Build import cythonize import numpy setup(name="clsh", ext_modules=cythonize(Extension( "clsh", # the extension name sources=["clsh.pyx", "LSH.cpp"], # the Cython source and additional C++ source files ...
mongoose-master
lsh_lib/setup.py
import torch from cupy_kernel import cupyKernel import numpy as np kernel = ''' extern "C" __global__ void fingerprint(const float* src, const int k, const int L, long* fp) { // product (N x kL bits) -> Column-Major Order // const int L = gridDim.y; // const int k = blockDim.x; int offs...
mongoose-master
lsh_lib/matrix_simhash.py
import torch import query_mul class QueryMulFn(torch.autograd.Function): """C = A @ B where A and B are dense matrices, but the output C is sparse, specified by CSR format """ @staticmethod def forward(ctx, A, B, rowPtrC, colIdxC): # Ensure that A and B are contiguous in the column-major forma...
mongoose-master
lsh_lib/query_mul_interface.py
import io import os import sys from distutils.util import convert_path from shutil import rmtree from setuptools import Command, find_packages, setup main_ns = {} ver_path = convert_path("domino/version.py") with open(ver_path) as ver_file: exec(ver_file.read(), main_ns) # Package meta-data. NAME = "domino" DES...
domino-main
setup.py
__version__ = "0.1.5"
domino-main
domino/version.py
import functools from typing import Any, List, Optional, Sequence from fvcore.common.registry import Registry as _Registry from tabulate import tabulate class Registry(_Registry): """Extension of fvcore's registry that supports aliases.""" _ALIAS_KEYWORDS = ("_aliases", "_ALIASES") def __init__(sel...
domino-main
domino/registry.py
from ._embed import embed, encoders from ._slice.abstract import Slicer from ._slice.mixture import MixtureSlicer, DominoSlicer from ._slice.spotlight import SpotlightSlicer from ._slice.barlow import BarlowSlicer from ._slice.multiaccuracy import MultiaccuracySlicer from ._slice.mlp import MLPSlicer from ._slice.fused...
domino-main
domino/__init__.py
from dataclasses import dataclass from functools import reduce, wraps from inspect import getcallargs from typing import Collection, Mapping import pandas as pd import torch import numpy as np from typing import List import meerkat as mk def unpack_args(data: mk.DataPanel, *args): if any(map(lambda x: isinstance...
domino-main
domino/utils.py
from typing import Dict, Union, Tuple, List from domino._describe.abstract import Describer from domino.utils import unpack_args import meerkat as mk import numpy as np from ._slice.abstract import Slicer from ._slice.mixture import MixtureSlicer from ._embed import embed from ._describe.abstract import Describer fro...
domino-main
domino/main.py
from typing import List, Union import ipywidgets as widgets import matplotlib.pyplot as plt import meerkat as mk import numpy as np import pandas as pd import seaborn as sns from IPython.display import display from domino.utils import unpack_args from ._describe import describe def explore( data: mk.DataPanel =...
domino-main
domino/gui.py
from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Dict, Union import meerkat as mk import numpy as np import torch.nn as nn from sklearn.base import BaseEstimator @dataclass class Config: pass class Describer(ABC, BaseEstimator): ...
domino-main
domino/_describe/abstract.py
from typing import Union import meerkat as mk import numpy as np import torch from scipy.stats import mode, pearsonr from .abstract import Describer from ..utils import convert_to_torch, unpack_args class CorrDescriber(Describer): """ Args: text (str, optional): A `Meerkat DataPanel` with columns ...
domino-main
domino/_describe/corr.py