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 |
|---|---|---|---|---|---|---|---|
"""
Modified based on: https://github.com/open-mmlab/mmskeleton
"""
import math
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from opendr.perception.skeleton_based_action_recognition.algorithm.graphs.nturgbd import NTUGraph
from opendr.perception.skeleton_based_action_recogn... | src/opendr/perception/skeleton_based_action_recognition/algorithm/models/stgcn.py | Apache-2.0 | 5,755 | ff101abfcc705ef2a0998cfc3d5bfec74e530cc7 | Python | py | |
import torch.nn as nn
class ResBlock(nn.Module):
def __init__(self, conv, n_feat, kernel_size, padding=0, bias=True, bn=False, act=nn.ReLU(True), res_scale=1):
super(ResBlock, self).__init__()
m = []
for i in range(2):
m.append(conv(n_feat, n_feat, kernel_size, padding=padding,... | code/models/archs/SRN_arch.py | MIT | 4,275 | 3ad156c145677cd950d5544df088b78eed91fbd2 | Python | py | |
# import multiprocessing as mp
# import numpy as np
# import ctypes
import torch
from rlpyt.utils.buffer import np_mp_array
from rlpyt.utils.logging import logger
from rlpyt.utils.quick_args import save__init__args
class EpsilonGreedyAgentMixin:
"""
Mixin class to operate all epsilon-greedy agents. Includes... | rlpyt/agents/dqn/epsilon_greedy.py | MIT | 5,641 | 3ad16098bb6de17008647ff94ede24d6da0625aa | Python | py | |
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import torch
import torch.nn as nn
import torch.autograd as autograd
import numpy as np
import json
class EventModule(nn.Module):
def __init__(self, params, word_size, seg_size, num_events, num_roles):
... | event_extractor/model/dgcnn.py | MIT | 14,514 | b23748f67f5645e2b150022ffd5f6a4678c7605e | Python | py | |
import json
import os
import random
import shutil
import time
import pickle
import numpy as np
import torch
import torch.backends.cudnn as cudnn
def reproducibility(args, seed):
torch.manual_seed(seed)
if args.cuda:
torch.cuda.manual_seed(seed)
np.random.seed(seed)
cudnn.deterministic = True
... | lib/utils/general.py | MIT | 3,297 | 3ad19dee08f6b8754e54f7e0f2895b88defd8dc9 | Python | py | |
from typing import Dict # isort:skip
from gym.spaces import Discrete
import torch
import torch.nn as nn
from catalyst.contrib.modules import Flatten
from catalyst.rl.agent.head import ValueHead # , StateNet
from catalyst.rl.core import CriticSpec, EnvironmentSpec
from catalyst.utils.initialization import create_opti... | examples/minigrid/src/critic.py | Apache-2.0 | 3,274 | 12a2ab2b6a8dc524207ecd7d747ae99f9696a612 | Python | py | |
import logging
import math
import monai
from monai.transforms import Compose, EnsureChannelFirstd, LoadImaged, ScaleIntensityd, ToTensord
from sklearn.metrics import classification_report, confusion_matrix, mean_squared_error, r2_score
import torch
from torch.utils.data import DataLoader
import wandb
logger = logging... | miqa/learning/nn_inference.py | Apache-2.0 | 7,431 | 3ad1b1c677c082989743407c4f8c384270502ddd | Python | py | |
import torch
import pytest
import numpy as np
from bgflow.distribution import NormalDistribution, TruncatedNormalDistribution, MeanFreeNormalDistribution
@pytest.mark.parametrize("dim", [2])
@pytest.mark.parametrize("n_samples", [10000])
@pytest.mark.parametrize("temperature", [1.0, 0.5, 2])
def test_normal_distributi... | tests/distribution/test_normal.py | MIT | 3,987 | 3ad1bf0297c8167474fdcaa8b719652c39687837 | Python | py | |
import torch
from .untargeted_batch_l2_reparameterized_gradient_descent import *
class UntargetedBatchL2CarliniWagner(UntargetedBatchL2ReparameterizedGradientDescent):
"""
Implementation of untargetetd PGD attack.
"""
def __init__(self, model, images, classes=None, epsilon=0.5, c=0.05, base_lr=0.1):
... | attacks/untargeted_batch_l2_carlini_wagner.py | Unlicense | 1,011 | fcfdf087058b4edbb7b1e33d9cb3741e8ee93c6f | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import math
import warnings
from typing import Optional, Sequence, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from pytorch3d.transforms import Rotate, Transform3d, Translate
from .utils import TensorProperties, convert... | pytorch3d/renderer/cameras.py | BSD-3-Clause | 48,434 | 4b10d1109f92e4f683e98c6919163957289956fb | Python | py | |
import torch
import numpy as np
import os
from utils.reranking import re_ranking
def euclidean_distance(qf, gf):
m = qf.shape[0]
n = gf.shape[0]
dist_mat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \
torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t()
dist_mat.addm... | transreid_pytorch/utils/metrics.py | MIT | 4,537 | 3ad1df33c5fefa90fac24853eb7a3f80c72bbee9 | Python | py | |
import numpy as np
import scipy.sparse as sp
import torch
import pickle
def encode_onehot(labels):
# set():创建无序不重复的序列 7类
classes = set(labels)
# np.identity():创建方阵的one-hot向量 主对角线为1,其余为0数组
classes_dict = {c: np.identity(len(classes))[i, :] for i, c in
enumerate(classes)}
# (2708,... | pygcn/utils.py | MIT | 3,317 | 52d626ca9337808a8da8dc4a3febc59b731a455b | Python | py | |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems 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
#... | speech_recognition/pytorch/decoder.py | Apache-2.0 | 7,123 | 5e8a5b3ae8511254c17d19faf025bad18492424b | Python | py | |
import torch
from torchtext import data, datasets
import random
def load_data(BATCH_SIZE=16):
SEED = 1234
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
TEXT = data.Field(tokenize='spacy')
LABEL = data.LabelField(dtype=torch.float)
train_da... | src/load_data.py | MIT | 887 | 3ad2077546dcab5ed2b6988e590fa20bccbc4c4c | Python | py | |
"""
Created on Mon Nov 21 21:57:29 2017
@author: Utku Ozbulak - github.com/utkuozbulak
"""
import os
from PIL import Image
import torch
from torch.optim import SGD
from torchvision import models
from misc_functions import preprocess_image, recreate_image, save_image
class DeepDream():
"""
Produces an i... | src/deep_dream.py | MIT | 3,588 | 653a61eb8fc8aa4d233d797535bd3a3f84b5ed8c | Python | py | |
from torchwisdom.core.utils import DatasetCollector
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from pathlib import Path
from torchwisdom.vision import transforms as ptransforms
from .datasets import CSVDataset
class CSVDataCollector(object):
def __init__(self, path, batch_... | torchwisdom/tabular/collector.py | MIT | 3,445 | 3ad20f5217be7e998cd5ccc326602489da47a9fa | Python | py | |
# -*- coding: utf-8 -*
from loguru import logger
import torch
from videoanalyst.model.common_opr.common_block import (conv_bn_relu,
xcorr_depthwise)
from videoanalyst.model.module_base import ModuleBase
from videoanalyst.model.task_model.taskmodel_base import (... | videoanalyst/model/task_model/taskmodel_impl/siamese_track.py | MIT | 8,928 | 3ad212ad35897706ce9d34eed919d7554ef25f37 | Python | py | |
"""General-purpose training script for image-to-image translation.
This script works for various models (with option '--model': e.g., pix2pix, cyclegan, colorization) and
different datasets (with option '--dataset_mode': e.g., aligned, unaligned, single, colorization).
You need to specify the dataset ('--dataroot'), e... | train.py | BSD-3-Clause | 5,251 | 3ad217363893b4caabed02c2121d4529248e60fd | Python | py | |
########################################################
#
# Autor: Andrej Paníček
# Posledná zmena: 10.4.2019
# Popis: Tento modul obsahuje pomocné funkcie, využité
# v iných moduloch
#
########################################################
import sys
import os
import torch
impor... | detector/func.py | MIT | 4,418 | 3ad2261fd2a11f8d561451f8c421eaedcc5d587f | Python | py | |
import torch
import PIL
import kornia as K
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from typing import Union
import pathlib
t_filename = Union[str, pathlib.Path]
t_filename_or_image = Union[t_filename, Image.Image]
t_font_or_none = Union[ImageFont.ImageFont, None]
def to_tensor(img: t_filename... | tormentor/util.py | Apache-2.0 | 4,260 | 3436b81798313a8e80d00f05c5ed3fa29461fce4 | Python | py | |
import copy
import os
import torch
import torch.utils.data
import torchvision
from PIL import Image
from pycocotools import mask as coco_mask
from pycocotools.coco import COCO
"""
Source: https://github.com/pytorch/vision/blob/master/references/detection/coco_eval.py
"""
class FilterAndRemapCocoCategories(object):
... | src/xview3/training/eval/coco_utils.py | Apache-2.0 | 7,697 | 3ad2491725313dee82680c2996d3e238ba75ef29 | Python | py | |
#!/usr/bin/env python3.6
import torch
from torch.autograd import Function
from torch import Tensor
import sys
import os
import numpy as np
import time
# http://wiki.ros.org/Packages#Client_Library_Support
import rospkg
rospack = rospkg.RosPack()
sf_src_path=rospack.get_path('surfel_renderer')
sf_build_path=os.path.ab... | latticenet_py/misc/lnn_make_teaser_img.py | MIT | 2,995 | 3ad26957aef940371ce8ca2eb9ca136e7753c3d5 | Python | py | |
# Copyright 2020 Erik Härkönen. All rights reserved.
# This file is licensed to you 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 applica... | notebooks/notebook_utils.py | Apache-2.0 | 9,307 | 5f421c441199fa04037adf739fd911df6f1c1559 | Python | py | |
from argparse import ArgumentParser
import json
import os
from PIL import Image
import torch
from torchvision import transforms
from ssim import ssim, msssim
def main():
parser = ArgumentParser('Calculate SSIM, MSSSIM')
parser.add_argument('--meta_path', type=str)
parser.add_argument('--img_dir', typ... | calculate_ssim.py | MIT | 1,710 | 3ad28d6ef70c6f971cce37a227d77a2accd06a81 | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
class CircleLoss(nn.Module):
def __init__(self, scale=32, margin=0.25, similarity='cos', **kwargs):
super(CircleLoss, self).__init__()
self.scale = scale
self.margin = margin
self.similarity = similarity
... | circle_loss.py | MIT | 1,878 | 1e27627c1edf70d85622652e029e3f766314bf7e | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytext.config import ConfigBase
from pytext.config.module_config import SlotAttentionType
from pytext.models.module import Module
from torch.nn.utils.rnn... | pytext/models/representations/slot_attention.py | BSD-3-Clause | 2,945 | fdb20cb0c80f45ff75d15161f28a5acf86e5619d | Python | py | |
#!/var/scratch/mao540/miniconda3/envs/maip-venv/bin/python
import argparse
import os
import torch
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.utils.data as data
import torchvision
import torchvision.transforms as transforms
from torchvision import datasets
from torch.utils.data impor... | train.py | MIT | 12,674 | 3ad2b3930a224bbab9e2c78f7d470b3f64b0a4e2 | Python | py | |
# Tencent is pleased to support the open source community by making ncnn available.
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy o... | tools/pnnx/tests/ncnn/test_nn_AdaptiveAvgPool1d.py | BSD-3-Clause | 1,752 | 3ad2bc34e8f991b2585541f1d081d4853d745ad3 | Python | py | |
# !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:8/11/2021 11:02 AM
# @File:MBConv.py
import math
from functools import partial
import torch
from torch import nn
from torch.nn import functional as F
class SwishImplementation(torch.autograd.Function):
@staticmethod
def forward(ctx,... | python_developer_tools/cv/bases/conv/MBConv.py | Apache-2.0 | 6,872 | 3ad2e0f563a370a85a70559ffc6f1e97e5d44b25 | Python | py | |
# adapted from https://github.com/metalbubble/cnnvisualizer/blob/master/pytorch_generate_unitsegments.py
import argparse
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.models as models
import torchvision.transforms as transforms
from ... | unit_visualization/generate_unitsegments.py | MIT | 8,770 | 6b3e51628e4ea8c109d96271b3238a42c9fb636c | Python | py | |
"""
LFFD for face detection, implemented in PyTorch.
Original paper: 'LFFD: A Light and Fast Face Detector for Edge Devices,' https://arxiv.org/abs/1904.10633.
"""
__all__ = ['LFFD', 'lffd20x5s320v2_widerface', 'lffd25x8s560v1_widerface']
import os
import torch.nn as nn
from .common import conv3x3, conv1x1_bl... | pytorch/pytorchcv/models/lffd.py | MIT | 10,582 | 7cc30af33af0dcadf4dc376152c7cf3d5e4fd0dd | Python | py | |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
"""
Contrastive loss function.
Based on: https://github.com/delijati/pytorch-siamese/blob/master/contrastive.py
"""
import torch
import torch.nn as nn
__author__ = "Pau Riba"
__email__ = "priba@cvc.uab.cat"
class ContrastiveLoss(nn.Module):
... | src/loss/contrastive.py | MIT | 2,139 | 3ad3144128903a87317305791c75c207c7a9a16f | Python | py | |
"""
The core research contribution for the pSp encoders
from the pixel2style2pixel framework.
Credit: https://github.com/eladrich/pixel2style2pixel
"""
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn import Linear, Conv2d, BatchNorm2d, PReLU, Sequential, Module
from m... | models/encoders/psp_encoders.py | Apache-2.0,BSD-2-Clause,MIT | 7,317 | 3ad34fa411638fc89b787dac9e929794ef7b7833 | Python | py | |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
import os
import torch.nn as nn
import torch
import random
from yolox.exp import Exp as MyExp
import torch.distributed as dist
class Exp(MyExp):
def __init__(self):
super(Exp, self).__init__()
self.de... | exps/default/shufflev2-GhostPAN.py | Apache-2.0 | 3,077 | 3ad355ab57778fee7803f8d297f4ef6a9813c2cc | Python | py | |
from torch.utils.data import Dataset
import rdkit
from torch_geometric.data import InMemoryDataset
class InMemoryRdkitDataset(InMemoryDataset):
edge_types = {rdkit.Chem.rdchem.BondType.SINGLE: 0,
rdkit.Chem.rdchem.BondType.DOUBLE: 1,
rdkit.Chem.rdchem.BondType.TRIPLE: 2,
... | torch_chemistry/datasets/base_dataset.py | MIT | 603 | 52c36fa45dd9a45b6749ff9e40f6d0b9cc393f20 | Python | py | |
import torch
import time
import torch.nn.functional as F
import numpy as np
import argparse
def run_lib(args):
assert torch.cuda.is_available()
cuda_device = torch.device("cuda") # device object representing GPU
batch_size = args.batch_size
input_features = args.input_features
lib_name ... | dim_obfuscator/torch_test.py | Apache-2.0 | 1,015 | 3ad3877a1739c850c87ac37c182783484c765fea | Python | py | |
"""Root package info."""
__version__ = '0.9.1rc1'
__author__ = 'William Falcon et al.'
__author_email__ = 'waf2107@columbia.edu'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright (c) 2018-2020, %s.' % __author__
__homepage__ = 'https://github.com/PyTorchLightning/pytorch-lightning'
# this has to be simple string, ... | pytorch_lightning/__init__.py | Apache-2.0 | 3,013 | 1e2027cd4e38d82d744c190930600f6cb13cdcb6 | Python | py | |
import random
from PIL import Image
import torch
class Compose(object):
def __init__(self, transforms):
self.group_transforms = []
self.transforms = []
for t in transforms:
if isinstance(t, ToTensor) or isinstance(t, Normalize):
self.transforms.append(t)
... | src/VioNet/spatial_transforms.py | MIT | 3,766 | 3ad39b067bb368dc6f3eb01b51a3a8e27b348436 | Python | py | |
#import torch
# TODO: Choose dataset and download using python scripts.
from models import *
import torch
from tokenization import *
import time
from torchtext.data.metrics import bleu_score
from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import corpus_bleu
import sys
from livelosspl... | main.py | Apache-2.0 | 11,597 | 52e30ac37cb0ccc7ab4f9bb158bf86d261d20fad | Python | py | |
import warnings
import psutil
import torch
import torch.nn as nn
from tez import enums
from tez.callbacks import CallbackRunner
from tez.utils import AverageMeter
from tqdm.auto import tqdm
warnings.filterwarnings("ignore", message=torch.optim.lr_scheduler.SAVE_STATE_WARNING)
class Model(nn.Module):
def __init_... | tez/model/model.py | Apache-2.0 | 9,809 | 7c2d06b4aad81aa7f8809b1bb49895651c27e800 | Python | py | |
# Copyright (c) 2018-2021 Oleg Sémery
# SPDX-License-Identifier: MIT
#
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
from inspect import isfunction
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from optim.dropout import Dropout
_VALID_MOD... | model/common.py | MIT | 25,777 | 5f2acf76e367bb07c39cd44c42c4d3c01c78667e | Python | py | |
from collections import OrderedDict
import numpy as np
import torch.optim as optim
from torch import nn as nn
import torch
from torch import autograd
from torch.autograd import Variable
import torch.nn.functional as F
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
fr... | rlkit/torch/irl/policy_optimizers/multiple_q_update_sac.py | MIT | 8,806 | 28b7af4e94df990289360aba11a20305548e461f | Python | py | |
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from collections import OrderedDict
from torch import Tensor
from torch.jit.annotations import List
#added
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from load_utils... | densenet_ori_train.py | MIT | 20,333 | 5e53b75cb5c5caab7a0eb5e96d84726d6aefac92 | Python | py | |
import os
import pickle
import pkg_resources
import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
from transvae.trans_models import TransVAE
from transvae.rnn_models import RNN, RNNAttn
from transvae.data import vae_data_gen, make_std_mask
from scripts.parsers import attn_parser
... | scripts/attention.py | MIT | 4,242 | 1ebfeb3a327075a84557feaa03c810ceabceabee | Python | py | |
from __future__ import print_function
from PIL import Image
import os
import os.path
import numpy as np
import sys
import torch
import torch.utils.data as data
import torchvision.transforms.functional as TF
import torchvision.transforms as transforms
if sys.version_info[0] == 2:
import cPickle as pickle
else:
... | dataset/cifar10.py | MIT | 9,140 | 248bbc79dd3faa4d6198d0ae72b2acf59a8f33f8 | Python | py | |
""" Tools for implementing Direct Feedback Alignment (DFA) in PyTorch.
"""
import copy
import numpy as np
import time
import torch
import torch.multiprocessing as mp
import torch.nn as nn
from collections import OrderedDict
class AsymmetricSequential(nn.Sequential):
"""A PyTorch sequential container modified to ... | dfatools/dfatorch.py | Apache-2.0 | 5,465 | 3ad441100dd026bf8c829fb7ecd5ab5cde63e497 | Python | py | |
# %%
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def compute_padding(kernel_size, stride):
"""
Ensures same padding for stride of 1
otherwise ensures sufficient padding that no edges are skipped
"""
greatest_remainder = stride - 1
pad = max(greatest_remainde... | feature_extractor/feature_extractor.py | MIT | 11,539 | 3ad44168b02f37123b951a06e10c1a9c43839a8d | Python | py | |
import os
from torch.utils.data import DataLoader, Dataset
import torch.nn as nn
import torch
import numpy as np
from collections import Counter
class KneeManager(object):
def __init__(self, options, train_args, labels, out_class):
self.train_args = train_args
self.options = options
""" D... | dataloader.py | MIT | 4,451 | 3ad45ff88599b626663c8074ac45b399464d56d3 | Python | py | |
"""
COCO Raccon Dataset Classes
"""
from .config import HOME
import os
import os.path as osp
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import cv2
import numpy as np
COCO_RACCOON_ROOT = osp.join(HOME, 'data/coco_raccoon')
IMAGES = 'images'
ANNOTATIONS = 'annot... | data/raccoon.py | MIT | 6,246 | ff88e19bf37b6a4a01209504176ac81926b6a838 | 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/plugins/training_type/horovod.py | Apache-2.0 | 8,181 | 6548ae4f927cbc9cfc9f531e6176e6a72fb7a9b5 | Python | py | |
# from GPUtils.startup_guyga import *
import sys, os, copy, math
from os.path import join as pjoin, exists as pexists, basename, isfile
import numpy as np
from numpy import array, unique
import torch
import torch.utils.data as data
import cv2
import json
from termcolor import cprint
cprintm = lambda s: cprint(s, 'magen... | datasets/xview.py | MIT | 10,451 | 3ad49cd0b934e42081c71b6749e1f62731ee3fc5 | Python | py | |
import sys
import numpy as np
import scipy.linalg
import PIL
import copy
import torch
from torch import nn
import torch.nn.functional as F
import keynet.sparse
from keynet.sparse import sparse_permutation_matrix, sparse_identity_matrix, sparse_identity_matrix_like
from keynet.torch import affine_to_linear, linear_to_a... | test/test_keynet.py | MIT | 14,483 | 03c52712c5c8679ec1000b947ea480c5f1ffd623 | Python | py | |
import os, sys
from os.path import join
import numpy as np
import torch
from torch.utils.data import DataLoader
import torchvision
from datasets import Data_Loader
from model import TIN
from logger import Logger
from utils import init_model
from torch.utils.tensorboard import SummaryWriter
"""
learning rate adjustment... | train.py | MIT | 3,842 | 3ad4a0a81de990e0e5da6a5efe8d6302f814a3cf | Python | py | |
from abc import ABC, abstractmethod
from typing import Union, List, Tuple, Callable
import torch.distributed as torch_distrib
from torch.utils.data import SequentialSampler, DataLoader
from torch.utils.data.distributed import DistributedSampler
from pytorch_lightning.core import LightningModule
from pytorch_lightning... | pytorch_lightning/trainer/data_loading.py | Apache-2.0 | 9,912 | 039c7ee588b456c53ee8e2cbb7c37a659f753ee9 | Python | py | |
from torch import nn
class TransitionModel(nn.Module):
def __init__(self, state_dim, num_agent, action_dim,
hidden_dim=64, act_fn='relu'):
super().__init__()
self.state_dim = state_dim
self.num_agent = num_agent
self.action_dim = action_dim
self.hidden_di... | src/efficient/transition.py | Apache-2.0 | 364 | e9a588c6846d373686b7b84370cf80b545b8fce1 | Python | py | |
"""
3D IoU Calculation and Rotated NMS
Written by Shaoshuai Shi
All Rights Reserved 2019-2020.
"""
import torch
import numpy as np
import iou3d_nms_cuda
def check_numpy_to_torch(x):
if isinstance(x, np.ndarray):
return torch.from_numpy(x).float(), True
return x, False
def boxes_bev_iou_cpu(boxes_a,... | generate_cluster_mask/utils/iou3d_nms/iou3d_nms_utils.py | MIT | 3,759 | 4b8566fcb0651fd5d9446c63e5846147deee8dc5 | Python | py | |
#!/usr/bin/env python3
import unittest
from math import exp, pi
import gpytorch
import torch
from gpytorch.distributions import MultivariateNormal
from gpytorch.kernels import RBFKernel, ScaleKernel
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.means import ConstantMean
from gpytorch.priors import... | test/examples/test_simple_gp_regression.py | MIT | 21,695 | 3ad4e712fc70f6cac0856795f7107a32e56e6a39 | Python | py | |
import os.path as osp
from pathlib import Path
import numpy as np
from torch.utils.data import Dataset
from .registry import DATASETS
from .pipelines import Compose
@DATASETS.register_module
class PointCloudDataset(Dataset):
"""An abstract class representing a pytorch-like Dataset.
All other datasets should... | det3d/datasets/custom.py | MIT | 6,409 | 1e877f2af31946cd58c454c085e48cd62a647c37 | Python | py | |
import torch
import torch.nn as nn
from torch import Tensor
from hnlp.base import task_config
from hnlp.register import Register
@Register.register
class FcClassifier(nn.Module):
"""
FC Classifier.
Using the first token [CLS] to classify.
"""
def __init__(self, is_training: bool):
super(... | hnlp/task/classification.py | MIT | 1,328 | fcd791162c62ba431d4332810bc2f3b6f067a7a9 | Python | py | |
import os
import json
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
from mcloader import ClassificationDataset
class INatDataset(Image... | datasets.py | Apache-2.0 | 4,287 | 3ad52dd05c72a943f97a2ee6e4fcef2d4e8ad4d6 | Python | py | |
import unittest
import torch
import os
import heat as ht
if os.environ.get("DEVICE") == "gpu" and torch.cuda.is_available():
ht.use_device("gpu")
torch.cuda.set_device(torch.device(ht.get_device().torch_device))
else:
ht.use_device("cpu")
device = ht.get_device().torch_device
ht_device = None
if os.environ... | heat/core/tests/test_operations.py | MIT | 4,114 | 24b5c2705f0b458160957cb530800ef744d8ae45 | Python | py | |
import torch
from torch.nn import functional as F
def entropy_kl_loss(recon_x, img, mu, logvar, batch_size, img_dimension):
"""
Loss function: binary cross entropy plus KL divergence.
Parameters:
----------
recons_x : Pytorch tensor
Reconstructed tensor from VAE.
img : Pytorch tensor... | molecules/models/unsupervised/variational_autoencoder/metrics.py | MIT | 1,234 | 457b3e212a8b38f9bacd2ba62cd9aa564dc8c2b2 | Python | py | |
import numpy as np
import pytest
import torch
from ignite.contrib.metrics.regression import GeometricMeanRelativeAbsoluteError
from ignite.engine import Engine
from ignite.exceptions import NotComputableError
def test_zero_sample():
m = GeometricMeanRelativeAbsoluteError()
with pytest.raises(
NotComp... | tests/ignite/contrib/metrics/regression/test_geometric_mean_relative_absolute_error.py | BSD-3-Clause | 3,673 | 3ad56643de9b2a8f273d49f9bdd7a25f93627cf4 | Python | py | |
#!/usr/bin/env python3
from typing import Any, Callable, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from ..._utils.common import _format_input
from ..._utils.typing import BaselineType, TargetType, TensorOrTupleOfTensorsGeneric
from .._utils.common import (
_format_and_verify_sliding_wi... | captum/attr/_core/occlusion.py | BSD-3-Clause | 18,716 | 10a3b5125c53d781811a9edeefa025541704d8db | Python | py | |
# code adapted from "The Annoted Transformer" http://nlp.seas.harvard.edu/2018/04/03/attention.html
import copy
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from allrank.config import PositionalEncoding
from allrank.models.positional import _make_position... | allrank/models/transformer.py | Apache-2.0 | 5,340 | e9d51bca8a114f3d55bec9db1dd3f15da383fe93 | Python | py | |
'''
Neural Network for mnist
Author : Sangkeun Jung (2019)
'''
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
class mlp(nn.Module):
def __init__(self):
super(mlp, self).__init__()
self.fc1 = nn.Linear(28*28, 512)
self.fc2 = nn.Linea... | DeepLearning/5.pytorch_lightning practice with mnist/code/mnist/nn.py | MIT | 577 | 45d8f9f2682c9cc935aa5d7f5ec88513bf417e34 | Python | py | |
import unittest
import torch
from numpy.testing import assert_array_almost_equal
from torchvision.datasets import MNIST, CIFAR10
from torchvision.transforms import Normalize
from mighty.utils.common import set_seed
from mighty.utils.data import DataLoader
from mighty.utils.data.normalize import NormalizeInverse, \
... | mighty/tests/test_utils_data.py | BSD-3-Clause | 4,210 | 3ad56b3e3fa817eef021b5417ec362e150967ff0 | Python | py | |
import os
import gym
import torch
import pprint
import argparse
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from tianshou.env import VectorEnv
from tianshou.policy import PPOPolicy
from tianshou.trainer import onpolicy_trainer
from tianshou.data import Collector, ReplayBuffer
from .continuous... | experiment/mujoco_ppo.py | MIT | 5,011 | 3ad57819067e55a47ce29d52955bb884c285c766 | Python | py | |
import torchvision.models as models
from effdet.config.model_config import efficientdet_model_param_dict
from effdet import get_efficientdet_config, EfficientDet, DetBenchTrain, create_model, load_pretrained, create_dataset
from effdet.efficientdet import HeadNet
from effdet.config.model_config import efficientdet_mode... | src/models/modules/EfficientDet.py | Apache-2.0 | 2,947 | 3ad57c7a8487ae158451eb4684b4ab378a453010 | Python | py | |
# coding=utf-8
# Copyright (c) 2020, 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | megatron/mpu/mappings.py | MIT | 4,402 | 2495d5dcac9ad9744d0220b4f5301338d3ca5451 | Python | py | |
import argparse
import json
import os, sys
import sys
import torch
import tangram as tg
import scanpy as sc
import pandas as pd
import sagenet as sg
import scanpy as sc
import squidpy as sq
import anndata as ad
import random
import torch
import re
currentdir = os.path.dirname(os.path.abspath(__file__))
parentdir = os.... | code/experiments/run_sagenet.py | MIT | 2,352 | 3ad59bdc713b34a1f98ad782d231a1cb49d882a2 | Python | py | |
from copy import deepcopy
import IPython
import tensorflow as tf
import numpy as np
import torch
import torch.nn as nn
from scipy.stats import kendalltau
try:
from nasbench.lib import base_ops
from nasbench.lib import model_builder
except Exception as e:
print(e)
print("have trouble loading nasbench. ... | search_policies/cnn/search_space/nas_bench/util.py | MIT | 16,357 | 3ad5bb09e55f43d6b0a5a6d89a121334317d47da | Python | py | |
""" Loader Factory, Fast Collate, CUDA Prefetcher
Prefetcher and Fast Collate inspired by NVIDIA APEX example at
https://github.com/NVIDIA/apex/commit/d5e2bb4bdeedd27b1dfaf5bb2b24d6c000dee9be#diff-cf86c282ff7fba81fad27a559379d5bf
Hacked together by / Copyright 2021 Ross Wightman
"""
import random
from functools impor... | timm/data/loader.py | Apache-2.0 | 10,056 | 5eb20b7102496b84a4beafe3a1171533b9504caa | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
from multimodelity.common.registry import registry
from torch import nn
from torch.nn.utils.weight_norm import weight_norm
class VisDialDiscriminator(nn.Module):
def __init__(self, config, embedding):
super().__init__()
self.config = ... | multimodelity/modules/decoders.py | BSD-3-Clause | 2,735 | e618bba57455df5cb0f6596b0eaa357474abd1b1 | Python | py | |
"""Attention modules for RNN."""
import math
import six
import torch
import torch.nn.functional as F
from espnet_pytorch_library.nets_utils import make_pad_mask
from espnet_pytorch_library.nets_utils import to_device
def _apply_attention_constraint(
e, last_attended_idx, backward_window=1, forward_window=3
):
... | espnet_pytorch_library/rnn/attentions.py | Apache-2.0 | 67,003 | 3ad5ff1d70d0e67289bece59bca80e70da4f1c55 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
from .networks.msra_resnet import get_pose_net
from .networks.dlav0 import get_pose_net as get_dlav0
from .networks.pose_dla_dcn import get_pose_net as get_dla_dcn
from .networks.resnet_dcn import... | src/lib/models/model.py | MIT | 4,950 | ffb807adbcc47df1ef3ad0e630b817c169d8053d | Python | py | |
# pylint: disable=C, R, not-callable, no-member, arguments-differ
from functools import partial
import torch
from e3nn.non_linearities import GatedBlock
from e3nn.point.operations import Convolution
from e3nn.non_linearities.rescaled_act import relu, sigmoid
from e3nn.kernel_mod import Kernel
from e3nn.radial import ... | examples/point/tetris.py | MIT | 3,382 | 3ad627516134e905cafa12b996152dd17b120beb | Python | py | |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
Schelling coordination game:
Two spies, Alice and Bob, want to meet.
They must choose between two locations without communicating
by recursively reasoning about one another.
Taken from: http://forestdb.org/models/schelling.ht... | examples/rsa/schelling.py | Apache-2.0 | 2,836 | 5e658cca073a0c3756852c6be79ec0e01ed01ada | Python | py | |
import math
import torch
import torch.nn as nn
from models.neural import MultiHeadedAttention, PositionwiseFeedForward
class Classifier(nn.Module):
def __init__(self, hidden_size):
super(Classifier, self).__init__()
self.linear1 = nn.Linear(hidden_size, 1)
self.sigmoid = nn.Sigmoid()
... | src/models/encoder.py | MIT | 5,353 | fde6ed098c554e472114ebdbc58dcb6b284b600f | Python | py | |
import copy
import csv
import itertools
import json
import logging
import yaml
from collections import defaultdict
import pandas as pd
import numpy as np
from scipy.optimize import linear_sum_assignment
from tqdm import tqdm
from yacs.config import CfgNode as CN
from tao.toolkit.tao import Tao, TaoEval, TaoResults
fr... | tao/tao/utils/evaluation.py | MIT | 24,098 | 3ad63fe406012f92e256c621c4aa0387751d53a0 | Python | py | |
"""
Copyright (c) 2019-2022 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 w... | tests/torch/test_algo_common.py | Apache-2.0 | 13,831 | 1e7b016ac1d6c63253f7d0428fef1fb61b3c2f47 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from inference.models.quantized_grasp_model import GraspModelQuantized, ResidualBlockQuantized
class GenerativeResnet(GraspModelQuantized):
def __init__(self, input_channels=4, output_channels=1, channel_size=32, dropout=False, prob=0.0):
super(Genera... | inference/models/grconvnet3_quant.py | BSD-3-Clause | 3,565 | 03c2825e1dcb21075a887cbac3a9717594031a36 | Python | py | |
import cv2
import torch
import numpy as np
from torch.utils import data
from config import config
from utils.img_utils import random_scale, random_mirror, normalize, \
generate_random_crop_pos, random_crop_pad_to_shape
class TrainPre(object):
def __init__(self, img_mean, img_std, target_size):
self.i... | model/pspnet/ade.pspnet.R50_v1c/dataloader.py | MIT | 2,338 | 4233c86d22e50aeb1d033c42b2725ee912c6c494 | Python | py | |
import torch
from torch import nn
import torch.distributions as dist
import torch.nn.functional as F
class VAE_layer(nn.Module):
'''simple layer to make latent space operations '''
def __init__(self, d_model, device):
super(VAE_layer, self).__init__()
self.d_model = d_model
... | models/transformer/vae_layer.py | MIT | 812 | 5fb39c7fcb6b73ff3823ffab804a5333bfd145de | Python | py | |
from __future__ import division
import os
import cv2
import torch
from src.head_detector_vgg16 import Head_Detector_VGG16
from trainer import Head_Detector_Trainer
from PIL import Image
import numpy as np
from data.dataset import preprocess
import matplotlib.pyplot as plt
import src.array_tool as at
from src.vis_too... | head_detection_demo.py | MIT | 3,068 | d7d179a4f291f841b950384d2daae7bd79432de9 | Python | py | |
import torch
import open3d
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import itertools
import imageio
from torch.autograd import Variable
from src.utils import point_cloud_utils as pcu
from sklearn.metrics import confusion_matrix
def weights_init(m):
classname = m.__class__.__n... | FastAutoAugment/utils/utils.py | MIT | 26,845 | fcacbde3bba335a6b61bda2101f46d6c3839fe23 | Python | py | |
import torch
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
import pickle
import pandas as pd
import numpy as np
import h5py
class CallHomeDataset(Dataset):
def __init__(self, path, stance, part="dev", acproject=False, acfset="eGeMAPSv01a"):
print("PART", part, acp... | DialogueRNN/dataloader.py | MIT | 10,938 | 3ad6a9a4fb27644890c17201b2c7e09dbb0e8934 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
class MLP(nn.Module):
def __init__(self, feature_size, hidden_dim, num_class=None, num_layer=2, adv=False, adv_lambda=1.):
super(MLP, self).__init__()
try:
in_features = self.compute_i... | networks/mlp.py | MIT | 1,465 | f9aac8fb783103e966b90decd774490fde4978d7 | Python | py | |
# 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.
import math
from typing import Dict, List, Optional
import torch
import torch.nn as nn
from fairseq import search, utils
from fairseq.data im... | fairseq/sequence_generator.py | MIT | 39,636 | ff45c7dfb767fc16bc0fd2b79a67fdbe8ad39a6d | Python | py | |
"""
Taken from ESPNet, modified by Florian Lux
"""
import os
from abc import ABC
import torch
def cumsum_durations(durations):
out = [0]
for duration in durations:
out.append(duration + out[-1])
centers = list()
for index, _ in enumerate(out):
if index + 1 < len(out):
cen... | Utility/utils.py | Apache-2.0 | 9,853 | 5fa60ebea1b4c9b50c1c0ca49644867699b2ddf2 | Python | py | |
"""The data layer used during training to train a Fast R-CNN network.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.utils.data as data
from PIL import Image
import torch
from model.utils.config import cfg
from roi_data_layer.minibatch im... | lib/roi_data_layer/roibatchLoader.py | MIT | 10,136 | 702b780696efb08bc80dae3e80080ab7333c3170 | Python | py | |
# -*- coding: utf8 -*-
"""
======================================
Project Name: NLP
File Name: kg_globalpointer
Author: czh
Create Date: 2022/2/10
--------------------------------------
Change Activity:
======================================
"""
import os
import sys
import json
import codecs
import... | experiments/relation_extraction/kg_globalpointer.py | MIT | 18,594 | 3ad729123b3a4cfe02c47cf48edab5ad58233470 | Python | py | |
import random
import torch
import torch.nn as nn
from torch.nn.functional import one_hot
from common.optim import ParamOptim
class PredictorModel(nn.Module):
def __init__(self, rnn_size):
super(PredictorModel, self).__init__()
self.rnn_size = rnn_size
self.encoder = nn.Sequential(nn.Linear... | pol/predictor.py | MIT | 3,742 | f9c2ccb7da300a6a935aebad0bcd3e00ebfaf756 | Python | py | |
from typing import Optional
import torch
import torch.nn.functional as F
from kornia.geometry.linalg import transform_points
from kornia.geometry.conversions import (
convert_points_to_homogeneous, convert_points_from_homogeneous
)
def project_points(
point_3d: torch.Tensor,
camera_matrix: torch... | kornia/geometry/camera/perspective.py | ECL-2.0,Apache-2.0 | 5,257 | 3ad7339b71402d92ed30c758afb123f6a9b9eb3e | Python | py | |
import math
import torch
from torch import nn
from torch.nn import functional as F
from utils.net import make_conv
from models.ops import Conv2d, ConvTranspose2d, interpolate, Scale
from rcnn.modeling import registry
from rcnn.core.config import cfg
@registry.ROI_HIER_OUTPUTS.register("hier_output")
class Hier_outp... | rcnn/modeling/hier_rcnn/outputs.py | MIT | 4,737 | 3ad759af64e6d8d0c11097877a0be27181834bf4 | Python | py | |
#!/usr/bin/env python3
import os
import gym
import ptan
import argparse
from tensorboardX import SummaryWriter
import torch
import torch.nn.utils as nn_utils
import torch.nn.functional as F
import torch.optim as optim
import torch.multiprocessing as mp
from lib import common
GAMMA = 0.99
LEARNING_RATE = 0.001
ENTROP... | z_externals/handson_second_edition/Chapter13/02_a3c_grad.py | MIT | 5,672 | 28f37f2fb442580014ae8bc2c97e22da54b221f4 | Python | py | |
"""
The main separation by localization inference algorithm
"""
import argparse
import os
from collections import namedtuple
import librosa
import torch
import torch.nn.functional as F
import numpy as np
import soundfile as sf
import cos.helpers.utils as utils
from cos.helpers.constants import ALL_WINDOW_SIZES, \
... | cos/inference/separation_by_localization.py | MIT | 10,086 | b2387a469fa572ddfbd85775b65c874fa94db575 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2018-19: Homework 4
sanity_check.py: sanity checks for assignment 4
Sahil Chopra <schopra8@stanford.edu>
Michael Hahn <>
Usage:
sanity_check.py 1d
sanity_check.py 1e
sanity_check.py 1f
"""
import math
import sys
import pickle
import time
import n... | courses/cs224n/hw/a4/sanity_check.py | MIT | 9,231 | 3ad7a08f93f88b1ae4a5344570effc65289a98e1 | Python | py | |
from visual import Logger
import os
import os.path as osp
import time
import numpy as np
import random
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.init as init
from torch.autograd import Variable
import torch.utils.data as dat... | trainer.py | Apache-2.0 | 38,281 | 3ad7bde300059a3bb134dbf1943552b78b043005 | Python | py | |
import torch
from mmedit.models.backbones import DeepFillEncoderDecoder, GLEncoderDecoder
from mmedit.models.components import DeepFillRefiner
def test_deepfill_encdec():
encdec = DeepFillEncoderDecoder()
assert isinstance(encdec.stage1, GLEncoderDecoder)
assert isinstance(encdec.stage2, DeepFillRefiner)
... | tests/test_deepfill_encdec.py | Apache-2.0 | 912 | f9e6ace2ebed1a9180b904b02482be44c59cfa56 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.