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 cv2 import os import numpy as np import torch from torch.utils.data import Dataset class CULane(Dataset): def __init__(self, path, image_set, transforms=None): super(CULane, self).__init__() assert image_set in ('train', 'val', 'test'), "image_set is not valid!" self.data_dir_path ...
src/dataset/CULane.py
MIT
3,021
fef9cb8843b79e121daec739ce9d3a7046158005
Python
py
import torch from torch.utils.data import Dataset,DataLoader from torch.nn import Module import torch.nn as nn from torch.optim import SGD from torch.optim.lr_scheduler import StepLR """ 配置: a=1层conv,b个feature,c个class """ class FakeData(Dataset): def __init__(self, klass_num, dup=100): super(FakeData,self...
gd_and_cnn1.py
MIT
2,435
fef9d9b295708ff00cdedeeeb31504de6ab1ab8d
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from skimage.measure import compare_ssim import torch from torch.autograd import Variable from lpips import dist_model class PerceptualLoss(torch.nn.Module): def __init__(self, model='...
lpips/__init__.py
BSD-2-Clause
5,760
fef9e161bd6a8b983306edbc57607883174ee671
Python
py
""" Adapted from https://github.com/Jackson-Kang/Pytorch-VAE-tutorial/blob/master/01_Variational_AutoEncoder.ipynb A simple implementation of Gaussian MLP Encoder and Decoder trained on MNIST """ import logging import os import hydra import torch import torch.nn as nn import torchvision.transforms as transforms from ...
08_reproduceability/vae_solution/vae_mnist.py
Apache-2.0
3,561
70a6d70c7afa73a8f74234f9b6c5dfc210ec0ed8
Python
py
import torch import itertools from util.image_pool import ImagePool from .base_model import BaseModel from . import networks import torch.nn.functional as F class PairedRevGANModel(BaseModel): ''' Paired 2D-RevGAN model ''' def name(self): return 'PairedRevGANModel' @staticmethod def modify_c...
models/paired_revgan_model.py
BSD-3-Clause
9,327
4bbbd6e73f052620f81685bd0b87c71ee29d8ead
Python
py
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import pandas as pd from tqdm import tqdm import os from io import open import hashlib import argparse from layers import RNNModel, AWDLSTMEncoder, DropoutLinearDecoder from utils import count_parameters,...
generate.py
MIT
4,652
4b3a62b833c7abe2b6830d36b277ed91d552be27
Python
py
from typing import Dict from torch.utils.data import DataLoader import albumentations as A from albumentations.pytorch import ToTensorV2 from .coco import COCODataset from .voc import VOCDataset from .crowdhuman import CrowdHumanDataset from .mot import MOTTrackingDataset from .kitti import KITTITrackingDataset from ...
centernet_lightning/datasets/builder.py
MIT
2,238
12ba314fc8642299bee8d90db2430085f9351486
Python
py
"""A collection of fully-specified model interfaces.""" import abc import logging import torch as th from . import ModelInterface from .utils import get_logger, plot_grad_flow LOG = get_logger(__name__) # HAS_AMP = False # if th.cuda.is_available(): # try: # HAS_AMP = True # from apex import ...
ttools/interfaces.py
MIT
15,822
a941ab91c0d4fb46e3948d0b6f8910d224ffad5d
Python
py
import torch import torch.nn.functional as F from torch_geometric.transforms import SIGN from torch.utils.data import DataLoader import torch from torch_sparse import SparseTensor from Precomputing.base import PrecomputingBase class SGC(PrecomputingBase): def __init__(self, args, data, train_idx): super(...
Precomputing/SGC.py
MIT
562
fefa212e51763157dca79377e40d005274c53ad6
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from DetectionHub.structures.bounding_box import BoxList from .roi_mask_feature_extractors import make_roi_mask_feature_extractor from .roi_mask_predictors import make_roi_mask_predictor from .inference import make_roi_mask_post_proc...
DetectionHub/modeling/roi_heads/mask_head/mask_head.py
MIT
3,101
b232d305a6e90c5dde9f01b05d72ac4b97e19c66
Python
py
from typing import Dict, List, Any import torch import torch.nn.functional as F import numpy as np from allennlp.data import Vocabulary from allennlp.data.dataset_readers.dataset_utils import bio_tags_to_spans from allennlp.models import Model from allennlp.modules import TextFieldEmbedder, Seq2SeqEncoder, TimeDistrib...
eventx/models/eventx_model.py
MIT
14,110
10f7f587bd83a342c5419976a2619cff75ec5ffe
Python
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 import shake class BasicBlock(nn.Module): ...
cifar10/models/resnet_flymake.py
MIT
4,030
b232a6dca2d8e906f37b01ff5c94119b36a0067b
Python
py
import torch from catalyst.registry import Model @Model class Model(torch.nn.Module): """ Your model """ def __init__(self, **kwargs): """ Model init. Args: **kwargs: model params """ super().__init__() def forward(self, x): """ ...
examples/_empty/src/model.py
Apache-2.0
770
fefa640bbae989353318604493bc289d7ad79fe1
Python
py
""" Evaluation with AutoAttack. """ import json import time import argparse import shutil import os import numpy as np import pandas as pd import torch import torch.nn as nn from autoattack import AutoAttack from core.data import get_data_info from core.data import load_data from core.models import create_mode...
eval-aa.py
MIT
2,737
10bf8a50daf873e1ff217c3557127c8c2f7821c4
Python
py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2018 Kyoto University (Hirofumi Inaguma) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Utility functions for training.""" import codecs import functools import logging import numpy as np import os import time import torch import yaml logge...
neural_sp/bin/train_utils.py
Apache-2.0
5,383
fefa8446008472acece0dd6dba0070e897adc214
Python
py
import unittest import json import os import random import responses import torchvision from lightly.api import routes class TestGetPresignedURL(unittest.TestCase): def setup(self, n_data=1000, psuccess=1.): self.filename = 'filename' self.dataset_id = 'XYZ' self.sample_id = 'ABC' ...
tests/api/test_GetPresignedURL.py
MIT
3,296
fefa8aa6bbcecbb3773d2851abd0220b0d3a382d
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...
tests/test_vote_ensembled.py
Apache-2.0
3,094
e94213733f184533b4fdac25007e063b4ed83a6d
Python
py
# example of calculating the frechet inception distance import os import json import argparse import numpy as np from PIL import Image from tqdm import tqdm import torch from torchvision import models, transforms import torch.nn.functional as F from skimage.measure import compare_ssim as ssim import torch.nn...
eval_scripts/eval_disc_dataset.py
MIT
7,275
28c8694408befca3dcf717bf0f9336d30b1a6ec2
Python
py
"""Dilated ResNet""" import math import torch import torch.utils.model_zoo as model_zoo import torch.nn as nn from ..models.model_store import get_model_file __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution...
gluoncvth/models/resnet.py
MIT
9,902
fefad7f15174ec3fa49ea49f9fb2612fd721da19
Python
py
import argparse import logging import random import numpy as np import pytorch_lightning as pl import torch import wandb from envs import network_flow_env_builder from pytorch_lightning.loggers import WandbLogger # Default big-ish from agents.pytorch_agents import CustomerOnehotDQN from experiments_v2.base_ptl_agent_...
python/src/experiments_seminar_2/agents/one_hot_dqn_v2.py
MIT
4,990
6528adb11ba38db85a29640f4e1e2039aa1c9650
Python
py
import json import logging import numpy as np import torch def xavier(net): def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1 and hasattr(m, 'weight'): torch.nn.init.xavier_uniform_(m.weight.data, gain=1.) if m.bias is not None: m.bias.data.zero_() elif classname....
network/initializer.py
MIT
7,889
e97a53cd1982e93eaa38c068806cb7b26cf1501a
Python
py
import numpy as np import torch class ReplayBuffer: """ Implement replay buffer. """ def __init__(self, max_size): """ :param max_size: the maximum number of experiences stored in the replay buffer. int. """ self._max_size = max_size self._data = { "...
utils.py
MIT
7,156
fefb1524e5fb69dce2d79dccdc29be336b48a91d
Python
py
import os import torch def save_checkpoint(epoch, step, model, optimizer, save_path): """ Save checkpoint pickle file with model weights and other experimental settings Args: epoch (Int): Current epoch when model is being saved step (Int): Mini-batch iteration count when mod...
checkpoint.py
MIT
1,187
455ef69ce183f13aa8381fd9e2e1d465124d8da8
Python
py
import logging from typing import Any, Dict, Iterable, List, Tuple import difflib import sqlparse from overrides import overrides import torch from allennlp.common.util import pad_sequence_to_length from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import Attention, Se...
allennlp_semparse/models/atis/atis_semantic_parser.py
Apache-2.0
27,962
fefb4d2fe8dcbe62d61b0f34433b9d2c52bc0b5c
Python
py
import logging from abc import abstractmethod from typing import List, Dict, Iterable, Tuple, Union import networkx as nx from Bio import SeqIO from openomics.database.annotation import * from openomics.database.base import Database from openomics.database.sequence import SequenceDatabase class Interactions(Database...
openomics/database/interaction.py
MIT
45,498
5e3009be81b5d1a4598e509280ba3ad502ad1e87
Python
py
import torch.utils.data as data import torch import torchvision.transforms as transforms import numpy as np from PIL import Image import os class frame_dataset(data.Dataset): def __init__(self, args): self.frame_dir = args.frame_dir self.frame_addr = np.asarray([os.path.join(self.frame_dir...
data/frame_dataset.py
MIT
1,000
1e4355c8017218d7a81df500df6c043f56677053
Python
py
import json import torch from PIL import Image from torchvision import transforms import io import numpy as np # defines the model def model_fn(model_dir): model_path = f'{model_dir}/infer-pytorch-ic-resnet50.pt' model = torch.load(model_path) model.eval() return model def input_fn(request_body, req...
right_size_your_sagemaker_endpoints/inference.py
MIT-0
1,364
34083b76ffe518086da3700e03b5b4168a6bf12e
Python
py
import torch import torch.nn as nn import torch.nn.functional as F class L2Norm(nn.Module): def __init__(self, n_channels, scale=1.0): super(L2Norm, self).__init__() self.n_channels = n_channels self.scale = scale self.eps = 1e-10 self.weight = nn.Parameter(torch.Tensor(sel...
SFD/net_s3fd.py
MIT
5,845
fefb980d843a5fe2169bd3152da7f373c1666af8
Python
py
import math, torch import torch.nn as nn from ..initialization import initialize_resnet from ..SharedUtils import additive_func from .SoftSelect import select2withP, ChannelWiseInter from .SoftSelect import linear_forward from .SoftSelect import get_width_choices as get_choices def conv_forward(inp...
zero_cost_utils/models/shape_searchs/SearchSimResNet_width.py
MIT
14,164
fefba16a121d446dda25378b08485eb17f5e1a83
Python
py
from pathlib import Path import json import scipy.sparse as sp import torch from ogb.nodeproppred import PygNodePropPredDataset import collections from copy import deepcopy import logging import warnings from typing import Any, Dict, Sequence, Union from rgnn_at_scale.data import split import numpy as np from sacred im...
examples/Graph_Adversarial_Learning/Targeted/Poisoning/PyTorch/sga_experiment_rgnn_scale_models.py
MIT
16,036
dfbe679941c6491ba1d582746bd856db775159fa
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...
tests/test_handler_stats.py
Apache-2.0
5,803
248be9f3290cbcdd14ab5d59581a975b744b2a2d
Python
py
#!/usr/bin/python # _____________________________________________________________________________ # ---------------- # import libraries # ---------------- # standard libraries # ----- import os import math import torch # configuration module # ----- import config # custom functions # ----- def update_target_net(n...
utils/general.py
MIT
1,746
fefbce8074a394b8a3973f0f26165706eb49720e
Python
py
""" This file contains the definition of the SMPL model It is adapted from opensource project GraphCMR (https://github.com/nkolot/GraphCMR/) """ from __future__ import division import torch import torch.nn as nn import numpy as np import scipy.sparse try: import cPickle as pickle except ImportError: import pi...
metro/modeling/_smpl.py
MIT
10,823
e98bd4ade27f3d1c07b85307caf59d16f8044ce4
Python
py
from GNN.globals import * import math from GNN.utils import * from GNN.graph_samplers import * from GNN.norm_aggr import * import torch import scipy.sparse as sp import scipy import numpy as np import time import hashlib def _coo_scipy2torch(adj, coalesce=True, use_cuda=False): """ convert a sc...
GNN/pytorch_version/minibatch.py
MIT
10,957
fefc0aa9029ace0b060e909cd6f4adfb0a555d42
Python
py
import argparse import json import time import sys import torch # import test import test_mapgiou # from models_diou_arcface import * # from models_diou import * from models_slim import * # from models import * from utils.datasets import JointDataset, collate_fn from utils.utils import * from utils.lo...
train_exp_sparsity.py
MIT
13,361
4b4f16d2e3802d77d2f8d6f6b25c544506d74fef
Python
py
from pathlib import Path from typing import List, Union import torch.nn.utils.rnn as rnn class Editor: @staticmethod def get_lines( text_corpus_paths: List[Path], ): lines = list() for text_corpus_path in text_corpus_paths: with open(text_corpus_path) as f: ...
trext/utils/editor.py
MIT
2,667
34814bd976f8a8a41954cc7ec11a5957da2d20c6
Python
py
import argparse import yaml import cv2 import torch from torch.autograd import Variable from models.yolov3 import * from utils.utils import * from utils.parse_yolo_weights import parse_yolo_weights def main(): """ Visualize the detection result for the given image and the pre-trained model. """ pars...
demo.py
MIT
3,320
fefc56b99380b84ccd0afa37cd7e9cd565664014
Python
py
from torch import nn from jcopdl.layers import conv_block, linear_block class CNN(nn.Module): def __init__(self): super().__init__() self.conv = nn.Sequential( conv_block(3, 8), conv_block(8, 16), conv_block(16, 32), conv_block(32, 64), ...
14 - Convolutional Neural Network/src/model.py
MIT
584
4266200b61a803c4588cdb929cc58af38ea06a21
Python
py
# -*- coding: utf-8 -*- """ Created on Tue Oct 5 19:13:50 2021 @author: behnood """ #from __future__ import print_function import matplotlib.pyplot as plt #%matplotlib inline # from numpy import linalg as LA import os #os.environ['CUDA_VISIBLE_DEVICES'] = '3' import numpy as np #from models import * ...
MiSiCNet_SimGit.py
Apache-2.0
8,883
ff5b7eb9f9059b16c3a4acaee26e2b66eed3dfb3
Python
py
import torch from .BaseAttacker import BaseAttacker class PGDAttacker(BaseAttacker): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # hardcode def _build(self, eta, iteration): self.eta = eta self.iteration = 100 @torch.no_grad() def...
attacker/PGD.py
MIT
1,620
fefc75b16015bc9fe6f7f2bc7085d308e83a6c42
Python
py
import torch from torch import nn as nn from basicsr.utils.registry import ARCH_REGISTRY from .arch_util import Upsample, make_layer # from depthwise_conv2d_implicit_gemm import DepthWiseConv2dImplicitGEMM torch.backends.cudnn.benchmark = True class UDown(nn.Module): """Downscaling with maxpool then double conv...
basicsr/archs/tm_arch.py
Apache-2.0
9,369
1e4addeade6b93321a683206e2bca4ad03703d75
Python
py
# Copyright 2020 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 writing, s...
3d_segmentation/ignite/unet_evaluation_array.py
Apache-2.0
4,252
5e5b4745b6a96010af5553111c306f933e566136
Python
py
import argparse from tqdm import tqdm from typing import Any, Dict import json import pickle import numpy as np import torch import sys sys.path.append("../../") from visdialch.data.get_bert_embeddings import BertEmbedder class EmbeddingExtractor: def __init__(self, config): super().__init__() self...
tests/extract_visdial_bert_emb.py
BSD-3-Clause
3,478
45d07ffadd65d4863f6bd48f5a9f07a04c175b7a
Python
py
""" An :class:`Activation` is just a function that takes some parameters and returns an element-wise activation function. For the most part we just use `PyTorch activations <http://pytorch.org/docs/master/nn.html#non-linear-activations>`_. Here we provide a thin wrapper to allow registering them and instantiating them ...
allennlp/nn/activations.py
Apache-2.0
3,235
10c2cccf0c9f5f39e6df33e220e2ffb273933ee9
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from ucb_rl2_meta.distributions import Categorical from ucb_rl2_meta.utils import init init_ = lambda m: init(m, nn.init.orthogonal_, lambda x: nn.init. constant_(x, 0)) init_relu_ = lambda m: init(m, nn.in...
ucb_rl2_meta/model.py
MIT
10,706
5ebcee875fd6670359cb512483fe83fd46abe528
Python
py
import torch from torchvision import datasets, transforms import torchvision.models as models from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset import logging import argparse from tqdm import tqdm import numpy as np import time logging.basicConfig( format="%(asctime)s - %(l...
collaborative_system/collaboration_cv.py
Apache-2.0
4,560
70a747565374c6784c27a91e795ce5f49ae3da4f
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision def calc_mean_std(feat, eps=1e-5): # eps is a small value added to the variance to avoid divide-by-zero. size = feat.size() assert (len(size) == 4) N, C = size[:2] feat_var = feat.view(N, C, -1)...
models/our_model.py
MIT
10,666
fefcdf99acdba3f9395e0330a560f984bfe1c788
Python
py
import sys import os import subprocess import numpy as np import torch def do_tensorflow_routine(path_name_file, grad_needed_for_embeddings = True): output_file = path_name_file.replace(".txt","") + "_emb_sgsc.txt" os.chdir(os.path.join("/data/megh98/projects/graph-prompt-project/baselines/syn/bne_resources"))...
baselines/bne/bne_resources/run_bne_for_pt.py
MIT
1,662
70696a34e5e43cf05846a6b82d9624fb593ca6a6
Python
py
from functools import reduce import operator import torch import torch.nn as nn from torch.autograd import Variable count_ops = 0 conv_ops = 0 count_params = 0 def get_num_gen(gen): return sum(1 for x in gen) def is_leaf(model): return get_num_gen(model.children()) == 0 def get_layer_info(layer): la...
utils/measure.py
MIT
4,514
fefd2fc43732bd68f7d19acda52e702d301fc5fc
Python
py
import torch.nn as nn import torch.nn.functional as F import torchvision.models as models class ResNetSimCLR(nn.Module): def __init__(self, base_model, out_dim): super(ResNetSimCLR, self).__init__() self.resnet_dict = {"resnet18": models.resnet18(pretrained=False, norm_layer=nn.InstanceNorm2d), ...
simclr/models/resnet_simclr.py
MIT
1,175
fefd46a6fc2cc69b9e6c5e91a8653cde35cd6138
Python
py
import torch from ..builder import HEADS, build_head from .standard_roi_head import StandardRoIHead from mmdet.core import bbox2roi @HEADS.register_module() class MaskTextspotterHead(StandardRoIHead): def __init__(self, mask_textspotter_head, **kwargs): assert mask_textspotter_head is not None s...
mmdet/models/roi_heads/mask_textspotter_roi_head.py
Apache-2.0
3,509
24eedee7df16091c5bc74d9d9029a1d15c3d9a4f
Python
py
import os import shutil import gc import torch from ..datasets.dataset import DreemDataset from ..models.modulo_net import ModuloNet from ..models.modulo_net.normalization import initialize_standardization_parameters from .descriptions import three_groups_record_description from .utils import generate_memmaps from .....
dreem_learning_open/test/test_models_features_only.py
MIT
4,554
52b60533f2a22ff18d0c86ad7ea3be62acfe6161
Python
py
import numpy as np import torch from tensorboardX import SummaryWriter from torch import nn from config import device, im_size, grad_clip, print_freq from data_gen_6 import DIMDataset from models_v16 import DIMModel from utils import parse_args, save_checkpoint, AverageMeter, clip_gradient, get_logger, get_learning_ra...
train_v16_6.py
MIT
7,275
1092c0a43d0cc7485597fb2a9b9021eabf7a950b
Python
py
#!/usr/bin/env python # coding: utf-8 import os import pickle import subprocess import torch import torch.nn as nn from torchvision import models MODELS = { 'supervised': ['', ''], 'moco-v1': ['https://dl.fbaipublicfiles.com/moco/moco_checkpoints/moco_v1_200ep/moco_v1_200ep_pretrain.pth.tar', 'pth'], 'm...
download_and_prepare_models.py
MIT
8,120
fefd9ccfd5b45cd70bd8601761a76787d87c9a07
Python
py
import bisect import operator import numpy as np import torch from torch.utils import data from multilayer_perceptron import * from utils import * def preprocess_weights(weights): w_later = np.abs(weights[-1]) w_input = np.abs(weights[0]) for i in range(len(weights) - 2, 0, -1): w_later = np.matm...
neural_interaction_detection.py
Apache-2.0
3,905
fefdcc4b39abbd36a5e2708a7747476f4a6c3a8b
Python
py
from typing import Union from itertools import zip_longest import torch import torch.nn as nn from ctt.models.transformers.ctt1 import _DiurnalContactTracingTransformer import ctt.models.modules as mods import ctt.models.attn as attn class _DiurnalContactTracingTransformerV2(_DiurnalContactTracingTransformer): ...
ctt/models/transformers/ctt2.py
Apache-2.0
13,293
12ef53376411c614f34cb3d52b576bdde562ca48
Python
py
import numpy as np import torch import torch.nn.functional as F from pretrainedmodels.models.dpn import DPN from pretrainedmodels.models.dpn import pretrained_settings class DPNEncorder(DPN): def __init__(self, feature_blocks, *args, **kwargs): super().__init__(*args, **kwargs) self.feature_blocks = np.c...
models/encoders/dpn.py
MIT
4,155
fefe11f498a812838d7e908ed45666f6d7f31fca
Python
py
from __future__ import absolute_import, division import os import torch.nn as nn import scipy.io as scio import cv2 import numpy as np import torch def loadmat(datasetPath, dataPath): '''load .mat as ndarray''' dataFullPath = os.path.join(datasetPath,dataPath) dataDict = scio.loadmat(dataFullPath) name...
PF/ops.py
MIT
1,717
1e031c048ee70da639829363d216ea501e52da83
Python
py
#encoding:utf-8 # #created by xiongzihua # ''' txt描述文件 image_name.jpg x y w h c x y w h c 这样就是说一张图片中有两个目标 ''' import os import sys import os.path import random import numpy as np import torch import torch.utils.data as data import torchvision.transforms as transforms import cv2 import matplotlib.pyplot as plt class...
dataset.py
MIT
10,622
b2540f5be29eb07b137084c9f64a2c28ad234a57
Python
py
""" Copyright (c) 2019 Intel Corporation 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 writin...
pytorch_toolkit/nncf/nncf/dynamic_graph/patch_pytorch.py
Apache-2.0
6,329
fefe5763cf944f63816a7e452ef1d79bd7016687
Python
py
import itertools import torch import torch.nn as nn import torch.nn.functional as F class CNNMapEncoder(nn.Module): def __init__(self, map_channels, hidden_channels, output_size, masks, strides, patch_size): super(CNNMapEncoder, self).__init__() self.convs = nn.ModuleList() patch_size_x = ...
trajectron/model/components/map_encoder.py
MIT
6,818
fefe72a5d7e8ec8028dd38c885d5a30c2247446a
Python
py
import torch from torch import nn import numpy as np import dataset import glob import pandas as pd import tqdm import sys import json import os import logging # own modules from GreedyInfoMax.stock.models import load_stock_model from GreedyInfoMax.stock.models.loss_supervised_fn import ( Supervised_Loss, targ...
convert.py
MIT
7,444
fefea6609ef9e3f0f5e634747eb742ef93459f8e
Python
py
import glob import cv2 import random import numpy as np import pickle import os from torch.utils import data class TrainDataset(data.Dataset): def __init__(self, config): super().__init__() self.config = config train_list_file = os.path.join(config.datasets_dir, config.train_list) ...
data_manager.py
MIT
2,137
1e4d565c92da0ed169b497ff8090225c7d9f0831
Python
py
""" This example uses average word embeddings (for example from GloVe). It adds two fully-connected feed-forward layers (dense layers) to create a Deep Averaging Network (DAN). If 'glove.6B.300d.txt.gz' does not exist, it tries to download it from our server. See https://public.ukp.informatik.tu-darmstadt.de/reimers/...
segmenation_baseline/training_agb_avg_word_embeddings.py
Apache-2.0
5,358
f98ed9b3e8b981a25366991ab41753a567a53087
Python
py
# ============================================================================== # Copyright 2019 Florent Mahoudeau. 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 License at # # ...
model/micResNet.py
MIT
17,410
4b7a2f1aa6dd1f2f993050e2956f0d1e89c4711e
Python
py
# System imports import sys, os # 3rd party imports import pytorch_lightning as pl from pytorch_lightning import LightningModule import torch from torch.nn import Linear import torch.nn.functional as F from torch.utils.data import random_split from torch_geometric.data import DataLoader import numpy as np ...
examples/Pipelines/TrackML_Example/LightningModules/Filter/filter_base.py
MIT
15,988
feff25e72c08d167ef317a6e276f6f432b3cc231
Python
py
import unittest as _unittest import warnings as _warnings from contextlib import redirect_stdout as _redirect_stdout from io import StringIO as _StringIO import torch as _torch import torchvision as _torchvision import torchutils as _tu from ._networks import (_CoverageNetwork, _MultipleInputNetwork, ...
test/test_models.py
MIT
4,820
5f70ea7dd22776f779db1f45160d27fea1fd2447
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import sys, os root_dir = os.path.join(os.path.dirname(__file__),'..') if root_dir not in sys.path: sys.path.insert(0, root_dir) from models.base import Base from models....
romp/lib/models/modelv1.py
MIT
5,420
fd905f39e1ec2860380b05b487ee1b36d3025ef2
Python
py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Provides utilities useful for multiprocessing. """ from multiprocessing import Lock, RawArray from collections.abc i...
parlai/core/thread_utils.py
MIT
5,976
7ceaa632fc56e4c72e102d8931c388a0291ad53c
Python
py
import os import random import numpy as np from torch.utils import data from PIL import Image class TorchAdaptor(data.Dataset): """Dataset class for the CelebA dataset.""" def __init__(self, dataset, transform, for_training=True): """Initialize and preprocess the CelebA dataset.""" ...
deeploader/plats/torch/torch_adaptor.py
Apache-2.0
1,042
7c86615c717c92ae4e69dca2a994590ab787b401
Python
py
import time import torch from queue import deque from collections import OrderedDict from contextlib import contextmanager class RecordManager: def __init__(self, window_size=None, summary_mode=None, sync_cuda=False): self.groups = OrderedDict() self.records = OrderedDict() self.ticks = d...
runner_master/runner/record.py
MIT
6,392
feff4e1b44824f543f3ad21133f74bce920401c9
Python
py
# header files import torch import torch.nn as nn import torchvision from torch.nn import CrossEntropyLoss, Dropout, Softmax, Linear, Conv2d, LayerNorm from torch.nn.modules.utils import _pair import numpy as np import skimage from skimage import io, transform import glob import csv from PIL import Image import time im...
code/utils/utils.py
MIT
7,022
feff89cd5f0357bef9e33962a5bac36fbf060133
Python
py
from dataclasses import dataclass from typing import Any from typing import Dict from typing import List import torch import torch.nn as nn import transformers from transformers import BertConfig, BertModel import warnings import jiant.proj.main.components.container_setup as container_setup import jiant.proj.main.mod...
src/probing-tasks/jiant/jiant/proj/main/modeling/model_setup.py
MIT
13,867
feff9045224d078bea40d4129f19510f5679fecb
Python
py
import torch.nn as nn from collections import OrderedDict import sys print(__name__) print(sys.path) class BidirectionalLSTM(nn.Module): def __init__(self, nIn, nHidden, nOut): super(BidirectionalLSTM, self).__init__() self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True) self.embedding = ...
recognize/crnn.py
MIT
8,213
fcccc5f5786c0c4aaca7dcbf0212730c5f55ecfa
Python
py
import torch from .base_reducer import BaseReducer class DivisorReducer(BaseReducer): def unpack_loss_info(self, loss_info): losses, loss_indices, reduction_type, kwargs = super().unpack_loss_info( loss_info ) if reduction_type != "already_reduced": kwargs = {"divi...
src/pytorch_metric_learning/reducers/divisor_reducer.py
MIT
1,174
7ce5661c7148f7afe8e51b6bb007e1596fe2018a
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/setup_tools.py
Apache-2.0
3,278
dfde2bc6e42b8975e410e21dc0b6d3c617324ca1
Python
py
import argparse import os import re import time import torch import pandas as pd from kernel_utils import VideoReader, FaceExtractor, confident_strategy, predict_on_video_set from training.zoo.classifiers import DeepFakeClassifier if __name__ == '__main__': parser = argparse.ArgumentParser("Predict test videos") ...
predict_folder.py
MIT
2,225
f9cce00bae16ad927185a4a96c1e02be79d2b11d
Python
py
import os import sys import inspect import argparse import yaml import numpy as np current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent_dir) import torch import torch.optim as optim import torch.nn as...
src/classification_train.py
MIT
8,359
4b77c5dd7d6342e536f6cc1ca2aa8999b5d16838
Python
py
''' retrain models on sst5 ''' import numpy as np import os import yaml import argparse from tqdm import tqdm import torch import torch.optim import torch.nn.functional as F from torch.utils.data import DataLoader from model.supernet import TextClassifier from task.utils import logger, set_seed from .search_supernet...
task/text_classification/retrain.py
Apache-2.0
9,645
45dbcce91f4e2cb4084ff76d0924148d5f8e1df2
Python
py
import unittest import numpy as np import pytest import torch from numpy.testing import assert_almost_equal from torch_audiomentations.augmentations.gain import Gain from torch_audiomentations.utils.dsp import ( convert_decibels_to_amplitude_ratio, convert_amplitude_ratio_to_decibels, ) class TestGain(unitt...
tests/test_gain.py
MIT
25,747
feffd05602d841617f55fee7f0da8cd475a7f88d
Python
py
from hythe.libs.dispatch.dispatcher import Dispatcher from torch.multiprocessing import Process, set_start_method class ParallelDispatcher(Dispatcher): def __init__(self, dispatch_list=None): super(ParallelDispatcher, self).__init__(dispatch_list) def dispatch(self): try: set_sta...
libs/dispatch/parallel_dispatcher.py
MIT
766
feffea1affedafdb3991320b38e1b269011021f6
Python
py
import os import torch from data.args import get_args, print_args, init_args from models.graph_models.model import RuleBasedModel from scripts.train import build_test_loader, check_model_iou torch.backends.cudnn.benchmark = True def main(args): args.vocab, val_loader = build_test_loader(args) init_args(args...
scripts/test_iou.py
MIT
1,039
e98ee0aff1253a2e0d125c2f3ded8f44af778da9
Python
py
import torch import torch.nn as nn import sys sys.path.append("../../") from general.train import TrainTemplate, get_default_train_arguments, start_training from general.mutils import get_param_val, general_args_to_params from general.parameter_scheduler import add_scheduler_parameters, scheduler_args_to_params from ...
experiments/molecule_generation/train.py
MIT
4,297
1e0c1c49a6b84401c3087a73d22568386766d7d8
Python
py
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @Author : Peike Li @Contact : peike.li@yahoo.com @File : dataset.py @Time : 8/30/19 9:12 PM @Desc : Dataset Definition @License : This source code is licensed under the license found in the LICENSE file in the root directory of this...
datasets/extractor_dataset.py
MIT
2,284
3a00204779cba946d035e20a3bea9521f0577686
Python
py
import argparse import torch import time import imageio import numpy as np from pathlib import Path from torch.autograd import Variable from utils.make_env import make_env from algorithms.maddpg import MADDPG def run(config): model_path = (Path('./models') / config.env_id / config.model_name / (...
evaluate.py
MIT
4,800
42837a13c9d5eb988082c06bf22fe1ba03086bb0
Python
py
import os import datetime as dt import torch import torch.distributed as dist import math import time import pickle import statistics from collections import defaultdict class DistEnv: def __init__(self, local_rank, world_size, backend='nccl'): assert(local_rank >= 0) assert(world_size > 0) ...
1D_CAGNET/utils.py
MIT
5,354
7c3ead53c5dcafe3c37975074f02d5cb5a05745e
Python
py
# Copyright (c) 2018, Curious AI Ltd. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View...
mean_teacher/utils.py
MIT
4,162
8010735163ae64d98b9b4ee8e81cd9cffe789a4e
Python
py
import importlib import inspect from typing import List import torch.nn as nn import torch.optim as opt from utils.constants import * from utils.data_loaders import * models = {x: {} for x in types} """ handles loading in model references as well as saving and loading """ def _read_all_class_names(): """ p...
utils/model_utils.py
MIT
3,191
3a005840da9979f1d06a9a4f9e8bbe8d42c42594
Python
py
# https://github.com/pyg-team/pytorch_geometric/blob/master/examples/graph_saint.py import os.path as osp import argparse import torch import torch.nn.functional as F from torch_geometric.datasets import Flickr from torch_geometric.loader import GraphSAINTRandomWalkSampler from torch_geometric.nn import GraphConv ...
examples/graph_saint.py
MIT
3,642
3a0066c3e0a93821c55cf57098a88ebb1322a462
Python
py
import torch import torch.nn as nn from torch.nn import init from torchvision import models ###################################################################### def weights_init_kaiming(m): classname = m.__class__.__name__ # print(classname) if classname.find('Conv') != -1: init.kaiming_normal(m...
model.py
MIT
1,896
28fd21f962ba562db7ee1d78c68f2445a193b8bb
Python
py
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Written by Bin Xiao (Bin.Xiao@microsoft.com) # Modified by Ke Sun (sunk@mail.ustc.edu.cn) # ------------------------------------------------------------------------------ from ...
tools/train.py
MIT
7,267
4b98acda90e30bc6e91f43f81559af4753836f43
Python
py
from sciwing.data.contextual_lines import LineWithContext from sciwing.data.seq_label import SeqLabel from sciwing.datasets.seq_labeling.base_seq_labeling import BaseSeqLabelingDataset from sciwing.numericalizers.numericalizer import Numericalizer from torch.utils.data import Dataset from typing import Dict, List, Any ...
sciwing/datasets/seq_labeling/conll_yago_dataset.py
MIT
6,241
3a00ca0ae4ae36beee13ac88e1281a283c71e525
Python
py
import math import torch from torch.optim import Optimizer import numpy as np class Adam(Optimizer): r"""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 ...
optimizers/adam_mnk.py
Apache-2.0
9,276
5e87f2b6af5dfd02112460b5ab45dcbef8777cd3
Python
py
import torch import torch.nn.functional as F import torch.nn as nn drop = 0.25 def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True) class BasicBlock(nn.Module): ex...
models/LadderNet.py
Apache-2.0
7,757
1e907d4b0935acc1cbdbb4fdc275f177f83107fc
Python
py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. import argparse import os import time from loguru import logger import cv2 import torch import sys sys.path.append("D:\mynetwork\YOLOX-main") from yolox.data.data_augment import ValTransform # from yolox.data.datasets impo...
.history/tools/demo_20211008153203.py
Apache-2.0
14,802
3a00fb3111d9394f6c21a01b2e6024ffce8c775b
Python
py
import torch import torch.nn as nn from torch.nn import functional as F from tensorboardX import SummaryWriter from satflow.models.layers.GResBlock import GResBlock from satflow.models.layers.Normalization import SpectralNorm from satflow.models.layers.ConvGRU import ConvGRU from satflow.models.layers.Attention impor...
satflow/models/layers/Generator.py
MIT
5,654
3a010294780d31e6718af2226d3c8170e21e4497
Python
py
import csv import glob import os import re import cv2 import matplotlib.pyplot as plt import numpy as np import scipy.io as sio import torch.utils.data import imgaug as ia from imgaug import augmenters as iaa from misc.utils import cropping_center from .augs import ( add_to_brightness, add_to_contrast, a...
dataloader/train_loader.py
MIT
6,761
fcb7902f048c79ebef6ad1a4804122b6fa5b0684
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...
pytorch_lightning/profiler/advanced.py
Apache-2.0
3,800
3a017d72ff5e07c6a147a25ad744b675a70c21dd
Python
py
import io import itertools import unittest from parameterized import parameterized from torchaudio._internal.module_utils import is_sox_available from torchaudio.backend import sox_io_backend from torchaudio.utils import sox_utils from torchaudio_unittest.common_utils import ( TempDirMixin, TorchaudioTestCase,...
test/torchaudio_unittest/backend/sox_io/smoke_test.py
BSD-2-Clause
6,372
cc0f7b5f26b640edb208363d9e1eadb37ff311b0
Python
py
import torch from torch import nn from torch.nn import functional as F from math import log, pi, exp import numpy as np from scipy import linalg as la logabs = lambda x: torch.log(torch.abs(x)) class ActNorm(nn.Module): def __init__(self, in_channel, logdet=True): super().__init__() ...
model.py
MIT
11,193
34126e34742c5e69ff5ff487cbaeace995815d05
Python
py