content
stringlengths
200
198k
repo
stringlengths
4
186
path
stringclasses
1 value
license
stringclasses
101 values
size
int64
200
198k
sha
stringlengths
40
40
lang
stringclasses
1 value
ext
stringclasses
1 value
import os import argparse from torch.backends import cudnn from config import config, dataset_config, merge_cfg_arg from dataloder import get_loader from solver_cycle import Solver_cycleGAN from solver_makeup import Solver_makeupGAN from solver_makeup2 import Solver_makeupGAN2 from solver_makeup3 import Solver_makeu...
train.py
MIT
5,075
e61d5076bfa039937fdd7011cf3a5e493535584e
Python
py
# -*- coding: utf-8 -*- """ Created on Fri Jun 25 13:55:21 2021 @author: DELL """ import shutil import torch import numpy as np import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt from torch.utils.data import Dataset from torch.utils.data import DataLoader import os ...
code_history/remove_code/my_classifier.py
MIT
12,628
3a68b22830246e1cd564ceb742807135ec02a2f8
Python
py
import torch def validation(model, validation_loader, criterion, optimizer, gpu=True): test_loss = 0 accuracy = 0 for ii, (inputs, labels) in enumerate(validation_loader): optimizer.zero_grad() if torch.cuda.is_available() and gpu: inputs, labels = inputs.to('cuda:0'), labels...
trainer.py
MIT
2,136
d77206e644969b57c12affb2c3d6b84702830e2b
Python
py
import json import torch from torch.utils.data import Dataset class ActivityDataset(Dataset): """ Dataloader for activity dataset """ def __init__(self, joints, phase): """ Load inputs and outputs from the pickles files from gt joints, mask joints or both """ assert(...
monoloco/monoloco/train/datasets.py
MIT
2,868
3a68c17df686535bfdf81014f75c36be075b0dd6
Python
py
""" Test case for DQN pytroch! CartPole-v0 """ import numpy as np import gym import torch from dqn_pytorch import DQN from collections import deque EPISODES = 20 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") env = gym.make('CartPole-v0') state_size = env.observation_space.shape[0] action_si...
DQL/pole_train.py
MIT
2,073
28c2296df931d71b329a9c282ed41c4bd087e86d
Python
py
#!/usr/bin/env python3 import argparse import os import numpy as np import time import torch from torch import optim import visual_plt import utils import pandas as pd from param_stamp import get_param_stamp, get_param_stamp_from_args import evaluate from data import get_multitask_experiment from encoder import Classif...
main.py
MIT
34,983
1ea8a08f37e57906c8b5488d05b3b63d6527e1a3
Python
py
import os, sys import logging import torch from pytorch_utils.trainers.train_utils import ( accuracy, distributed_average_gradients ) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(stream=sys.stdout)) def test_helper(test_loader, model, criterion, epo...
workshops/sagemaker/pytorch_utils/trainers/classifier_trainers.py
CC0-1.0
3,594
3a68cef1ab8204b101179e78cf1a7403a7cb86b7
Python
py
import torch import tqdm from sklearn.metrics import roc_auc_score from torch.utils.data import DataLoader from torchfm.dataset.avazu import AvazuDataset from torchfm.dataset.criteo import CriteoDataset from torchfm.dataset.movielens import MovieLens1MDataset, MovieLens20MDataset from torchfm.model.afi import Automati...
examples/main.py
MIT
6,785
ff2e9ca2350660db68d7d4a60601c687bdc5b78d
Python
py
""" Usage: main.py train [options] [--dataset-config=<dataset config path>] [--model-config=<model config path>] [--runner-config=<runner config path>] main.py train (-h | --help) Options: --dataset-config <dataset config path> Path to YAML file for dataset configuration [default: conf/mlp/dataset/dataset...
train.py
MIT
3,329
f949d4102965674c1fed49268a9b41fff5abeb2d
Python
py
import os, sys, inspect, re from collections import OrderedDict from torch.optim import * optimizer_dict = {} naming_rule = lambda x: re.sub("([a-z])([A-Z])", r"\1_\2", x).lower() for class_name, _class in inspect.getmembers(sys.modules[__name__], inspect.isclass): optimizer_dict[naming_rule(class_name)] = _class...
jorldy/core/optimizer/__init__.py
Apache-2.0
1,177
3a68e4e20a4dd0992df1f91934f466b25070f53d
Python
py
""" File defining the recurrent neural network models that we trained. They all inherit the class NNModel defined in nnmodel.py. """ import torch.nn as nn from torch.nn import functional as F from nnmodel import NNModel class LSTMNet1(NNModel): def __init__(self, dim_input, dim_recurrent, num_layers, dim_outpu...
project1/src/rec_models.py
MIT
2,747
5ec2de22ca0463700ebdf91bd58f8d61dc180828
Python
py
from threading import Thread import gtimer as gt from torch.multiprocessing import Pipe, Process import rlkit.torch.pytorch_util as ptu import rlkit.torch.vae.vae_schedules as vae_schedules from rlkit.core import logger from rlkit.data_management.online_vae_replay_buffer import OnlineVaeRelabelingBuffer from rlkit.da...
rlkit/rlkit/torch/skewfit/online_vae_algorithm.py
MIT
7,458
7c992ba4354db4bbea5552855a71403712b15090
Python
py
import time import os import argparse import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import seaborn as sns parser = argparse.ArgumentParser() parser.add_argument('--tol', type=float, default=1e-3) parser.add_argument('--adjoint', type=eval, default=Fa...
experiments/function_fitting/double_function/double_func_anode_mixed.py
MIT
7,258
4b2e6f18db0bed10d3c0f9340ac5ee62400051ea
Python
py
import torch import numpy as np from .strategy import Strategy import torch.nn.functional as F # use permutation to implement random # seed is stable class RandomSampling(Strategy): def __init__(self, source, target_train, target_test, idxs_lb, net, cfg): super(RandomSampling, self).__init__(source, target...
sample_strategy/RandomSample.py
Apache-2.0
591
a914e71a0474ebd51adeb958f7e8d518171e7315
Python
py
from torch.utils.data import Dataset import numpy as np import torch from pathlib import Path class TextDataset(Dataset): def __init__(self,root_dir,mode): self.root_dir=root_dir self.mode=mode file=Path(self.root_dir).joinpath(f"{self.mode}.txt") self.data=np.loadtxt(file,dtype=...
lab4/dataset.py
MIT
959
4b01582c4a5922a4ccb2d78b9a96e9214af70654
Python
py
import torch import torch.nn as nn import torch.nn.functional as F def initialize_weights(module): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight.data, mode='fan_out', nonlinearity='relu') elif isinstance(module, ...
pytorch_image_classification/models/cifar/se_resnet_preact.py
MIT
10,637
d771e8aa5d5d6f3e63233a192a7ed48a65a3b1bf
Python
py
import numpy as np import torch from nltk.translate.bleu_score import sentence_bleu import os from metric import get_bleu class _EVAL(object): def __init__(self, vocab_obj, args, device): super().__init__() self.m_sos_idx = vocab_obj.sos_idx self.m_eos_idx = vocab_obj.eos_idx self....
eval_rec.py
MIT
7,455
343fff43482c92b2e7b78cc38e2e632f57e24ab2
Python
py
"""Module to perform projective transformations to tensors.""" from typing import Tuple, List, Optional import warnings import torch import kornia as K from kornia.geometry.conversions import convert_affinematrix_to_homography3d from kornia.geometry.transform.homography_warper import normalize_homography3d, homograph...
kornia/geometry/transform/projwarp.py
ECL-2.0,Apache-2.0
16,156
b243c189314c2ce4f0dcf4b4478032be7294658a
Python
py
# Copyright 2020 - 2021 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in wri...
monai/data/nifti_saver.py
Apache-2.0
9,877
427b2d29d5af4e115fd141e61623c9922b7bafd2
Python
py
''' Handling the data io ''' import os import argparse import logging import dill as pickle import urllib from tqdm import tqdm import sys import codecs import spacy import torch import tarfile import torchtext.data import torchtext.datasets from torchtext.datasets import TranslationDataset import transformer.Constants...
preprocess.py
MIT
15,284
3a69a3b52e49339d3fb9cb70e8c2df1c3e3bb4ff
Python
py
import numpy as np import matplotlib.pyplot as plt import torch import torchvision import copy class Data: def __init__(self, dataset_name, dataset, dataloader): self.dataset = dataset self.dataloader = dataloader self.name = dataset_name if self.name == 'cifar': # ...
lib/data.py
MIT
2,989
3a69a4c8d5dfb9512d75e6c91e13dc3d8aee60ee
Python
py
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
utils/boxes.py
MIT
15,773
f93c7ec07b4de2414764da880c6ee92b6f9d6711
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Save some representative images from each dataset to disk. """ import random import torch import argparse from domainbed import hparams_registry from domainbed import datasets import imageio import os from tqdm import tqdm if __name__ == '__ma...
domainbed/scripts/save_images.py
MIT
2,020
3a69cb806b8930be8d7edf6c609ac3e2c359fa17
Python
py
import argparse import torch from torch.utils.data import DataLoader from pytorch_transformers import GPT2LMHeadModel, AdamW, WarmupLinearSchedule from utils.data import EpisodeSummaryTokenizer, create_datasets_from_jsons from utils.gen_utils import set_random_seeds, generate_sequence def make_train_state(save_path, ...
train.py
MIT
11,407
45ac66a1bd22824043f39a840b07e718ef2ee031
Python
py
# ========================================================================= # Copyright (C) 2021. Huawei Technologies Co., Ltd. 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 copy of the Lice...
fuxictr/pytorch/models/FFM.py
Apache-2.0
3,043
ff1b734e471f9f81dd48b4a5130c2764645d88c1
Python
py
import math import random import numpy as np import matplotlib import matplotlib.pyplot as plt # from itertools import count from collections import namedtuple ## Import function approximator for Q from other file from Q_network import QNetwork from whittle_network import Whittle from whittle_network import New_Whittl...
src/whittle_old/FGDQN_Agent.py
MIT
6,793
d7fcd0ef07549417285910d5b72221d30395f33b
Python
py
# code is based on https://github.com/katerakelly/pytorch-maml import torchvision import torchvision.datasets as dset import torchvision.transforms as transforms import torch from torch.utils.data import DataLoader,Dataset import random import os from PIL import Image import matplotlib.pyplot as plt import numpy as np ...
ucf101/task_generator_vid_8lian.py
MIT
6,332
5f0ad0b2c0c832245025f78c4608eefab4fb6c6a
Python
py
#summary pytorch from torchsummary import summary #pip install torchsummary import torchvision.models as models def summaryNet(net, inputSize): summary(net, inputSize) print(net) def test(): alexnet = models.alexnet(pretrained=False) #alexnet.cuda() help(summary) summary(alexnet, (3, 224, 224)) print(...
src/summaryModel.py
MIT
3,617
3a6a3086f2a845b5f36ab1d0a800c65add67c56d
Python
py
import logging import torch import torch.nn as nn import numpy as np from pykp.masked_softmax import MaskedSoftmax class Attention(nn.Module): def __init__(self, decoder_size, memory_bank_size, coverage_attn, attn_mode): super(Attention, self).__init__() # attention if attn_mode == "concat"...
pykp/attention.py
MIT
9,362
f986f53a68b2006003721d2b6879d2074d197081
Python
py
'''This is the repo which contains the original code to the WACV 2022 paper "Fully Convolutional Cross-Scale-Flows for Image-based Defect Detection" by Marco Rudolph, Tom Wehrbein, Bodo Rosenhahn and Bastian Wandt. For further information contact Marco Rudolph (rudolph@tnt.uni-hannover.de)''' import config as c from t...
baselines/differnet/main.py
MIT
4,785
3a6a6e55dd911a5b4aa86da7d175e647050d080c
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from einops import rearrange, repeat import torch import torch.nn as nn import torch.nn.functional as Fn import math def iterative_inv(mat, n_iter = 6, init_option="exact"): I = torch.eye(mat.size(-2), device = mat.dev...
slowfast/models/nystrom_helper.py
Apache-2.0
5,098
804acc15678162491c0ecb81fde06ec858b1c5c7
Python
py
import sys, os, time, math, random from copy import deepcopy import numpy as np from tqdm import tqdm import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.init import xavier_uniform_ from sklearn.metrics import accuracy_score from tensorboardX import SummaryWriter from utils.data_loader imp...
model/trainer.py
MIT
22,626
3a6aaa716c72e4f20f226fe2bcb68522b0b3b3fd
Python
py
import os, sys import time from torch import optim import random as rand import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from PIL import Image import torch.utils.data as data import torchvision as tv import torchvision.transforms as tvt import math from imsitu impo...
deepinspect/imsitu/baseline_crf_deepinspect.py
MIT
52,767
347ea2261b2fcc2ffea930d45032ca1eb9e60059
Python
py
#!/usr/bin/env python3 # # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang) # # See ../../../LICENSE for clarification regarding multiple authors # # 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...
k2/python/tests/nbest_test.py
Apache-2.0
3,565
3a6ae0e81e6ae88bf5ac120b44354ef1f3fb1742
Python
py
import os import shutil import time import numpy as np import torch import torch.nn as nn from torch.nn import CrossEntropyLoss from torch.optim import SGD, Optimizer from torch.optim.lr_scheduler import StepLR from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from architectures import ge...
code/train_utils.py
MIT
7,662
3a6ae27e2aae2e9b83ee06789d6099091da33b86
Python
py
import torch from cogdl.tasks import build_task from cogdl.datasets import build_dataset from cogdl.models import build_model from cogdl.utils import build_args_from_dict def get_default_args(): default_dict = {'hidden_size': 16, 'num_shuffle': 1, 'cpu': True, ...
tests/tasks/test_unsupervised_node_classification.py
MIT
7,927
343b91dc06923e51b9c4daa53704de335d26f245
Python
py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import logging import pytest import torch from pyro.ops.indexing import Vindex from tests.common import xfail_param # put all funsor-related imports here, so test collection works without funsor try: import funsor import py...
tests/contrib/funsor/test_valid_models_plate.py
Apache-2.0
7,546
4b2f75d844428eee2ac0f68e95798db279f62752
Python
py
""" Create train, valid, main iterators for CIFAR-10 [1]. Easily extended to MNIST, CIFAR-100 and Imagenet. [1]: https://discuss.pytorch.org/t/feedback-on-pytorch-for-kaggle-competitions/2252/4 """ import os import numpy as np # from utils import plot_images from torchvision import datasets from torchvision import tra...
train/dataset/cifar10_dataloader.py
MIT
9,434
3a6b1214e8b819f73ecbb2ffb3304ff1b4e5deaf
Python
py
import sys import torch.nn as nn import time import numpy as np import torch import copy import ltprg.data.feature from torch.autograd import Variable from torch.optim import Adam from mung.feature import MultiviewDataSet, Symbol from mung.data import Partition from mung.torch_ext.eval import Loss from mung.torch_ext.l...
src/test/py/ltprg/game/shapeGrids/model/learn_seqS.py
MIT
3,475
106f35133da694dd62ae0ea247fe8977d2e90257
Python
py
from __future__ import print_function import torch from retinaface.data import cfg_mnet from retinaface.models.retinaface import RetinaFace def check_keys(model, pretrained_state_dict): ckpt_keys = set(pretrained_state_dict.keys()) model_keys = set(model.state_dict().keys()) used_pretrained_keys = model...
retinaface/loader.py
Apache-2.0
1,769
ff8b0ebac1c982e127ef2f85289e55a82cf9ea54
Python
py
import os import sys BASE_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__))))) sys.path.append(BASE_DIR) from tools.path import ILSVRC2012_path from simpleAICV.distillation.distillmodel import KDModel from simpleAICV.distillation import losses from simpleA...
distillation_training/imagenet/resnet_34_kd_18/train_config.py
MIT
3,293
3a6b3bc1854bdf561f80e81f50a4169ac6b4cef8
Python
py
import numpy as np import torch.utils.data as data import torchvision.datasets as datasets from collections import defaultdict class LabelNoise(data.Dataset): def __init__(self, dataset, k, n_labels, p=1): assert n_labels % k == 0 self.dataset = dataset self.k = k # random label...
smooth-topk/src/data/utils.py
MIT
3,901
5ec6ec65cbd399da0eaa7e19d3361a7c647d022a
Python
py
import json from data import load_data, get_epoch import model import torch from torch import nn import os from random import shuffle import argparse import logging logger = logging.getLogger(__name__) # pylint: disable=invalid-name logger.setLevel(logging.INFO) def train_epoch(model, data, config): model.train(...
train_model.py
MIT
4,608
e9822a29e6d122d16eafd07450245753dd8db735
Python
py
""" @author: JiXuan Xu, Jun Wang @date: 20201015 @contact: jun21wangustc@gmail.com """ import numpy as np import torch from App.exts.face_sdk.api_usage.logFile import logger from App.exts.face_sdk.core.model_handler.BaseModelHandler import BaseModelHandler from App.exts.face_sdk.utils.BuzException import ...
App/exts/face_sdk/core/model_handler/face_recognition/FaceRecModelHandler.py
MIT
2,384
fdaebca5637d55377fab3ebf06a0cfa874426ddb
Python
py
import torch import numpy as np import time import pdb from rlkit.torch.policies.tanh_gaussian_policy import TanhGaussianPolicy from rlkit.torch.policies.make_deterministic import MakeDeterministic from rlkit.torch.policies.gumbel_softmax_policy import GumbelSoftmaxMlpPolicy from rlkit.policies.argmax import ArgmaxDisc...
tests/RoboSumo/visualize_against.py
MIT
3,227
ff0ce03e68af3e8652470aa8ca279bf760d01930
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from typing import TYPE_CHECKING, Optional, Tuple, Union import torch from .knn import knn_points if TYPE_CHECKING: from pytorch3d.structures import Pointclouds def wmean( x: torch.Tensor, weight: Optional[torch.Tensor] = None, ...
pytorch3d/ops/utils.py
BSD-3-Clause
5,119
3a6ba4a98e9db70b2f44c7be28e3f298cce9f225
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Misc functions, including distributed helpers. Mostly copy-paste from torchvision references. """ import os import subprocess import time from collections import defaultdict, deque import datetime import pickle from typing import Optional, List...
util/misc.py
Apache-2.0
13,420
45d055d919315eef682a856ab1888a64f316815f
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import sys def read_files_batch(file_list): """Reads the provided files in batches""" batch = [] # Keep batch for each file fd_list = [] # File descriptor list exit = False # Flag used for quitting the program in case of error try:...
tools/create_vocabulary.py
MIT
2,986
3a6bc4a889be57dc759f72e9d51f09434fde8149
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Define the Gaussian Mixture Regression (GMR) value function approximators. Define the GMR value that can be used. """ import numpy as np import torch from pyrobolearn.approximators.gmr import GMRApproximator from pyrobolearn.values.value import ParametrizedValue, Para...
pyrobolearn/values/gmr.py
Apache-2.0
6,171
a92b09cb097bce09afd9723c8dca3a475897cb75
Python
py
# Copyright 2021, Crepaldi Michele. # # Developed as a thesis project at the TORSEC research group of the Polytechnic of Turin (Italy) under the supervision # of professor Antonio Lioy and engineer Andrea Atzeni and with the support of engineer Andrea Marcelli. # # Licensed under the Apache License, Version 2.0 (the "L...
src/Model/nets/ALOHA_net.py
Apache-2.0
16,157
3a6bfb06a64ef15ed36a79540b7be220deb1410d
Python
py
import torch from torchvision import datasets, transforms import torch.utils.data.sampler as sampler import torch.utils.data as data import numpy as np import argparse import random import os from custom_datasets import * import model import vgg import mnist_net from solver import Solver from utils import * import a...
main.py
BSD-2-Clause
5,955
5f6c8645914ed06777e38aac0d2ae12130365a30
Python
py
"""Module Description. - Author: Jongkuk Lim - Contact: lim.jeikei@gmail.com """ import os from typing import List, Union import numpy as np import torch from torch import nn from kindle import Model from kindle.generator import GeneratorAbstract from kindle.torch_utils import Activation, autopad, count_model_params...
tests/test_custom_module.py
MIT
2,552
3a6c1e9927ef3ebaa4d627a5161e13a3cb794622
Python
py
import argparse import os import numpy as np import torch.nn as nn from tqdm import tqdm from mypath import Path from dataloaders import make_data_loader from modeling.sync_batchnorm.replicate import patch_replication_callback # TODO: remove all wildcards from modeling.deeplab import * from modeling.fpn import FPN fr...
lane_train.py
MIT
18,369
3a6c2e102d2aa773ba85108eef1e10e22ecbec74
Python
py
"""Gaussian-based Convolutional Restricted Boltzmann Machine. """ import time from typing import Optional, Tuple import torch import torch.nn.functional as F from torch.utils.data import DataLoader from tqdm import tqdm import learnergy.utils.constants as c import learnergy.utils.exception as e from lea...
learnergy/models/gaussian/gaussian_conv_rbm.py
MIT
7,262
3a6c42c9f877a7a38598e8025b10958641c25dfb
Python
py
import sys import torchpruner import torchpruner.model_tools as model_tools import torchvision import torch import torch.nn as nn # model creator, the input shape, prune_modules models = { # "faster_rcnn": (torchvision.models.detection.fasterrcnn_resnet50_fpn,(1,3,300,400), # [('self.backbone.body.l...
examples/support_model/detection.py
MIT
1,438
707dae08c965ab0fb581a971d74b368852c037ae
Python
py
# -*- coding: utf-8 -*- # @Date : 2/16/21 # @Author : Xinyu Gong (xinyu.gong@utexas.edu) # @Link : None # @Version : 0.0 import torch import torch.nn as nn from .modules import DisBlock, GenBlock, OptimizedDisBlock class Generator(nn.Module): def __init__(self, args, activation=nn.ReLU()): super(...
GAN/models/sngan_small_128.py
MIT
3,771
3a6c6331d64d1a20d5f4665ec2c887879291e164
Python
py
# coding: utf-8 import gym import torch.utils.data as data from dynamics import * from controller import * from utils import * from quanser_robots.common import GentlyTerminating import time def test(mpc, model): reward_episodes = [] for i in range(data_fac.n_mpc_episodes): data_tmp = [] label...
Quanser Robot/MPC/MPC-ball_balancer/test.py
MIT
2,023
3a6c6fb39881f0cad53ca19b6d734638784a3551
Python
py
import unidecode import torch from torch.autograd import Variable from collections import Counter import observations import os import pickle cuda = torch.cuda.is_available() def data_generator(args): file, testfile, valfile = getattr(observations, args.dataset)('data/') file_len = len(file) valfile_len...
MCRM/char_ptb/utils.py
MIT
2,995
106c8b1b2fd2179df5b4127dcb0bdd09e773056a
Python
py
import torch from . import util def cosine_similarity(a, b, normalize=True, inplace=False): """ Compute batched cosine similarity between 'a' and 'b' a: torch.Tensor, shape : [l, d_vector, m] b: torch.Tensor, shape : [l, d_vector, n] normalize: bool, default : True if True, a and b will be norm...
torchpq/metric.py
MIT
3,503
03e601263e7c15a2ede3c8a06c141e2fd553f825
Python
py
"""Data transformation test. This test contains the following test: - Transformations could be ``None``, ``yaml``, ``json`` or ``dict``. - When it is ``None``, the script loads the default transforms - When it is ``yaml``, ``json`` or ``dict``, `albumentations` package deserializes the transformati...
tests/pre_merge/pre_processing/transforms/test_transforms.py
Apache-2.0
2,642
3a6c954435353d0c4ecf95c02dcb5a92fdb480fe
Python
py
import numpy as np import wandb from torch.utils.tensorboard import SummaryWriter import omegaconf class Writer(SummaryWriter): def __init__(self, cfg, logdir): self.cfg = cfg if cfg.log.use_tensorboard: self.tensorboard = SummaryWriter(logdir) if cfg.log.use_wandb: ...
utils/writer.py
Apache-2.0
933
d7f17136e4f9fbae4ce910f7214ba6d8a9d6a436
Python
py
from __future__ import print_function, absolute_import import time from collections import OrderedDict import pdb import torch import numpy as np from .evaluation_metrics import cmc, mean_ap, map_cmc from .utils.meters import AverageMeter from torch.autograd import Variable from .utils import to_torch from .utils im...
reid/evaluators.py
Apache-2.0
12,347
5f280a42edc23de91b3193956546da8b40be94ae
Python
py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
torchmetrics/retrieval/recall.py
Apache-2.0
3,405
3a6cd0cc1b7b19f28f40a4e270ddcbcf3800127c
Python
py
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. """ Train and eval functions used in main.py """ import math import sys from typing import Iterable, Optional import torch from timm.data import Mixup from timm.utils import accuracy, ModelEma from losses import DistillationLoss import utils def t...
engine.py
Apache-2.0
3,518
a90f1f1a361800dbc989e78ca047df76568dae50
Python
py
from io import BytesIO import requests import torch from PIL import Image from torchvision import models from torchvision import transforms class PythonPredictor: def __init__(self, config): self.device = "cuda" if torch.cuda.is_available() else "cpu" print(f"using device: {self.device}") ...
test/apis/pytorch/object-detector/predictor.py
Apache-2.0
1,629
ff57e6c4e48386d49e422cc4b0e78d8807385c99
Python
py
import torch as tr class Hyperparams: """ Base Hyperparams class. It uses base version of bcgan with 1D x space and z space """ dtype = float # Trainer parameters: n_iterations = 10000 show_visual_while_training = True train_generator_adv = True train_autoencoder = True ...
src/hyperparams/toy_gaussians.py
MIT
1,466
3a6d3d0fac946a28c41345fbeaffaa3784b7a3fa
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Any, Dict, Optional, Type, Union import torch from accelerators.pytorch.lib.accelerator_lowering import ( lower_modules_to_accelerator, lower_split_model_to_accelerator, ) from accelerators.pytorc...
pytext/task/new_task.py
BSD-3-Clause
19,202
3a6d4dff86f7f4cdb8aab11af8a265acd5995c12
Python
py
""" GraN-DAG Copyright © 2019 Sébastien Lachapelle, Philippe Brouillard, Tristan Deleu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights...
dcdi/dag_optim.py
MIT
5,015
03fc4b0de3d934899e1183040b495df02389a657
Python
py
import os import numpy as np from torch.utils.data import Dataset from utils import load_feature, tokenize class TACOS(Dataset): def __init__(self, feature_path, data, word2vec, is_training=True): self.data = data self.feature_path = feature_path self.is_training = is_training sel...
code/datasets/TACOS.py
MIT
2,593
3a6d94dbc4dae7f0f0e528b2a3c55884a01ff0cf
Python
py
# -*- coding: utf-8 -*- """ Created on Wed Oct 30 10:07:33 2019 @author: Yang Xu """ import cv2 import numpy as np import pandas as pd import NaiveDE ##neural net import torch import torch.nn.functional as F import umap import scipy.stats from scipy.special import softmax from sklearn.cluster i...
CoSTA/MERFISH_by_CoSTA.py
MIT
11,492
3a6d9ecc05194ffb399afc605c378dafa25a2f4a
Python
py
import torch from synthesizer import audio from synthesizer.hparams import hparams from synthesizer.models.tacotron import Tacotron from synthesizer.utils.symbols import symbols from synthesizer.utils.text import text_to_sequence from vocoder.display import simple_table from pathlib import Path from typing import Union...
synthesizer/inference.py
MIT
7,691
3a6dc6c89702b44dccf66e7e8d0fbca9590dae8a
Python
py
import os from pathlib import Path import torch import torch.nn as nn import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torchvision import datasets, models from torchvision.transforms import Compose, Normalize, Pad, RandomCrop, RandomHorizontalFlip, ToTensor import ignite.distributed as idi...
assets/tldr/teaser.py
BSD-3-Clause
6,616
3a6dcd3fa58324414a618542beea62c26a553560
Python
py
# Training DNC import sys import time import torch import random import numpy as np # torch.autograd.set_detect_anomaly(True) # Setting Anomaly Detection True for finding bad operations def random_seed(): seed = int(time.time()*10000000) random.seed(seed) np.random.seed(int(seed/10000000)) # NumPy s...
train.py
MIT
1,259
3a6de186c72e63907412fb086b2a8060d61daf7a
Python
py
import sys sys.path.append('..') from utils import * import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim # from torchvision import datasets, transforms class OthelloNNet(nn.Module): def __init__(self, game, args): # game params self.board_...
trading/pytorch/TradingNNet.py
MIT
3,913
3449179508f88166f0c467539ab16120b4683c8c
Python
py
# # Copyright 2016 The BigDL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
python/nano/src/bigdl/nano/utils/inference/pytorch/model.py
Apache-2.0
1,954
3a6e28a902ec2969e8388197d4254eb90a98c2ba
Python
py
import torch from torch.utils import data from torchvision import datasets, transforms import numpy as np import os from dataset_wrapper import DatasetWrapper def get_loader(dataset_name, data_dir, batch_size, mode, shuffle, num_workers=1): data_set = None data_dir = os.path.join(data_dir, dataset_name.lower...
others/loader.py
MIT
5,253
3a6e33ef5e771661dfb3049eb2aaa81d77fc9ec8
Python
py
from enum import Enum __all__ = ("DataType", "Algorithm", "Dataset", "VariationalDistribution") class DataType(Enum): single = 1 float32 = 2 double = 11 float64 = 12 def to_torch_dtype(self): import torch if self.value < 10: return torch.float32 else: ...
benchmark/benchmark_utils.py
MIT
1,691
fcf200fb280ad4017aa711a1017fee2eb5904acf
Python
py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/config.ipynb (unless otherwise specified). __all__ = ['create_path', 'DATA_PATH', 'MODEL_PATH', 'OUTPUT_PATH', 'LR', 'TRAIN_BATCH_SIZE', 'VALID_BATCH_SIZE', 'NUM_EPOCHS', 'MAX_SEQ_LEN', 'MODEL_NAME', 'DEVICE', 'TOKENIZER'] # Cell import os import torch import...
Bert4NER/config.py
Apache-2.0
1,020
3a6e934f5f80bd807729620a819f11fc439cf575
Python
py
import argparse import time import numpy as np import torch import torch.nn.functional as F import dgl from dgl.data import CoraGraphDataset, CiteseerGraphDataset, PubmedGraphDataset from gcn import GCN #from gcn_mp import GCN #from gcn_spmv import GCN def evaluate(model, features, labels, mask): model.eval() ...
examples/pytorch/gcn_bit_random/evaluate.py
Apache-2.0
3,454
1e7313f14c30f04088908538ee569e86dda2ec4b
Python
py
#!/usr/bin/env python3 """ part1.py UNSW COMP9444 Neural Networks and Deep Learning ONLY COMPLETE METHODS AND CLASSES MARKED "TODO". DO NOT MODIFY IMPORTS. DO NOT ADD EXTRA FUNCTIONS. DO NOT MODIFY EXISTING FUNCTION SIGNATURES. DO NOT IMPORT ADDITIONAL LIBRARIES. DOING SO MAY CAUSE YOUR CODE TO FAIL AUTOMATED TESTIN...
hw2/part1.py
MIT
2,629
5e212b6ff4c6a7873783cef2ec2789c2281b7c6f
Python
py
import os, sys import numpy as np import json import random import time import torch import torch.nn as nn import torch.nn.functional as F from tqdm import tqdm, trange import scipy.io import matplotlib.pyplot as plt from run_netf_helpers import * from MLP import * from load_nlos import * from math import ceil device...
run_netf.py
MIT
33,457
3a6f00d27af4d2b64694c7549f39178744e9fff1
Python
py
import torch import argparse from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.pyplot as plt from IPython import embed import numpy as np from matplotlib.patches import Circle import matplotlib.cm as cmap class Cursor(object): def __init__(self, sample_ax, draw_ax): self.sample_ax =...
scripts/inspect_h36m_fusion.py
MIT
2,873
3a6f01575e02d27027d7a7be0d3b5201dbe3685c
Python
py
from typing import Dict, Union, Callable, List, Optional from pathlib import Path import subprocess import numpy as np import pandas as pd import random import torch import yaml import json import shutil from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.linear_model import Logist...
poison.py
BSD-3-Clause
37,584
b273d07be67763474ce0e955fb86a8ce1167a0a0
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from sqlnet.model.modules.word_embedding import WordEmbedding from sqlnet.model.modules.aggregator_predict import AggPredictor from sqlnet.model.modules.selection_predict import SelPredictor from sq...
sqlnet1.py
BSD-3-Clause
18,386
343174f20c5178e793daf3dddbabac99ef1d6aa2
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from UnarySim.sw.kernel.linear import UnaryLinear from UnarySim.sw.kernel.relu import UnaryReLU class NN_SC_Weight_Clipper(object): """ This is a clipper for weights and bias of neural networks """ def __init__(self, frequency=1, mode="...
sw/kernel/nn_utils.py
MIT
7,361
3a6f231f9c9f77ccf647e2f77efea9c44c8a79cf
Python
py
import os import numpy as np from PIL import Image from PIL import ImageFile import torch from torch.utils import data ImageFile.LOAD_TRUNCATED_IMAGES = True Image.MAX_IMAGE_PIXELS = None def random_crop(img): w, h = img.size if w > h: r = w/h*512 img = img.resize((int(r), 512)) w_in...
data.py
MIT
1,996
3a6f2af15bd2659e796efb70e61129727f9af698
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from model_utils.resnet import Resnet18 # from modules.bn import InPlaceABNSync as BatchNorm2d class ConvBNReLU(nn.Module): def __init__(self, in_chan, out_chan, ks=3, stride=1, padding=1, *args, **kwargs): super(ConvBNReLU, self).__init_...
seg_mask_modifs/model_utils/model_celebmask.py
MIT
10,873
707870763e5a9f5e863a3673e71e452a1084c103
Python
py
import torch import logging import torchvision import torch.nn as nn import torch.nn.functional as F from Utils.constants import GEM class GeMHeadNet(nn.Module): ''' module for the GeM network ''' def __init__(self, pool, whiten): super(GeMHeadNet, self).__init__() self.pool = pool se...
src/Networks/GeMNet.py
MIT
1,382
3a6f549102358a3ffedddeaf68ab239b8a179814
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import warnings from functools import partial from functools import wraps import numpy import torch from torch._C import ListType, OptionalType ...
deeploader/x2onnx/converters/onnx_torch/symbolic_opset9.py
Apache-2.0
82,388
12ee9b128df90e0eae8f56a8a4798cc846a9f284
Python
py
import colorsys import os import cv2 import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn as nn import tqdm from PIL import Image, ImageDraw, ImageFont from scipy.io import loadmat from torch.autograd import Variable from nets.retinaface import RetinaFace from retinaface import Retinaf...
evaluation.py
MIT
12,929
5e24df77f9e897eab1511d2444e0f7fc976ba4b0
Python
py
import abc import copy import torch import numpy as np from rl_agents.agents.budgeted_ftq.greedy_policy import optimal_mixture, pareto_frontier_at from rl_agents.agents.common.utils import sample_simplex class BudgetedPolicy: __metaclass__ = abc.ABCMeta @abc.abstractmethod def execute(self, state, beta)...
rl_agents/agents/budgeted_ftq/policies.py
MIT
2,990
3a6f59dd42ee567aaf70b2026058a750ad51b7b3
Python
py
import time import logging def timeit(f): """ Decorator to time Any Function """ def timed(*args, **kwargs): start_time = time.time() result = f(*args, **kwargs) end_time = time.time() seconds = end_time - start_time logging.getLogger("Timer").info(" [-] %s : %2.5f s...
utils/misc.py
MIT
1,393
d7a5cd00940e7f3d9410f008ac76fb4bdf7477ae
Python
py
from easydict import EasyDict import torch import os config = EasyDict() config.gpu = "1" # dataloader jobs number config.num_workers = 12 # batch_size config.batch_size = 2 # training epoch number config.max_epoch = 200 config.start_epoch = 0 # learning rate config.lr = 1e-4 # using GPU config.cuda = True con...
util/config.py
MIT
1,186
3a6f8ad3748f7dd532858c2b59e251bea9d1bf6e
Python
py
from typing import Tuple import torch from torch import nn from models.vae import BaseVAE class LargeVAESmallKernels(BaseVAE): def __init__(self, model_parameters: dict, use_kld_warmup: bool, kld_weight: float = 1.0): super().__init__(model_parameters, use_kld_warmup, kld_weight) self.conv_1 =...
models/vae/large_vae_small_kernel.py
MIT
8,834
343d4c175db1a609048f96830a3a79dcb3f4a943
Python
py
import torch from torch import nn import torch.nn.functional as F import pj3_emotion_car.config as conf def optimize_step(model, input_tensors, category_tensor, optimizer): model.zero_grad() model.train() output = model(input_tensors) loss = F.cross_entropy(output, category_tensor) optimizer.zero_...
pj3_emotion_car/model.py
Apache-2.0
6,703
3a6fbac38d56ebc92998cd05c3c92509c39718f9
Python
py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
tests/accelerators/test_accelerator_connector.py
Apache-2.0
30,569
5f5d3a3877fa72f3a6a956c0668e803ae643859d
Python
py
import os import pytest import torch import tests.models.utils as tutils from pytorch_lightning import Trainer from pytorch_lightning.callbacks import ( ModelCheckpoint, ) from pytorch_lightning.core import memory from tests.models import ( LightningTestModel, ) from pytorch_lightning.trainer.distrib_parts im...
tests/test_gpu_models.py
Apache-2.0
13,427
5fd37870eee2327652e3c7ac7179db776dd3a7a1
Python
py
import torch from torch import nn from einops.layers.torch import Reduce from .utils import pair class PreNormResidual(nn.Module): def __init__(self, dim, fn): super().__init__() self.fn = fn self.norm = nn.LayerNorm(dim) def forward(self, x): return self.fn(self.norm(x)) + x ...
models_pytorch/s2_mlp_v2.py
MIT
4,532
3a704bb4e70e0cfe959de111d70ba30df4c3df1b
Python
py
import math import numpy as np import torch.nn as nn from torch.nn.modules.utils import _pair from .quantizable_ops import ( QuantizableConv2d, QuantizableLinear ) from utils.config import FLAGS class DepthwiseSeparableConv(nn.Module): def __init__(self, inp, outp, stride, input_size): super(Dep...
quantization/lbq-v2/models/q_mobilenet_v1.py
MIT
3,852
7cd7c1ba444332ea710834f2bd6efd1821214318
Python
py
import logging import math from typing import Any, Dict, List, Tuple import torch import torch.nn.functional as F from overrides import overrides from allennlp.data import TextFieldTensors, Vocabulary from allennlp.models.model import Model from allennlp.modules.token_embedders import Embedding from allennlp.modules ...
allennlp/models/coreference_resolution/coref.py
Apache-2.0
30,906
4b8cc0dead0f785e4fd61a6bc240b6b4a03c0e00
Python
py