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 |
|---|---|---|---|---|---|---|---|
'''Bayesian Normal distribution with prior over the mean and
covariance matrix.
'''
import abc
import math
import torch
from .bayesmodel import BayesianParameter
from .bayesmodel import BayesianModel
from ..priors import IsotropicNormalGammaPrior
from ..priors import NormalGammaPrior
from ..priors import NormalWisha... | beer/models/normal.py | MIT | 8,979 | 3a961c5eb2d3f5bad99f1813cbaca1363e7a036f | Python | py | |
from ._registry import DATASETS
from torch_geometric.datasets import ModelNet as PyGModelNet
import torch_geometric.transforms as T
@DATASETS.register
class ModelNet(PyGModelNet):
def __init__(self, root='data/ModelNet', name='40', train=True):
# Default setting
pre_transform = T.NormalizeScale()
... | datasets/modelnet.py | MIT | 548 | 1e67ea834f3dcb958c2c8eec5c8fba5e3c864cf2 | Python | py | |
import torch
import numpy as np
import argparse
from model import train
def main(params):
train(argparse.Namespace(**{\
"mini_batch": params["mini_batch"],
"dataset": params["dataset"],
"model": params["model"],
"dim_word": params["dim_word"],
"ctx_dim": params["ctx_dim"],
"mini_batch": par... | MultiEsenNIC/train_model.py | MIT | 2,183 | 3a968af5b937b785576d0042940edf9aed453d6c | Python | py | |
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
class Strategy:
def __init__(self, dataset, net):
self.dataset = dataset
self.net = net
def query(self, n):
pass
def update(self, pos_idxs, neg_idxs=... | query_strategies/strategy.py | MIT | 1,188 | 3a96ba61671c59697d65e754a373756509698cb4 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Conv1d, ConvTranspose1d
from torch.nn.utils import weight_norm, remove_weight_norm
LRELU_SLOPE = 0.1
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.wei... | hifigan/models.py | MIT | 5,630 | 5f828f6ec76b22fcd90cb35105f31bb7d7e36a61 | Python | py | |
import torch
a = torch.randn(2, 2)
a = ((a * 3) / (a - 1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b = (a * a).sum()
print(b.requires_grad)
print(b.grad_fn)
b = b.detach()
print(b)
x = torch.ones(2, 2, requires_grad=True)
print(x)
y = x + 2
print(y)
z = y * y * 3
out = z.mean()
print(z,... | 00-60-minute-blitz/grad.py | MIT | 642 | 3a9726e6e110193ded4590a2b1363588910229d8 | Python | py | |
# file for handling image inputs (images from web and dataset for training)
# see https://towardsdatascience.com/building-efficient-custom-datasets-in-pytorch-2563b946fd9f
import torch
import numpy as np
from PIL import Image
from torch.utils.data.dataset import Dataset
class ImageData(Dataset):
""" Class to rep... | client/custom_model/image_processing.py | MIT | 1,539 | dfaf3c9f10b5e01db329150a04e75884e4078ef3 | Python | py | |
import os
import torch
import torchvision as tv
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
import argparse
import skimage.data
import skimage.io
import skimage.transform
import numpy as np
import matplotlib.pyplot as plt
from torchvision import models
from torch.nn im... | featuremap.py | MIT | 8,551 | 3a97707fdbfa5a99afde5b3ae9e3abf151eb6a1b | Python | py | |
import shutil
import torch
import torch.optim as optim
from monodepth.models import MidasNet, MidasNetSearch
from monodepth.optim.optimizer import MGDA, GDA
from monodepth.validation import Validation
from monodepth.utils.checkpointer import Checkpointer, load_json, save_args
from monodepth.utils.reporter import Repor... | nasws/cnn/search_space/monodepth/params/search-decoder-v1/retrain_resnext101_wsl.py | MIT | 4,986 | f9fabe0dc5cd9e2ae0436b4b9a605958805b766e | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
COCO dataset which returns image_id for evaluation.
Mostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py
"""
from pathlib import Path
import torch
import torch.utils.data
import torchvision
f... | datasets/coco.py | Apache-2.0 | 5,251 | 3a9798d3909bd688bba5146344f6c0aaff67c2d4 | Python | py | |
from setuptools import setup, find_packages
import unittest
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
CUDA_FLAGS = []
INSTALL_REQUIREMENTS = []
def test_all():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover('tests', pattern='test_*.py')
return test_suite
... | lib/neural_renderer/setup.py | MIT | 1,363 | fceb501a633256065cc8d60bfafc36abdeba4f8f | Python | py | |
import os
import json
import torch
from torch.multiprocessing import Process
from lighter.context import Context
from lighter.loader import Loader
class ContextBuilder(object):
"""
Is used to create a proper context object for running an experiment with the current
"""
def __init__(self,
... | lighter/scheduler.py | BSD-3-Clause | 4,856 | 3a97eade36ffc71fb776180fd9bcecbaad2aecd5 | Python | py | |
import torch
import torchtestcase
import unittest
import copy
from survae.tests.nn import ModuleTest
from survae.nn.layers.autoregressive import SpatialMaskedConv2d, MaskedConv2d
class SpatialMaskedConv2dTest(ModuleTest):
def test_layer_is_well_behaved(self):
batch_size = 10
shape = (2,8,8)
... | survae/tests/nn/layers/autoregressive/masked_conv_2d.py | MIT | 4,945 | 248da15930439a3981705ab529ebc7ff2f4bd9e0 | Python | py | |
import torch
from torch import nn
class ConvBlock(nn.Module):
def __init__(self, in_dim, out_dim, k=4, s=2, p=1, norm=True, non_linear='leaky_relu'):
super(ConvBlock, self).__init__()
layers = []
# Convolution Layer
layers += [nn.Conv3d(in_dim, out_dim, kernel_size=(k, k, k), stri... | molpro/models/bicycle_gan.py | Apache-2.0 | 7,135 | d78793ce0833efe5e50300786881b5a004c1fd9a | Python | py | |
# ---------------------------------------------------------------------------
# Unified Panoptic Segmentation Network
#
# Copyright (c) 2018-2019 Uber Technologies, Inc.
#
# Licensed under the Uber Non-Commercial License (the "License");
# you may not use this file except in compliance with the License.
# You may obtai... | data loader and processing/lib/utils/data_parallel.py | MIT | 6,466 | 5e6975eccba41af2220bb890beadd2b56caa1466 | Python | py | |
import pickle
import numpy as np
import pytest
import torch
from torch import nn
from garage.envs import GarageEnv
from garage.torch.q_functions import ContinuousMLPQFunction
from tests.fixtures.envs.dummy import DummyBoxEnv
class TestContinuousNNQFunction:
# yapf: disable
@pytest.mark.parametrize('hidden_s... | tests/garage/torch/q_functions/test_continuous_mlp_q_function.py | MIT | 3,242 | 8019d241a931d13910b7b6bef4e11f8722de8843 | Python | py | |
import torch
import torch.nn as nn
from attr import asdict
from allrank.models.transformer import make_transformer
from allrank.utils.python_utils import instantiate_class
def first_arg_id(x, *y):
return x
class FCModel(nn.Module):
"""
This class represents a fully connected neural network model with g... | allrank/models/model.py | Apache-2.0 | 10,102 | 4b902d0fc9bd1905488fc564775ffb71495acb82 | Python | py | |
"""
This file handles the details of the loss function during training.
This includes: loss criterion, training statistics, and memory optimizations.
"""
import time
import sys
import math
import torch
import torch.nn as nn
from torch.autograd import Variable
import onmt
def NMTCriterion(vocabSize, opt, pad_id):
... | onmt/Loss.py | MIT | 6,019 | d766db0d20a185f93de53532e66d67072a39bf9f | Python | py | |
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '5'
import numpy as np, argparse, time, pickle, random
np.set_printoptions(threshold = np.inf)
import torch
import torch.nn as nn
import torch.optim as optim
from model import ERC_transfo_xl, ERC_xlnet
from sklearn.metrics import f1_score, confusion_matrix, accuracy_score,... | DialogXL/eval.py | Apache-2.0 | 5,477 | 421061d52c7b5d86d3aee0f1de78983c5a718034 | Python | py | |
import time
import torch
import torch.nn.functional as F
from torch.optim.optimizer import Optimizer
from torch.utils.data import Dataset
from torch.utils.tensorboard import SummaryWriter
from models.tacotron import Tacotron
from trainer.common import Averager, TTSSession
from utils import hparams as hp
from utils.ch... | trainer/taco_trainer.py | MIT | 6,984 | 3a98920f07411d65852529d5976adceaa961a607 | Python | py | |
import neptune
from torch import Tensor
from sonata.loggers import BaseLogger
class NeptuneLogger(BaseLogger):
def __init__(
self,
api_token,
project_name,
experiment_description=None,
experiment_name=None,
params=None,
):
se... | sonata/loggers/neptune_logger.py | MIT | 1,112 | 7c6591da1023ceadb2b4ed591a2da3d186116406 | Python | py | |
import random
import argparse
from typing import Union, Tuple
import numpy as np
import pandas as pd
import csv
import sys
import os
#os.environ['CUDA_VISIBLE_DEVICES'] = '6'
import __init__
from utils.dataloader import DataLoader
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Ten... | hec_gnn/single_model/main.py | MIT | 21,444 | 3a98993cfc56a8109fb028e0d01c358cfac56dff | Python | py | |
import os
import numpy as np
from torch.utils.data import Dataset
class P3B3(Dataset):
"""P3B3 Synthetic Dataset.
Args:
root: str
Root directory of dataset where CANDLE loads P3B3 data.
partition: str
dataset partition to be loaded.
Must be either 'train' ... | common/darts/datasets/p3b3.py | MIT | 3,016 | 3a98b9cd7d571ca51fc0dd1f419e071c97392294 | Python | py | |
import argparse
import torch
def get_args():
parser = argparse.ArgumentParser(description="RL")
parser.add_argument(
"--algo", default="ppo", help="algorithm to use: a2c | ppo | acktr"
)
parser.add_argument(
"--gail",
action="store_true",
default=False,
help="d... | PPO/a2c_ppo_acktr/arguments.py | MIT | 5,233 | 1ed7efe10bf7b9f9e4bba5c0380ab85dd40b507c | Python | py | |
import torch
from matplotlib import pyplot as plt
import cv2
import os
import csv
class Analysis:
def __init__(self, px_source, px_target, inliers, reprojection, \
warp_time, result_path, vol, scene, cam, \
source_frame, target_frame, verbose=False):
self.verbose = v... | hypersim_multiview/analysis.py | MIT | 7,841 | dfaee2ca70b124a201b644ef36b654c8f4d4501b | Python | py | |
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... | pynet/utils.py | CECILL-B | 11,153 | 3a98e09918233a25e3044bbbd72a40cee4f0af23 | Python | py | |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | nnUNet/nnunet/training/network_training/network_trainer.py | MIT | 31,344 | 4ba2a26befff7713ffb6d824374db86a353f5ad9 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
from model.dcrnn_cell import DCGRUCell
import random
from base import BaseModel
class DCRNNEncoder(BaseModel):
def __init__(self, input_dim, adj_mat, max_diffusion_step,... | model/dcrnn_model.py | MIT | 9,824 | 3a98f7c0a1f68947186fe412b726750e09708ce2 | Python | py | |
# Copyright 2019 The Texar Authors. 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 required by applicable ... | texar/torch/modules/pretrained/pretrained_gpt2.py | Apache-2.0 | 11,411 | 127f1738dbb6d5155d3b74f74b97322202da8c13 | Python | py | |
# _*_ coding: utf-8 _*_
"""
Author: Kwong
Create time: 2020/10/24 9:42
"""
import torch.nn as nn
import functools
import torch
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
from torchvision.models.resnet import ResNet
from torchvision.models.resnet import BasicBlock
from torchvisi... | Backbone/resnet.py | MIT | 7,648 | 1e61357da3942d580113fa3368bfbe73f2930426 | Python | py | |
# Copyright (c) 2020. Hanchen Wang, hw501@cam.ac.uk
# Ref: https://github.com/yanx27/Pointnet_Pointnet2_pytorch/blob/master/models/pointnet_cls.py
import torch.nn as nn, torch.nn.functional as F
from pointnet_util import PointNetEncoder, feature_transform_regularizer
class get_model(nn.Module):
def __init__(self,... | OcCo_Torch/models/pointnet_cls.py | MIT | 1,305 | 3a992524d265fe997f9af1686ccbf5ba818e2ada | 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.
from typing import Dict, List, Optional
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.modules import LayerNorm, M... | fairseq/modules/transformer_layer.py | MIT | 16,314 | 037d8e88aeb0e82e224fe3290ee337bb89e48e48 | Python | py | |
# We retain the copyright notice by NVIDIA from the original code. However, we
# we reserve our rights on the modifications based on the original code.
#
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution a... | train.py | MIT | 8,814 | 7cbc2e1ea324430ce0f53c952004ce352c563161 | Python | py | |
import base64
import os
import pickle
import random
import re
import string
import subprocess
import threading
from typing import Tuple
from requests.exceptions import ConnectTimeout
import wandb
import torch
def is_set(name: str) -> bool:
"""Helper method to check if given property is set, anything except missin... | util.py | Unlicense | 5,342 | 3a994251b25dc5271cd489a9376f287ccadc1dc4 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from maskrcnn_benchmark import _C
# from apex import amp
class _ROIPool(Functi... | openks/models/pytorch/mmd_modules/det_sgg/maskrcnn_benchmark/layers/roi_pool.py | Apache-2.0 | 1,904 | b26eda9d7ff22d1d11a470fc682f19fb88cfa718 | Python | py | |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-01-06 16:12
from typing import List
from elit.common.dataset import SortingSamplerBuilder
from elit.common.transform import NormalizeToken
from elit.components.mtl.loss_balancer import MovingAverageBalancer
from elit.components.mtl.multi_task_learning import MultiTa... | stem_cell_hypothesis/en_electra_base/joint/ner_srl.py | Apache-2.0 | 4,864 | 3a99547d30eb6bd2f8fb6100b7e90d4a053f304e | Python | py | |
import cPickle as pickle
import shutil
from os import listdir
import os
from os.path import join
import torch
import gtd
from gtd.ml.torch.utils import RandomState
class TrainState(object):
def __init__(self, model, optimizer, train_steps, random_state, max_grad_norm):
"""Construct a snapshot of trainin... | Model Codes/RetrieveEdit/gtd/ml/torch/checkpoints.py | CC-BY-4.0 | 5,264 | e668906d691b052554b43a770ce5100263cc7d5b | Python | py | |
import argparse
import logging
import sys
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
import wandb
from torch import optim
from torch.utils.data import DataLoader, random_split
from tqdm import tqdm
from utils.data_loading import BasicDataset, CarvanaDataset
from utils.... | Pytorch-UNet-classification-segmentation/fyp_train.py | MIT | 9,172 | d789abe33a838642c4d0d001ecbd27ab7d95e100 | Python | py | |
import torch
from torch.optim import Optimizer
class PerAvgOptimizer(Optimizer):
def __init__(self, params, lr):
defaults = dict(lr=lr)
super(PerAvgOptimizer, self).__init__(params, defaults)
def step(self, beta=0):
for group in self.param_groups:
for p in group['params']:... | system/flcore/optimizers/fedoptimizer.py | MIT | 4,348 | 3a997180c36b090743bab877de65997239e8afaa | Python | py | |
import numpy as np
import torch
import torch.nn as nn
from models.modules import thops
from models.modules.ActNorm import ActNorm2d
class LinearZeros(nn.Linear):
def __init__(self, in_channels, out_channels, logscale_factor=3):
super().__init__(in_channels, out_channels)
self.logscale_factor = lo... | models/modules/layers.py | MIT | 5,606 | 5e1eaee6c2b587c695b8994e503cac3f3b29e145 | Python | py | |
import os
from functools import partial
import torch
from adv_lib.attacks import alma, ddn
from adv_lib.attacks.auto_pgd import minimal_apgd
from adv_lib.attacks.perceptual_color_attacks import perc_al
from adv_lib.distances.color_difference import ciede2000_loss
from adv_lib.distances.lpips import LPIPS
from adv_lib.... | minimal_attack_imagenet.py | BSD-3-Clause | 4,005 | cc21b58661a41f98435c50f783cfa1a641316734 | 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/trainer/configuration_validator.py | Apache-2.0 | 15,276 | 3a99cb3778e65be6b539471afb8a786bf793cc6a | Python | py | |
# MIT License
# Copyright (c) 2018 the NJUNLP groups.
# 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
# to use, copy, modify, me... | dss_vae/decoder/att_nonauto_decoder.py | Apache-2.0 | 5,690 | 3a99d3ab13ee991ea3b04df5d264d6a00ec23f00 | Python | py | |
import argparse
import utility
import matplotlib.pyplot as plt
import json
import torch
import numpy as np
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from collections import OrderedDict
from PIL import Image
def get_input_args():
... | predict.py | MIT | 1,441 | 10d22941f94abd9b7dc6d049f13c8d493571f767 | Python | py | |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
def compute_cl(s_1, s_2):
"""
Compute weights from s_1 and s_2
:param s_1: 1*1 conv layer
:param s_2: 3*3 conv layer
:return: new weight and bias
"""
if isinstance(s_1, nn.Conv2d):
w_s_1 = s_1.weig... | tests/expand_net.py | Apache-2.0,MIT | 6,785 | f930f23b36d8f142d99dfa99516ec7cd86201a36 | Python | py | |
from ..functional.sublevel import SubLevelSetDiagram
from topologylayer.functional.persistence import SimplicialComplex
from topologylayer.util.construction import unique_simplices
import torch
import torch.nn as nn
import numpy as np
from scipy.spatial import Delaunay
import itertools
class LevelSetLayer(nn.Module)... | topologylayer/nn/levelset.py | MIT | 6,225 | 3a99e2284e881c3fb2f3865c38812ab621bffd63 | Python | py | |
import os
from torch.utils.data import Dataset
from PIL import Image
import processing.processing_utils as pu
from data.config import *
import processing.augmentation as pa
class CarvanaDataset(Dataset):
"""Kaggle Carvana dataset."""
def __init__(self, im_dir,
ids_list=None,
... | src/data/data_utils.py | MIT | 3,070 | 03f174b40cf140e5fa84e4ec34f9f668f51c923a | Python | py | |
from pathlib import Path
from datetime import datetime
import pandas as pd
from tqdm import tqdm
from PIL import Image
import torch
from torch.utils.data import DataLoader
from torchvision.transforms import functional as tf
import util
from model import CCPDRegressor
class CCPDTest:
def __init__(self, img_dir, ... | exp1/test.py | MIT | 1,869 | 28d2fcc3c8e63929907bebcaa9c21b72ca98ebdb | Python | py | |
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from maskrcnn_benchmark import _C
# TODO: Use JIT to replace CUDA implementation in the future.
class _SigmoidFocalLoss(Function):
@staticmethod
def forward(ctx, logits, targets, gamma... | maskrcnn_benchmark/layers/sigmoid_focal_loss.py | MIT | 2,504 | 3a9a24c860b9b940873c760974a3eb2fb4d2e424 | Python | py | |
import torch
from torchfm.layer import FeaturesLinear, FieldAwareFactorizationMachine
class FieldAwareFactorizationMachineModel(torch.nn.Module):
"""
A pytorch implementation of Field-aware Factorization Machine.
Reference:
Y Juan, et al. Field-aware Factorization Machines for CTR Prediction, 20... | torchfm/model/ffm.py | MIT | 809 | 3a9a3996a64867764b2a49878b508d67fab4324d | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import math
from typing import List, Optional, Dict, Any, Tuple, cast, ... | torchrec/distributed/sharding/twrw_sharding.py | BSD-3-Clause | 20,884 | 4597620aa45850a51212fae24c774c94cc1abf02 | Python | py | |
import torch.nn as nn
import torchvision.transforms as transforms
import torch.utils as utils
import torchvision
import torch
import torch.optim as optim
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
import argparse
import time
transforms = transforms.Compose([transforms.Resize... | pytorch/pytorch_solution.py | MIT | 6,538 | 3a9a409335b58e2bc19ac12dcaf6749c018c68ec | Python | py | |
import torch
import math
from rlpyt.distributions.base import Distribution
from rlpyt.utils.collections import namedarraytuple
from rlpyt.utils.tensor import valid_mean
EPS = 1e-8
DistInfo = namedarraytuple("DistInfo", ["mean"])
DistInfoStd = namedarraytuple("DistInfoStd", ["mean", "log_std"])
class Gaussian(Dist... | rlpyt/distributions/gaussian.py | MIT | 10,296 | 03c37c466693caae1e70ab90efcd4bbde480e338 | 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/trainer/legacy_deprecate_flow_log_tests/test_eval_loop_dict_return.py | Apache-2.0 | 10,526 | 3a9a87f84e5d929289bc9b074980e18882c5a22e | Python | py | |
#label list
import torch
user_idlist = torch.load('user_idlist.pt').tolist()
print(user_idlist[0])
label_dict = {}
f = open('label.txt')
for line in f:
temp = line.split(' ')
label_dict[int(temp[1])] = int(temp[2])
label_list = []
count = 0
for id in user_idlist:
try:
label_list.app... | data processing/label_list.py | MIT | 485 | 3a9a8b6b37199b5c2f5a44a0353e176e09031947 | Python | py | |
import pathlib
import re
from typing import Any, Dict, List, Tuple, BinaryIO, Union
import numpy as np
from torchdata.datapipes.iter import (
IterDataPipe,
Mapper,
Filter,
IterKeyZipper,
)
from torchvision.prototype.datasets.utils import Dataset, GDriveResource, OnlineResource
from torchvision.prototyp... | torchvision/prototype/datasets/_builtin/caltech.py | BSD-3-Clause | 6,832 | 3a9a8f08d41d137559f4fe66024ae4c7050d3796 | Python | py | |
# Copyright 2019 The Texar Authors. 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 required by applicable ... | data_utils/rl_data_utils_128.py | MIT | 6,961 | 3a9a9ba2d9425ac38571696debf7c20226e4181e | Python | py | |
import logging
import os
from functools import partial
from itertools import combinations
from operator import is_not
from typing import Any, Dict, List, Optional, Tuple, Union
from ipdb import set_trace as bp
import numpy as np
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.common.f... | neural_persona/models/partial-gen.py | Apache-2.0 | 20,588 | 3a9a9bfd188ee74b566672971f3ffa401f489301 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import numpy as np
import os
import sys
from PIL import Image
from cvxpy import *
from fancyimpute import SoftImpute, BiScaler
import tensorflow as tf
im... | attack_blackbox.py | MIT | 16,570 | 12ae8aa40da7c37dc6f3a072d599d8fc76b2f372 | Python | py | |
import torch
from torch import tensor, rand
import pyro
import torch.distributions.constraints as constraints
import pyro.distributions as dist
def guide_rnn(category=None, input=None, n_characters=None):
___shape = {}
___shape['n_characters'] = ()
___shape['input'] = n_characters
___shape['category'... | test/integration/dppl/target_py/lstm.py | BSD-3-Clause | 5,063 | 10f85d1c14da734e5f444bf91e8988fe21217b69 | Python | py | |
import torch
from torchvision import transforms as T
import cv2
from PIL import Image
model_name = "trained_models/signatrix_efficientdet_coco.pth"
model = torch.load(model_name).module
model.cuda()
img_path = "../dataset/photo10.png"
image = cv2.imread(img_path)
image = cv2.resize(image,(512,512))
img = cv2.cvtColor... | edgeai/test_det.py | MIT | 884 | d74880fc15623864ed19a413d52e4c64d65a9157 | Python | py | |
import os
from warnings import warn
import numpy as np
import torch
import torch.nn as nn
def get_activation_by_name(activation):
if activation == "leaky_relu":
return nn.LeakyReLU
elif activation == "relu":
return nn.ReLU
elif activation == "sigmoid":
return nn.Sigmoid
elif ac... | lasaft/utils/functions.py | MIT | 1,786 | 129870de64450c4128cad0c824146f79388ef762 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import os
import tempfile
import torch
from ml.rl.test.base.horizon_test_base import HorizonTestBase
from ml.rl.test.gridworld.gridworld_base import DISCOUNT, GridworldBase
from ml.rl.test.gridworld.gridworld_... | ml/rl/test/gridworld/gridworld_test_base.py | BSD-3-Clause | 3,315 | f97675d474478b7ee3eab86de837c6a5337f155e | Python | py | |
import os, math, collections, sys
import copy
import boto3
import numpy as np
import json
import subprocess
from io import StringIO
from types import SimpleNamespace
import logging
import shutil
import unicodedata
import tarfile
import tempfile
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
fr... | sagemaker-ngc-examples/Pytorch BYOM BERT for question-answering/transform_script.py | Apache-2.0 | 69,867 | 127707f3d46949f06eb7c53953b9a6414439e890 | Python | py | |
import torch
from robolearn.torch.policies import LinearGaussianPolicy
import matplotlib.pyplot as plt
batch_size = 5
obs_dim = 3
action_dim = 3
n_policies = 2
Tend = 5
Ts = 0.01
T = int(Tend/Ts)
time = torch.linspace(0, Tend-Ts, T)
des_obs_x = torch.sin(time)
des_obs_y = torch.cos(time)
des_obs_z = torch.cos(time*2... | examples/miscellaneous/test_lin_gauss_pol.py | BSD-3-Clause | 5,471 | 7c15fbfcb8c9bbcae6c617b6cc8c9a331a70c3bb | Python | py | |
# python3.7
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | third_party/stylegan2_official_ops/custom_ops.py | MIT | 6,650 | 4b9a8ef3ec71d144eed7584378546d7ccc183748 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.nn import init
from torch.nn.modules.utils import _pair, _triple
padding_mode = 'replicate' # ['replicate', 'zero']
class CrownConv2d(nn.Module):
def __init__(self, in_channels, out_channels... | models/crown_nn.py | MIT | 8,204 | 3a9b11edd7f456aec161e030d9dc7cc497c91a23 | Python | py | |
import torch, cv2
import numpy.random as random
import numpy as np
import dataloaders.helpers as helpers
class ScaleNRotate(object):
"""Scale (zoom-in, zoom-out) and Rotate the image and the ground truth.
Args:
two possibilities:
1. rots (tuple): (minimum, maximum) rotation angle
... | src/models/wisenet_base/packages/DEXTR/dataloaders/custom_transforms.py | Apache-2.0 | 10,323 | 12aaed529d5227104b49575b673a7e045ec83706 | Python | py | |
# python3.7
"""Contains the class of data loader."""
import argparse
from torch.utils.data import DataLoader
from .distributed_sampler import DistributedSampler
from .datasets import BaseDataset
__all__ = ['IterDataLoader']
class IterDataLoader(object):
"""Iteration-based data loader."""
def __init__(sel... | datasets/dataloaders.py | MIT | 4,258 | 3a9b31c4545233e9b0c0e134e627fa34dffe806f | Python | py | |
"""
ON THE HUMAN-RECOGNIZABILITY PHENOMENON OF ADVERSARIALLY TRAINED DEEP IMAGE CLASSIFIERS
Copyright 2020 Carnegie Mellon University.
NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE
MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO
WARRANTIES OF ANY KIND... | src/train_label_smoothing.py | MIT | 4,481 | 3a9b4719b7aceca4987e27505df7a5cd8a041d15 | Python | py | |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import json
import random
import shutil
import sys
import os
import torch
from torch.autograd import Variable
import... | Clevr/clevr-iep/scripts/run_model_h5.py | MIT | 10,798 | 6540929f1a7ed6a5491a872c1854b283d7ad8d37 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
the input x in both networks should be [o, g], where o is the observation and g is the goal.
"""
# define the actor network
class actor(nn.Module):
def __init__(self, env_params):
super(actor, self).__init__()
self.max_action ... | hindsight-experience-replay/rl_modules/models.py | MIT | 1,373 | 7ceaf46bc924c5c6cb32afeb46bc527ffe2b2df8 | Python | py | |
from typing import List, Tuple, Dict, Optional
import torch
import torchvision
from torch import nn, Tensor
from torchvision.transforms import functional as F
from torchvision.transforms import transforms as T, InterpolationMode
def _flip_coco_person_keypoints(kps, width):
flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7,... | references/detection/transforms.py | BSD-3-Clause | 12,895 | 3a9bad78c25cab1a0cc85224996c4b5f2bc468d5 | Python | py | |
from collections import namedtuple
from string import Template
import cupy
import torch
import cupy as cp
import torch as t
from torch.autograd import Function
from model.utils.roi_cupy import kernel_backward, kernel_forward
Stream = namedtuple('Stream', ['ptr'])
@cupy.util.memoize(for_each_device=True)
def load_ke... | model/roi_module.py | MIT | 4,301 | f93f2f6fdaf10e86e05bebcb3d1a52ec3ddd69a0 | Python | py | |
import torch
from egnn_pytorch import EGNN, EGNN_Sparse
from egnn_pytorch.utils import rot
torch.set_default_dtype(torch.float64)
def test_egnn_equivariance():
layer = EGNN(dim=512, edge_dim=4)
R = rot(*torch.rand(3))
T = torch.randn(1, 1, 3)
feats = torch.randn(1, 16, 512)
coors = torch.randn(... | tests/test_equivariance.py | MIT | 5,689 | 3a9bc90df8b206b2b0b6a9f7c45c8617cbc0880a | Python | py | |
""" Copy of https://github.com/pytorch/vision/blob/master/torchvision/transforms/functional.py
But for dict entries of the following format
{
'image': PIL.Image object,
'bbox' (optional): (x1, y1, x2, y2) coords,
'annotations' (optional): np.ndarray in shape (N, 5),
'mask' (optional): PIL.Image object,... | dataset_tools/transforms/functional.py | MIT | 10,229 | e9d301eda712df894f7fbe61ae2fbf7658debe77 | Python | py | |
import torch
import numpy as np
import argparse
import os
import sys
from utils import print_and_log, get_log_files, ValidationAccuracies, loss, aggregate_accuracy
from transductive_cnaps import TransductiveCnaps
from meta_dataset_reader import MetaDatasetReader
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Quiet TensorF... | transductive-cnaps-src/run_transductive_cnaps.py | MIT | 15,210 | 5e2de1366bb6806945d36f59421586306a48a943 | Python | py | |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/95_utils_test.ipynb (unless otherwise specified).
__all__ = ['synth_dbunch', 'RegModel', 'synth_learner']
#Cell
from ..torch_basics import *
from ..test import *
from ..layers import *
from ..data.pipeline import *
from ..data.source import *
from ..data.core import *
fr... | dev/local/utils/test.py | Apache-2.0 | 1,401 | f9572b932821fe78d57389aaec675a53bfdba38a | Python | py | |
# import
import torch.nn as nn
"""
I-Frame Feature Extractor
"""
class IFrameFeatExtractor(nn.Module):
def __init__(self):
super(IFrameFeatExtractor, self).__init__()
self.conv_64 = nn.Sequential(
# H x W
nn.Conv2d(
in_channels=3,
out_c... | video_networks/pf_video_auto/if_feat_ext.py | CC0-1.0 | 1,948 | 5eba95b86827a302005606b3797be0a1d1babab3 | Python | py | |
import torch
import torch.nn as nn
import time, pdb
import numpy as np
from util import py_softmax,MovingAverage
from multigpu import gpu_mul_Ax, gpu_mul_xA, aggreg_multi_gpu, gpu_mul_AB
def cpu_sk(o1):
""" Sinkhorn Knopp optimization on CPU
* stores activations to RAM
* does matrix-vector multip... | sinkhornknopp_multi.py | MIT | 7,379 | dffb071c87c10a8b7fe42438a35b7928f3988324 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
class ImageResizeTransform:
"""
Transform that converts frames loaded from a dataset
(RGB data in NHWC channel order, typically uint8) to a format ready to be
consumed by DensePose training (BGR float32 data in NCHW c... | projects/DensePose/densepose/data/transform/image.py | Apache-2.0 | 1,480 | ff9de52601ae2acf52ac80245e697e3065100fb9 | Python | py | |
from torch import nn
from ..init import init_bn
class FC(nn.Module):
"""Applies a linear transformation to the incoming data
optionally followed by batch normalization and relu activation
Attributes:
fc (nn.Module): linear module
bn (nn.Module): batch normalization module
relu (n... | multi_model/utils/pn2_utils/nn/modules/linear.py | MIT | 1,208 | 652a53abc072ec2c5a9ef7f5fefef7563846bc97 | Python | py | |
"""Test GNN layers."""
from typing import Any, MutableMapping
import torch
import unittest_templates
from mphrqe.layer.gnn import StarEConvLayer
class StarEConvLayerTests(unittest_templates.GenericTestCase[StarEConvLayer]):
"""Tests for the StarE convolution layer."""
cls = StarEConvLayer
num_entities... | tests/test_layers.py | MIT | 2,214 | f9d2e60aa543a2061859074d8d282d754ea18b2a | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .batch_norm import FrozenBatchNorm2d
from .misc import Conv2d
from .misc import DFConv2d
from .misc import ConvTranspose2d
from .misc import BatchNorm2d
from .misc import interpolate
from .nms import nms, hnms, MultiHashNMSAnyKPt... | maskrcnn_benchmark/layers/__init__.py | MIT | 1,391 | 3a9c0c427a63fb94ab747dc0d209d961a85b6730 | Python | py | |
import argparse
from datetime import datetime
import random
import torch
from agent import Agent
from env import Env
from memory import ReplayMemory
from test import test
parser = argparse.ArgumentParser(description='Rainbow')
parser.add_argument('--seed', type=int, default=123, help='Random seed')
parser.add_argume... | main.py | MIT | 7,278 | 3a9c12369da572aea52425038a6ac8f6d9dd6cbf | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
class GCELoss(nn.Module):
def __init__(self, q=0.7, k=0.5, trainset_size=50000, num_classes=2):
super(GCELoss, self).__init__()
self.q = q
self.k = k
self.weight = torch.nn.Parameter(d... | GCE/GCEloss.py | MIT | 1,573 | ff746569ffebaecdfbe84a97e4175016870c22a7 | Python | py | |
from tqdm import tqdm
import net as nn
import torch
import pydicom
import pylibjpeg
from PIL import Image as im
from PIL import ImageDraw
import numpy as np
import cv2
from ipywidgets import *
import xnat
net = nn.Net()
net.load_weights('trained_data.npy')
def input_image(file):
bboxes = []
ds = pydicom.dcmr... | input_image.py | Apache-2.0 | 1,920 | 3a9c24e786def7c9fe48115bdd66d63bda141685 | Python | py | |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... | electra_pyt/run_pretrain.py | BSD-3-Clause | 33,483 | cc01598d92b6302d0bee32e876b6b846b6a7d28b | Python | py | |
from pyro.nn import PyroSample, PyroModule
from torch.utils.data import Dataset, DataLoader
import torch
import torch.nn as nn
import pyro
from pyro.nn import PyroModule, PyroSample, pyro_method
import matplotlib.pyplot as plt
import logging
import pyro.distributions as dist
import copy
import random
class RandomSyst... | code_eide_et_al21/agents.py | Apache-2.0 | 869 | 3a9c477008fe8ce298ea4b57d18f67c72ce320cc | Python | py | |
import os
import re
import functools
import fnmatch
import numpy as np
import torch
import math
import torch.optim as optim
from torch.optim.optimizer import Optimizer
def find_recursive(root_dir, ext='.jpg'):
files = []
for root, dirnames, filenames in os.walk(root_dir):
for filename in fnmatch.filte... | utils.py | BSD-3-Clause | 6,858 | 3a9c5d3aeb19c95dc8b8c7930ab726186f6600e9 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch.nn as nn
class LSTMEncoder(nn.Module):
def __init__(
self, input_dim=None, hidden_dim=1024, num_layers=1, lstm=None,
):
"""LSTMEncoder encodes input vector using LSTM cells.
Attributes:
input_dim: Size of inp... | fairmotion/models/encoders.py | BSD-3-Clause | 1,263 | 3a9c62648ee96b1abf566252e453f749a9304165 | Python | py | |
from __future__ import print_function
import math
import sys
from glob import glob
import json
import copy
import torch as t
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn.functional as F
from torch.autograd import Variable
import data
from utils import *... | trainer.py | MIT | 18,594 | 3a9c67ff9eca58d38d4b3949577d6901124524ce | Python | py | |
import torch
import torch.nn as nn
from torchvision import models
class InpaintingLoss(nn.Module):
def __init__(self, extractor, tv_loss='mean'):
super(InpaintingLoss, self).__init__()
self.tv_loss = tv_loss
self.l1 = nn.L1Loss()
# default extractor is VGG16
self.extractor ... | application/pconv/loss.py | Apache-2.0 | 5,415 | 7c957d07ea9baf761e82d16971731988d4c7bba3 | Python | py | |
import numpy as np
import torch
import gym
import random
import math
import time
from src.models import MDPnet, QNet, TerminalClassifier
from src.config import cartpole_config
from src.memory import *
from src.utils import *
from src.train_pipeline import *
from collections import deque
# if gpu is to be used
use_cud... | parameter_searching_cartpole.py | MIT | 10,536 | f98b5a1c044d093f9d3dbca0fa162687d9182358 | Python | py | |
from copy import deepcopy
from typing import Dict, List
import numpy
import torch
from allennlp.common.util import JsonDict, sanitize
from allennlp.data.fields import TextField
from allennlp.data.token_indexers import (
ELMoTokenCharactersIndexer,
TokenCharactersIndexer,
SingleIdTokenIndexer,
)
from allen... | allennlp/interpret/attackers/hotflip.py | Apache-2.0 | 18,577 | 3a9ca1dcb6b4b28d7bee5f4ebe02f4ac7473138c | Python | py | |
r"""PyTorch Detection Training.
To run in a multi-gpu environment, use the distributed launcher::
python -m torch.distributed.launch --nproc_per_node=$NGPU --use_env \
train.py ... --world-size $NGPU
The default hyperparameters are tuned for training on 8 gpus and 2 images per gpu.
--lr 0.02 --batch-... | Train/python/train.py | Unlicense | 8,265 | 3a9cb0ec0c77b3a599ec2cdbbc04caefc240eadf | Python | py | |
# -*- encoding: utf-8 -*-
"""
@File : mbv2_ca.py
@Time : 2021/6/3 18:22
@Author : Zhl
@Desc :
"""
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
__all__ = ['mbv2_ca']
from torch.backends import cudnn
class ConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_p... | nets/mbv2_ca.py | MIT | 7,497 | b27dcf4b19613a5d600b3ad2ffc4622f79d221a2 | Python | py | |
import torch
from torch import nn
class LabelSmoothingLoss(nn.Module):
def __init__(self, num_classes: int, smoothing: float = 0.0,
dim: int = -1):
super(LabelSmoothingLoss, self).__init__()
self.smoothing = smoothing
self.confidence = 1.0 - self.smoothing
self.num... | interactive_spectrogram_inpainting/utils/losses/prediction.py | MIT | 770 | e9262732fc83ce39890f4337bb928436ea94b91b | Python | py | |
from __future__ import print_function, division
import time
import numpy as np
from scipy.ndimage.morphology import distance_transform_cdt
from scipy.ndimage import label as scipy_label
from scipy.ndimage.morphology import binary_erosion
from scipy.ndimage.interpolation import shift
import scipy.spatial as sp
import ... | torch_connectomics/data/dataset/dataset_mask_dualInput.py | MIT | 8,647 | 457ea323ad54e8291ec58e4bcd3ab52478d6b78a | Python | py | |
import functools
import os
import numpy as np
import torch
from pytorch_lightning import Trainer
from torch import nn
import torch.nn.functional as F
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader, random_split
from torchvision import transforms
import pytorch_lightning as pl
import ev... | train4.py | MIT | 2,991 | 5fa42449a3d15918e2e9b32f30e09ddb5ad917ce | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.