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 |
|---|---|---|---|---|---|---|
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/run_distillation_logits_creator.py | import argparse
import os
import torch
import torch.utils.data
from tqdm import tqdm
import examples.run_classifier_dataset_utils as classifier_utils
import utils.logging as logging_utils
import utils.module as module_utils
from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification
def load_pr... | 4,609 | 45.1 | 137 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/evaluation/metrics/classification.py | import numpy as np
import torch
import torch.nn.functional as F
from .metric import *
"""
All classes/methods in this module expect to receive numpy ndarrays (and not pytorch tensors).
"""
class TopKAccuracyWithLogits(AveragedMetric):
"""
Top K accuracy metric that receives logits for multiclass classificat... | 33,954 | 36.602436 | 150 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/evaluation/metrics/accumulator.py | import serialization.torch_serializable as torch_serializable
class MetricAccumulator(torch_serializable.TorchSerializable):
"""
Metric accumulator that allows metric value aggregation.
"""
def __init__(self, metric, save_history=True):
"""
:param metric: metric to accumulate epoch va... | 1,684 | 32.039216 | 120 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/evaluation/evaluators/evaluator.py | from abc import ABCMeta, abstractmethod
from typing import Dict, Sequence
from evaluation.metrics import MetricInfo, MetricAccumulator
from serialization.torch_serializable import TorchSerializable
class MetricsEvaluator(TorchSerializable, metaclass=ABCMeta):
"""
Parent abstract class for a metric evaluator.... | 6,097 | 32.877778 | 145 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/evaluation/evaluators/dse_evaluator.py | import torch
import evaluation.metrics as metrics
import utils.module as module_utils
import utils.tensor as tensor_utils
from evaluation.evaluators.evaluator import Evaluator, TrainEvaluator
from evaluation.metrics import MetricAccumulator
class DSETrainEvaluator(TrainEvaluator):
"""
DSE Train evaluator for... | 3,133 | 39.701299 | 123 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/models/dse_model.py | import torch.nn as nn
from pytorch_pretrained_bert import BertSumConcatTopHiddenEmbeddingsPooler, BertMaxConcatTopHiddenEmbeddingsPooler
from pytorch_pretrained_bert import BertSumMeanTopHiddenEmbeddingsPooler, BertMaxMeanTopHiddenEmbeddingsPooler
class DSEModel(nn.Module):
"""
The DSE model. Wraps a BERT mo... | 3,784 | 55.492537 | 148 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/models/dse_siamese_classifier.py | import torch.nn as nn
from models.feature_extractors import ConcatCompareCombinedFeaturesExtractor, DotProductCombinedFeaturesExtractor
class CombineSiameseHead(nn.Module):
def __init__(self, input_dim, fc_dims=None, siamese_head_type="concat"):
super().__init__()
self.__verify_siamese_head_type... | 2,566 | 37.313433 | 123 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/models/feature_extractors.py | from abc import ABCMeta, abstractmethod
import torch
class CombinedFeaturesExtractor(metaclass=ABCMeta):
@abstractmethod
def extract_combined_features(self, first_input, second_input):
raise NotImplementedError
@abstractmethod
def get_combined_features_size(self, first_input_size):
... | 1,049 | 29 | 81 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/factories/dse_model_factory.py | import utils.module as module_utils
from models.dse_model import DSEModel
from models.dse_siamese_classifier import DSESiameseClassifier, CombineSiameseHead
from pytorch_pretrained_bert import BertForSequenceClassification
class DSEModelFactory:
@staticmethod
def create_model(bert_model, additional_embedding... | 1,177 | 48.083333 | 118 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/train/trainer.py | from abc import ABCMeta, abstractmethod
from collections import OrderedDict
import torch
import torch.utils.data
import utils.module as module_utils
from evaluation.evaluators.evaluator import VoidEvaluator
from serialization.torch_serializable import TorchSerializable
from train.callbacks.callback import ComposeCallb... | 5,184 | 40.48 | 148 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/train/callbacks/checkpoint.py | import os
import torch
from datetime import datetime
from .callback import *
class Checkpoint(Callback):
"""
Allows saving the trainer object (with all of its components) on epoch end. Will also persist trainer state at
the end of the fitting process.
Each save interval a checkpoint will be saved. I... | 5,596 | 46.033613 | 164 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/train/callbacks/callback.py | from collections import OrderedDict
from serialization.torch_serializable import TorchSerializable
class Callback(TorchSerializable):
"""
Callback for trainer to allow hooks for added functionality. Callback can raise StopFitIteration during hooks (except on_fit_end and
on_exception) in order to stop the... | 5,967 | 33.102857 | 145 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/pytorch_pretrained_bert/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and 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/LICEN... | 13,045 | 40.948553 | 139 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/pytorch_pretrained_bert/__main__.py | # coding: utf8
def main():
import sys
if (len(sys.argv) != 4 and len(sys.argv) != 5) or sys.argv[1] not in [
"convert_tf_checkpoint_to_pytorch",
"convert_openai_checkpoint",
"convert_transfo_xl_checkpoint",
"convert_gpt2_checkpoint",
]:
print(
"Should be used ... | 4,393 | 51.309524 | 145 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/pytorch_pretrained_bert/tokenization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and 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/LICEN... | 18,657 | 42.090069 | 179 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/pytorch_pretrained_bert/modeling.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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 cop... | 82,747 | 51.042767 | 187 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/pytorch_pretrained_bert/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
import fnmatch
import json
import os
import shutil
im... | 9,338 | 32.117021 | 98 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/utils/module.py | import torch
import torch.utils.data
def get_use_cuda(disable_cuda=False):
"""
Returns true if cuda is available and no explicit disable cuda flag given.
"""
return torch.cuda.is_available() and not disable_cuda
def get_device(disable_cuda=False, cuda_id=0):
"""
Returns a gpu cuda device if ... | 777 | 25.827586 | 78 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/utils/tensor.py | def to_numpy(tensor):
"""
Converts tensor to numpy ndarray. Will move tensor to cpu and detach it before converison. Numpy ndarray will share memory
of the tensor.
:param tensor: input pytorch tensor.
:return: numpy ndarray with shared memory of the given tensor.
"""
return tensor.cpu().deta... | 333 | 36.111111 | 126 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/configurable_trainers/dse_configurable_trainer.py | import json
import random
from datetime import datetime
import numpy as np
import torch.nn as nn
import torch.utils.data
import evaluation.evaluators as evaluators
import evaluation.metrics as metrics
import examples.run_classifier_dataset_utils as classifier_utils
import train.callbacks as callbacks
import train.tra... | 20,513 | 58.80758 | 150 | py |
corpus-tools | corpus-tools-main/remove_too_much_punc.py | # modified from https://github.com/pytorch/fairseq/blob/main/examples/m2m_100/process_data/remove_too_much_punc.py
import argparse
from string import punctuation
import sys
def len_no_punc(s, punc):
return len([ch for ch in s if ch in punc])
def filter_overpunc(len_npunc, len_sen):
return len_npunc < 0.5*le... | 1,274 | 33.459459 | 114 | py |
corpus-tools | corpus-tools-main/remove_too_much_punc_mono.py | # modified from https://github.com/pytorch/fairseq/blob/main/examples/m2m_100/process_data/remove_too_much_punc.py
import argparse
from string import punctuation
import sys
def len_no_punc(s, punc):
return len([ch for ch in s if ch in punc])
def filter_overpunc(len_npunc, len_sen):
return len_npunc < 0.5*le... | 1,060 | 31.151515 | 114 | py |
corpus-tools | corpus-tools-main/clean_histogram.py | # modified from https://github.com/pytorch/fairseq/blob/main/examples/m2m_100/process_data/clean_histogram.py
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--src', type=str, help='Source language')
parser.add_argument('--tgt', type=str, help='Target language')
parser.add_argument(... | 1,568 | 35.488372 | 109 | py |
IGEL | IGEL-master/gnnml-comparisons/igel_embedder.py | import torch as T
import igraph as ig
from structural import StructuralMapper
from embedders import SimpleStructuralEmbedder
from parameters import IGELParameters, NegativeSamplingParameters, TrainingParameters
from model_utils import train_negative_sampling
from learning import set_seed
TRAINING_OPTIONS = TrainingPa... | 2,184 | 51.02381 | 181 | py |
IGEL | IGEL-master/src/aggregators.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from activations import Sparsemax
def attention_concat(tensor):
'''Computes the concatenation of the attention masked tensor'''
return tensor.reshape(tensor.shape[0], -1)
def attention_sum(tensor):
'''Computes the su... | 10,843 | 41.52549 | 116 | py |
IGEL | IGEL-master/src/ppi_eval.py | import os
import json
import logging
import dill
import numpy as np
import igraph as ig
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.preprocessing import StandardScaler
from samplers import *
from embedders import *
from aggregators import *
from structural import StructuralMapper
fr... | 8,762 | 40.92823 | 566 | py |
IGEL | IGEL-master/src/model_utils.py | import torch
import torch.nn as nn
import torch.optim as optim
from models import EdgeInferenceModel, NegativeSamplingModel
from learning import GraphNetworkTrainer
from batching import graph_random_walks, negative_sampling_generator, negative_sampling_batcher
from embedders import SimpleStructuralEmbedder, GatedStruc... | 5,170 | 51.232323 | 145 | py |
IGEL | IGEL-master/src/run_node_inference_experiment.py | import os
import json
import dill
import random
import argparse
import threading
import torch
import torch.multiprocessing as mp
import numpy as np
from filelock import FileLock
from learning import EarlyStopping
from node_inference import node_inference_experiment
from experiment_utils import create_experiment_param... | 7,764 | 49.096774 | 198 | py |
IGEL | IGEL-master/src/run_lp_experiment.py | import os
import json
import dill
import random
import argparse
import threading
import torch
import torch.multiprocessing as mp
import numpy as np
from filelock import FileLock
from parameters import TrainingParameters
from link_prediction import link_prediction_experiment
from experiment_utils import create_experim... | 6,653 | 46.870504 | 196 | py |
IGEL | IGEL-master/src/structural.py | import math
import json
import numpy as np
import torch
import torch.nn.init as init
from multiprocessing import cpu_count, Pool
from collections import Counter
def get_relative_degrees(node, dist_vector):
'''Computes the relative degree of a node given a distance vector indexed by node indices.
Relative deg... | 7,368 | 42.347059 | 125 | py |
IGEL | IGEL-master/src/learning.py | import os
import dill
import torch
import random
import numpy as np
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from tqdm import tqdm, trange
from time import time
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
os.environ['PYTHONHAS... | 8,477 | 36.513274 | 178 | py |
IGEL | IGEL-master/src/link_prediction.py | import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from graph import load_graph, sample_edges, edge_difference, generate_negative_edges
from models import EdgeInferen... | 5,463 | 45.700855 | 151 | py |
IGEL | IGEL-master/src/clustering.py | import json
import argparse
import numpy as np
import torch
from sklearn.cluster import KMeans
from graph import load_graph
from models import NegativeSamplingModel
from learning import set_seed
from model_utils import make_structural_model, train_negative_sampling
from experiment_utils import create_experiment_para... | 3,566 | 40.476744 | 193 | py |
IGEL | IGEL-master/src/parameters.py | from batching import batch_dictionary_mapping
from aggregators import attention_concat, attention_sum, attention_mean, attention_max, combine_sum, combine_mean, combine_max
import torch.nn as nn
ACTIVATIONS = {
'elu': nn.ELU,
'relu': nn.ReLU,
'gelu': nn.GELU,
'relu6': nn.ReLU6,
'tanh': nn.Tanh... | 4,572 | 36.178862 | 126 | py |
IGEL | IGEL-master/src/models.py | import torch
import torch.nn as nn
class NodeInferenceModel(nn.Module):
def __init__(self, graph_model, graph_outs, num_outs, hidden_size=64, depth=1, activation=nn.ReLU):
super(NodeInferenceModel, self).__init__()
self.graph_model = graph_model
layers = []
for i in range(depth):
... | 3,811 | 42.318182 | 148 | py |
IGEL | IGEL-master/src/activations.py |
from __future__ import division
import torch
import torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Sparsemax(nn.Module):
"""Sparsemax activation function.
Pytorch implementation of Sparsemax function from:
-- "From Softmax to Sparsemax: A Sparse Model of At... | 3,168 | 32.010417 | 122 | py |
IGEL | IGEL-master/src/node_inference.py | import os
import json
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from graph import load_graph
from models import NodeIn... | 10,336 | 49.921182 | 203 | py |
IGEL | IGEL-master/src/embedders.py | import math
import igraph as ig
import torch
import torch.nn as nn
from structural import StructuralMapper
from activations import Sparsemax
class NodeEmbedder(nn.Module):
def __init__(self, data, node_key='id', requires_grad=True):
super(NodeEmbedder, self).__init__()
self.node_key = node_key
... | 7,646 | 41.016484 | 112 | py |
IGEL | IGEL-master/scripts/scalability.py | import os
import sys
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append('{}/../src/'.format(dir_path))
import time
import json
import torch
import igraph as ig
import pandas as pd
from itertools import product
from experiment_utils import create_experiment_params
from models import NegativeSampli... | 4,379 | 40.714286 | 123 | py |
skweak | skweak-main/examples/sentiment/transformer_model.py | from transformers import BertTokenizer, BertForSequenceClassification
from transformers import AdamW
from transformers import get_linear_schedule_with_warmup
from torch.nn import functional as F
import torch
import numpy as np
import argparse
from tqdm import tqdm
from sklearn.metrics import f1_score
import sys
sys... | 8,150 | 37.088785 | 152 | py |
skweak | skweak-main/skweak/utils.py | import functools
import json
import re
from typing import Dict, Iterable, List, Optional, Set, Tuple, TypeVar
import numpy as np
from spacy.tokens import Doc, DocBin, Span, Token # type: ignore
T = TypeVar('T')
############################################
# Utility functions for NLP analysis
######################... | 32,282 | 35.273034 | 111 | py |
vaeac | vaeac-master/prob_utils.py | import torch
from torch.distributions import Categorical, Normal
from torch.nn import Module
from torch.nn.functional import softplus, softmax
def normal_parse_params(params, min_sigma=0):
"""
Take a Tensor (e. g. neural network output) and return
torch.distributions.Normal distribution.
This Normal d... | 13,511 | 39.698795 | 78 | py |
vaeac | vaeac-master/imputation_networks.py | from torch import nn
from torch.optim import Adam
from mask_generators import MCARGenerator
from nn_utils import ResBlock, MemoryLayer, SkipConnection
from prob_utils import CategoricalToOneHotLayer, GaussianCategoricalLoss, \
GaussianCategoricalSampler, SetGaussianSigmasToOne
def get_imputati... | 3,723 | 31.382609 | 78 | py |
vaeac | vaeac-master/inpaint.py | from argparse import ArgumentParser
from importlib import import_module
from os import makedirs
from os.path import join
import torch
from torch.utils.data import DataLoader
from torchvision.transforms import ToPILImage
from tqdm import tqdm
from datasets import load_dataset, ZipDatasets
from train_utils import exten... | 5,790 | 36.849673 | 77 | py |
vaeac | vaeac-master/VAEAC.py | import math
import torch
from torch.distributions import kl_divergence
from torch.nn import Module
from prob_utils import normal_parse_params
class VAEAC(Module):
"""
Variational Autoencoder with Arbitrary Conditioning core model.
It is rather flexible, but have several assumptions:
+ The batch of o... | 7,814 | 44.17341 | 77 | py |
vaeac | vaeac-master/train_utils.py | import torch
from tqdm import tqdm
def extend_batch(batch, dataloader, batch_size):
"""
If the batch size is less than batch_size, extends it with
data from the dataloader until it reaches the required size.
Here batch is a tensor.
Returns the extended batch.
"""
while batch.shape[0] != ba... | 2,469 | 37 | 77 | py |
vaeac | vaeac-master/impute.py | from argparse import ArgumentParser
from copy import deepcopy
from importlib import import_module
from math import ceil
from os.path import exists, join
from sys import stderr
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from datasets import compute_normalization
from ... | 10,573 | 37.450909 | 78 | py |
vaeac | vaeac-master/datasets.py | from os.path import join, exists, isdir
import torch
from torch.utils.data import Dataset
from torchvision.datasets.folder import default_loader
from torchvision.transforms import CenterCrop, Compose, Normalize, ToTensor
from mask_generators import ImageMaskGenerator
def compute_normalization(data, one_hot_max_size... | 6,690 | 32.123762 | 79 | py |
vaeac | vaeac-master/mask_generators.py | import numpy as np
import torch
from torchvision import transforms
from PIL import Image
# Mask generator for missing feature imputation
class MCARGenerator:
"""
Returned mask is sampled from component-wise independent Bernoulli
distribution with probability of component to be unobserved p.
Such mask... | 11,889 | 38.370861 | 79 | py |
vaeac | vaeac-master/train.py | from argparse import ArgumentParser
from importlib import import_module
from math import ceil
from os import replace
from os.path import exists, join
from shutil import copy
from sys import stderr
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from datasets import load_dataset
from train_u... | 8,180 | 38.907317 | 78 | py |
vaeac | vaeac-master/nn_utils.py | import torch
from torch import nn
class ResBlock(nn.Module):
"""
Usual full pre-activation ResNet bottleneck block.
For more information see
He, K., Zhang, X., Ren, S., & Sun, J. (2016, October).
Identity mappings in deep residual networks.
European Conference on Computer Vision (pp. 630-645).... | 3,594 | 31.681818 | 77 | py |
vaeac | vaeac-master/celeba_model/model.py | from torch import nn
from torch.optim import Adam
from mask_generators import ImageMaskGenerator
from nn_utils import ResBlock, MemoryLayer, SkipConnection
from prob_utils import normal_parse_params, GaussianLoss
# sampler from the model generative distribution
# here we return mean of the Gaussian to avoid white no... | 4,421 | 37.452174 | 75 | py |
pytorch-metric-learning | pytorch-metric-learning-master/setup.py | import sys
import setuptools
sys.path.insert(0, "src")
import pytorch_metric_learning
with open("README.md", "r") as fh:
long_description = fh.read()
extras_require_with_hooks = [
"record-keeper >= 0.9.32",
"faiss-gpu >= 1.6.3",
"tensorboard",
]
extras_require_with_hooks_cpu = [
"record-keeper >... | 1,507 | 27.45283 | 138 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/distances/snr_distance.py | import torch
from .base_distance import BaseDistance
# Signal to Noise Ratio
class SNRDistance(BaseDistance):
def __init__(self, **kwargs):
super().__init__(**kwargs)
assert not self.is_inverted
def compute_mat(self, query_emb, ref_emb):
anchor_variances = torch.var(query_emb, dim=1)... | 714 | 31.5 | 67 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/distances/lp_distance.py | import torch
from ..utils import loss_and_miner_utils as lmu
from .base_distance import BaseDistance
class LpDistance(BaseDistance):
def __init__(self, **kwargs):
super().__init__(**kwargs)
assert not self.is_inverted
def compute_mat(self, query_emb, ref_emb):
dtype, device = query_e... | 1,042 | 36.25 | 82 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/distances/base_distance.py | import torch
from ..utils.module_with_records import ModuleWithRecords
class BaseDistance(ModuleWithRecords):
def __init__(
self, normalize_embeddings=True, p=2, power=1, is_inverted=False, **kwargs
):
super().__init__(**kwargs)
self.normalize_embeddings = normalize_embeddings
... | 3,508 | 34.806122 | 86 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/distances/dot_product_similarity.py | import torch
from .base_distance import BaseDistance
class DotProductSimilarity(BaseDistance):
def __init__(self, **kwargs):
super().__init__(is_inverted=True, **kwargs)
assert self.is_inverted
def compute_mat(self, query_emb, ref_emb):
return torch.matmul(query_emb, ref_emb.t())
... | 424 | 25.5625 | 52 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/distances/batched_distance.py | import torch
class BatchedDistance(torch.nn.Module):
def __init__(self, distance, iter_fn=None, batch_size=32):
super().__init__()
self.distance = distance
self.iter_fn = iter_fn
self.batch_size = batch_size
def forward(self, query_emb, ref_emb=None):
ref_emb = ref_emb... | 755 | 29.24 | 63 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/samplers/fixed_set_of_triplets.py | import numpy as np
import torch
from torch.utils.data.sampler import Sampler
from ..utils import common_functions as c_f
class FixedSetOfTriplets(Sampler):
"""
Upon initialization, this will create num_triplets triplets based on
the labels provided in labels_to_indices. This is for experimental purposes,... | 2,132 | 40.823529 | 85 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/samplers/tuples_to_weights_sampler.py | import numpy as np
import torch
from torch.utils.data.sampler import Sampler
from ..testers import BaseTester
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
class TuplesToWeightsSampler(Sampler):
def __init__(self, model, miner, dataset, subset_size=None, **tester_kwa... | 1,696 | 32.94 | 85 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/samplers/m_per_class_sampler.py | import torch
from torch.utils.data.sampler import Sampler
from ..utils import common_functions as c_f
# modified from
# https://raw.githubusercontent.com/bnulihaixia/Deep_metric/master/utils/sampler.py
class MPerClassSampler(Sampler):
"""
At every iteration, this will return m samples per class. For example,... | 2,555 | 38.9375 | 86 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/samplers/hierarchical_sampler.py | import itertools
from collections import defaultdict
import torch
from torch.utils.data.sampler import Sampler
from ..utils import common_functions as c_f
# Inspired by
# https://github.com/kunhe/Deep-Metric-Learning-Baselines/blob/master/datasets.py
class HierarchicalSampler(Sampler):
def __init__(
sel... | 3,843 | 35.609524 | 117 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/pair_margin_miner.py | import torch
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
class PairMarginMiner(BaseMiner):
"""
Returns positive pairs that have distance greater than a margin and negative
pairs that have distance less than a margin
"""
def __init__(self, pos_margin=0.2, neg... | 1,742 | 33.176471 | 80 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/distance_weighted_miner.py | import torch
from ..distances import LpDistance
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
# adapted from
# https://github.com/chaoyuaw/incubator-mxnet/blob/master/example/gluon/embedding_learning/model.py
class DistanceWeightedMiner(... | 2,066 | 35.263158 | 99 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/triplet_margin_miner.py | import torch
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
class TripletMarginMiner(BaseMiner):
"""
Returns triplets that violate the margin
Args:
margin
type_of_triplets: options are "all", "hard", or "semihard".
"all" means all triplet... | 2,461 | 38.079365 | 110 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/base_miner.py | import torch
from ..utils import common_functions as c_f
from ..utils.module_with_records_and_reducer import ModuleWithRecordsAndDistance
class BaseMiner(ModuleWithRecordsAndDistance):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_to_recordable_attributes(
list_of_... | 2,201 | 37.631579 | 82 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/angular_miner.py | import numpy as np
import torch
from ..distances import LpDistance
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
class AngularMiner(BaseMiner):
"""
Returns triplets that form an angle greater than some threshold (angle).
The ... | 2,874 | 37.851351 | 81 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/uniform_histogram_miner.py | import torch
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
class UniformHistogramMiner(BaseMiner):
def __init__(self, num_bins=100, pos_per_bin=10, neg_per_bin=10, **kwargs):
super().__init__(**kwargs)
self.num_bins = num_bins
self.pos_per_bin = pos_per... | 2,303 | 33.38806 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/multi_similarity_miner.py | import torch
from ..distances import CosineSimilarity
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
class MultiSimilarityMiner(BaseMiner):
def __init__(self, epsilon=0.1, **kwargs):
super().__init__(**kwargs)
self.eps... | 2,315 | 33.567164 | 83 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/hdc_miner.py | import math
import torch
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
# mining method used in Hard Aware Deeply Cascaded Embeddings
# https://arxiv.org/abs/1611.05720
class HDCMiner(BaseMiner):
def __init__(self, filter_percentage=0.5, **kwargs):
super().__init__(**k... | 2,192 | 32.227273 | 73 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/batch_easy_hard_miner.py | import torch
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from .base_miner import BaseMiner
class BatchEasyHardMiner(BaseMiner):
HARD = "hard"
SEMIHARD = "semihard"
EASY = "easy"
ALL = "all"
all_batch_mining_strategies = [HARD, SEMIHARD, EASY, ALL]
... | 8,131 | 38.862745 | 96 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/miners/embeddings_already_packaged_as_triplets.py | import torch
from .base_miner import BaseMiner
class EmbeddingsAlreadyPackagedAsTriplets(BaseMiner):
# If the embeddings are grouped by triplet,
# then use this miner to force the loss function to use the already-formed triplets
def mine(self, embeddings, labels, ref_emb, ref_labels):
batch_size ... | 493 | 31.933333 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/utils/inference.py | import numpy as np
import torch
from ..distances import BatchedDistance, CosineSimilarity
from . import common_functions as c_f
try:
import faiss
import faiss.contrib.torch_utils
except ModuleNotFoundError:
pass
class MatchFinder:
def __init__(self, distance, threshold=None):
self.distance =... | 11,776 | 33.946588 | 118 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/utils/loss_and_miner_utils.py | import math
import numpy as np
import torch
from . import common_functions as c_f
# input must be 2D
def logsumexp(x, keep_mask=None, add_one=True, dim=1):
if keep_mask is not None:
x = x.masked_fill(~keep_mask, c_f.neg_inf(x.dtype))
if add_one:
zeros = torch.zeros(x.size(dim - 1), dtype=x.d... | 9,444 | 34.111524 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/utils/accuracy_calculator.py | import torch
from sklearn.metrics import adjusted_mutual_info_score, normalized_mutual_info_score
from . import common_functions as c_f
from .inference import FaissKMeans, FaissKNN
EQUALITY = torch.eq
def get_unique_labels(labels):
return torch.unique(labels, dim=0)
def maybe_get_avg_of_avgs(
accuracy_per... | 18,488 | 33.950851 | 134 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/utils/common_functions.py | import collections
import glob
import logging
import os
import re
import numpy as np
import scipy.stats
import torch
LOGGER_NAME = "PML"
LOGGER = logging.getLogger(LOGGER_NAME)
NUMPY_RANDOM = np.random
COLLECT_STATS = False
def set_logger_name(name):
global LOGGER_NAME
global LOGGER
LOGGER_NAME = name
... | 15,447 | 28.59387 | 88 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/utils/logging_presets.py | import os
import sqlite3
import torch
from . import common_functions as c_f
# You can write your own hooks for logging.
# But if you'd like something that just works, then use this HookContainer.
# You'll need to install record-keeper and tensorboard.
# pip install record-keeper tensorboard
class HookContainer:
... | 15,836 | 35.659722 | 98 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/utils/distributed.py | import torch
from ..losses import BaseMetricLossFunction, CrossBatchMemory
from ..miners import BaseMiner
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
# modified from https://github.com/allenai/allennlp
def is_distributed():
return torch.distributed.is_available() a... | 6,399 | 34.359116 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/utils/module_with_records.py | import torch
from . import common_functions as c_f
class ModuleWithRecords(torch.nn.Module):
def __init__(self, collect_stats=None):
super().__init__()
self.collect_stats = (
c_f.COLLECT_STATS if collect_stats is None else collect_stats
)
def add_to_recordable_attributes(... | 661 | 25.48 | 77 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/sum_reducer.py | import torch
from pytorch_metric_learning.reducers import MeanReducer
class SumReducer(MeanReducer):
def element_reduction(self, losses, *_):
return torch.sum(losses)
| 182 | 19.333333 | 56 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/multiple_reducers.py | import torch
from .base_reducer import BaseReducer
from .mean_reducer import MeanReducer
class MultipleReducers(BaseReducer):
def __init__(self, reducers, default_reducer=None, **kwargs):
super().__init__(**kwargs)
self.reducers = torch.nn.ModuleDict(reducers)
self.default_reducer = (
... | 1,214 | 35.818182 | 83 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/divisor_reducer.py | import torch
from ..utils import common_functions as c_f
from .base_reducer import BaseReducer
class DivisorReducer(BaseReducer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_to_recordable_attributes(name="divisor", is_stat=True)
def unpack_loss_info(self, ... | 1,551 | 36.853659 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/class_weighted_reducer.py | import torch
from ..utils import common_functions as c_f
from .base_reducer import BaseReducer
class ClassWeightedReducer(BaseReducer):
def __init__(self, weights, **kwargs):
super().__init__(**kwargs)
self.weights = weights
def element_reduction(self, losses, loss_indices, embeddings, label... | 1,130 | 38 | 78 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/mean_reducer.py | import torch
from .base_reducer import BaseReducer
class MeanReducer(BaseReducer):
def element_reduction(self, losses, *_):
return torch.mean(losses)
def pos_pair_reduction(self, losses, *args):
return self.element_reduction(losses, *args)
def neg_pair_reduction(self, losses, *args):
... | 473 | 25.333333 | 52 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/threshold_reducer.py | import torch
from .base_reducer import BaseReducer
class ThresholdReducer(BaseReducer):
def __init__(self, low=None, high=None, **kwargs):
super().__init__(**kwargs)
assert (low is not None) or (
high is not None
), "At least one of low or high must be specified"
self.... | 2,211 | 38.5 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/base_reducer.py | import torch
from ..utils import common_functions as c_f
from ..utils.module_with_records import ModuleWithRecords
class BaseReducer(ModuleWithRecords):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_to_recordable_attributes(name="losses_size", is_stat=True)
... | 3,816 | 35.701923 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/reducers/per_anchor_reducer.py | import torch
from ..utils import common_functions as c_f
from .base_reducer import BaseReducer
from .mean_reducer import MeanReducer
def aggregation_func(x, num_per_row):
zero_denom = num_per_row == 0
x = torch.sum(x, dim=1) / num_per_row
x[zero_denom] = 0
return x
class PerAnchorReducer(BaseReduce... | 2,149 | 32.59375 | 83 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/regularizers/zero_mean_regularizer.py | import torch
from ..utils import common_functions as c_f
from .base_regularizer import BaseRegularizer
class ZeroMeanRegularizer(BaseRegularizer):
def compute_loss(self, embeddings):
return {
"loss": {
"losses": torch.abs(torch.sum(embeddings, dim=1)),
"indices... | 432 | 26.0625 | 66 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/regularizers/base_regularizer.py | from ..utils import common_functions as c_f
from ..utils.module_with_records_and_reducer import ModuleWithRecordsReducerAndDistance
class BaseRegularizer(ModuleWithRecordsReducerAndDistance):
def compute_loss(self, x):
raise NotImplementedError
def forward(self, x):
"""
x should have ... | 499 | 30.25 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/regularizers/sparse_centers_regularizer.py | import torch
from ..distances import CosineSimilarity
from ..reducers import DivisorReducer
from ..utils import common_functions as c_f
from .base_regularizer import BaseRegularizer
class SparseCentersRegularizer(BaseRegularizer):
def __init__(self, num_classes, centers_per_class, **kwargs):
super().__in... | 2,697 | 37 | 77 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/regularizers/center_invariant_regularizer.py | import torch
from ..distances import LpDistance
from ..utils import common_functions as c_f
from .base_regularizer import BaseRegularizer
class CenterInvariantRegularizer(BaseRegularizer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
c_f.assert_distance_type(self, LpDistance, power=1,... | 871 | 32.538462 | 87 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/regularizers/regular_face_regularizer.py | import torch
from ..distances import CosineSimilarity
from ..utils import common_functions as c_f
from .base_regularizer import BaseRegularizer
# modified from http://kaizhao.net/regularface
class RegularFaceRegularizer(BaseRegularizer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
as... | 1,229 | 33.166667 | 86 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/regularizers/lp_regularizer.py | import torch
from ..utils import common_functions as c_f
from .base_regularizer import BaseRegularizer
class LpRegularizer(BaseRegularizer):
def __init__(self, p=2, power=1, **kwargs):
super().__init__(**kwargs)
self.p = p
self.power = power
self.add_to_recordable_attributes(list_... | 723 | 27.96 | 86 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/testers/with_same_parent_label.py | from collections import defaultdict
import numpy as np
import torch
from ..utils import common_functions as c_f
from .base_tester import BaseTester
class WithSameParentLabelTester(BaseTester):
def do_knn_and_accuracies(
self,
accuracies,
embeddings_and_labels,
query_split_name,
... | 2,791 | 38.885714 | 112 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/testers/base_tester.py | from collections import defaultdict
import torch
import tqdm
from ..utils import common_functions as c_f
from ..utils import inference
from ..utils.accuracy_calculator import AccuracyCalculator
class BaseTester:
def __init__(
self,
normalize_embeddings=True,
use_trunk_output=False,
... | 12,495 | 38.796178 | 100 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/testers/global_twostream_embedding_space.py | import torch
import tqdm
from ..utils import common_functions as c_f
from .global_embedding_space import GlobalEmbeddingSpaceTester
class GlobalTwoStreamEmbeddingSpaceTester(GlobalEmbeddingSpaceTester):
def compute_all_embeddings(self, dataloader, trunk_model, embedder_model):
s, e = 0, 0
with to... | 2,820 | 41.104478 | 88 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/losses/manifold_loss.py | import numpy as np
import torch
from torch import nn
from ..distances import CosineSimilarity
from ..utils import common_functions as c_f
from .base_metric_loss_function import BaseMetricLossFunction
class ManifoldLoss(BaseMetricLossFunction):
r"""
The parameters are defined as in the paper https://openacces... | 4,731 | 35.122137 | 190 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/losses/contrastive_loss.py | import torch
from ..reducers import AvgNonZeroReducer
from ..utils import loss_and_miner_utils as lmu
from .generic_pair_loss import GenericPairLoss
class ContrastiveLoss(GenericPairLoss):
def __init__(self, pos_margin=0, neg_margin=1, **kwargs):
super().__init__(mat_based_loss=False, **kwargs)
s... | 2,005 | 35.472727 | 84 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/losses/margin_loss.py | import torch
from ..reducers import DivisorReducer
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from .base_metric_loss_function import BaseMetricLossFunction
class MarginLoss(BaseMetricLossFunction):
def __init__(
self,
margin=0.2,
nu=0,
... | 3,288 | 30.932039 | 84 | py |
pytorch-metric-learning | pytorch-metric-learning-master/src/pytorch_metric_learning/losses/supcon_loss.py | from ..distances import CosineSimilarity
from ..reducers import AvgNonZeroReducer
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from .generic_pair_loss import GenericPairLoss
# adapted from https://github.com/HobbitLong/SupContrast
class SupConLoss(GenericPairLoss):
d... | 1,715 | 36.304348 | 87 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.