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 torch from scripts.study_case.ID_4.torch_geometric.nn.conv import MessagePassing from scripts.study_case.ID_4.torch_geometric.utils import remove_self_loops, add_self_loops from ..inits import reset class PointConv(MessagePassing): r"""The PointNet set layer from the `"PointNet: Deep Learning on Point Set...
scripts/study_case/ID_4/torch_geometric/nn/conv/point_conv.py
Apache-2.0
3,377
f957c1e9f0e1ab30dfe883a67179675a8c10a487
Python
py
#!/usr/bin/python # -*- encoding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as modelzoo # from modules.bn import InPlaceABNSync as BatchNorm2d resnet18_url = 'https://download.pytorch.org/models/resnet18-5c106cde.pth' def conv3x3(in_planes, out_planes...
models/face_part_seg/resnet.py
BSD-3-Clause
3,761
dfa114960c5103c47ef06e906ab20e44c67cfce5
Python
py
import torch from .module import Module from torch.nn.parameter import Parameter from .. import functional as F from .. import init # TODO: check contiguous in THNN # TODO: use separate backend functions? class _BatchNorm(Module): _version = 2 def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=T...
torch/nn/modules/batchnorm.py
BSD-3-Clause
13,649
cc1d0f1a142018e119dbf1df1b475546ee186c96
Python
py
"""model.py - Model and module class for EfficientNet. They are built to mirror those in the official TensorFlow implementation. """ # Author: lukemelas (github username) # Github repo: https://github.com/lukemelas/EfficientNet-PyTorch # With adjustments and added comments by workingcoder (github username). import...
efficientnet_pytorch/model.py
Apache-2.0
15,066
7c6f6551375f2ceaa0ccf8af8b5a239d07e9d2eb
Python
py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import numpy as np import torch class CutoutCustom: """ Reference : https://github.com/quark0/darts/blob/master/cnn/utils.py """ def __init__(self, length): self.length = length def __call__(self, img)...
archai/datasets/transforms/cutout_custom.py
MIT
829
fed4cc65f3dd55574cb8cc15c4d7de77a0e1a745
Python
py
import os import argparse import numpy import pyro_models from pyro_models.utils import json_file_to_mem_format from utils import save, load from model_constants import model_constants import pyro.poutine as poutine from pyro.infer.mcmc import MCMC, NUTS from pyro.infer.abstract_infer import TracePredictive import t...
run_nuts.py
MIT
4,355
fed4d343a72656944f5765aca0a6b8d449882816
Python
py
from torch import nn class ShapeClassMaskRCNNC4Predictor(nn.Module): def __init__(self, config, pretrained=None): super(ShapeClassMaskRCNNC4Predictor, self).__init__() stage_index = 4 stage2_relative_factor = 2 ** (stage_index - 1) res2_out_channels = config.MODEL.RESNETS.RES2_OUT...
maskrcnn_benchmark/modeling/roi_heads/shape_class_head/roi_shape_class_predictors.py
MIT
1,161
fed4ebb80de208864986a1e79bbf0464dd3ffd03
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...
sample-apps/segmentation_spleen/lib/train.py
Apache-2.0
3,490
5e81394192f585b5b9be923fa1ac503f0b500069
Python
py
import numpy as np import torch from ignite.engine import Engine def mixup_data(x, y, alpha=1.0, use_cuda=True): '''Returns mixed inputs, pairs of targets, and lambda''' if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = x.size()[0] if use_cuda: ...
oneshot/mixup.py
BSD-3-Clause
3,227
458f2395a325673aac7e399bed22ecb16b14f728
Python
py
# MIT License # # Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho # # 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...
openspeech/models/deepspeech2/model.py
Apache-2.0,MIT
5,042
fed53d0d97c574dfdd44e8701e15a8eea3f574b2
Python
py
from __future__ import absolute_import, division, print_function import logging import numpy as np import pytest import torch import torch.optim import pyro import pyro.distributions as dist import pyro.poutine as poutine from pyro.distributions.testing import fakes from pyro.infer import (SVI, JitTrace_ELBO, JitTra...
tests/infer/test_gradient.py
MIT
9,875
fed5464441475e6771861cb634003024dbe75e95
Python
py
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Also available under a BSD-style license. See LICENSE. import torch from torch_mlir_e2e_test.torchscript.framework imp...
python/torch_mlir_e2e_test/test_suite/elementwise_comparison.py
Apache-2.0
14,342
247dd8bc1659db9ba1e5ff356bce5f868e3895a1
Python
py
import torch.nn as nn from layers.autogcn_layer import AUTOGCNLayer from dgl.nn.pytorch.conv import SGConv from layers.mlp_readout_layer import MLPReadout import dgl import torch.nn.functional as F import torch class AUTOGCNNet(nn.Module): def __init__(self, net_params): super().__init__() in_di...
nets/SBMs_node_classification/autogcn_net.py
MIT
2,384
fed5a822d3275c52007b0d43aadbb243e5324784
Python
py
import torch import pandas as pd import numpy as np import os from torch.utils.data import Dataset from time import time __author__ = "Junhao Wen" __copyright__ = "Copyright 2018 The Aramis Lab Team" __credits__ = ["Junhao Wen"] __license__ = "See LICENSE.txt file" __version__ = "0.1.0" __maintainer__ = "Junhao Wen" _...
clinicadl/clinicadl/patch_level/utils.py
MIT
32,572
fed5b6c265d4c01260bfee7b4ec9529185da617f
Python
py
from collections import Counter, OrderedDict import torch import torch.utils.data as data_utils import torch.autograd as autograd import torch.nn as nn import torch.optim as optim from allennlp.modules import FeedForward import torch.nn.functional as F from torch.autograd import Variable from torch.nn.utils.clip_grad...
src/modules/hierarchical_document_classifier.py
BSD-3-Clause
14,936
fed5b839299a714a6a4fc920e07f92772c6150be
Python
py
import unittest import torch from leanai.core.indexed_tensor_helpers import * class TestIndexedTensorHelpers(unittest.TestCase): def setUp(self) -> None: pass def test_map_per_batch(self): values = torch.tensor([1, 2, 3, 4, 5]) indices = torch.tensor([0, 0, 1, 1, 2]) def fun(s...
tests/core/test_indexed_tensor_helpers.py
MIT
1,272
d7b7b6eac41f9b094bfc19b39139444a897e3c55
Python
py
import sys sys.path.append('../../') import time import torch from dataGen import train_loader, test_loader from neurasp import NeurASP from network import Sudoku_Net startTime = time.time() ###################################### # The NeurASP program can be written in the scope of ''' Rules ''' # It can also be wr...
NeurASP-master/examples/solvingSudoku_70k/test.py
Apache-2.0
1,609
340e262d2e981281c9d45f1e0e83706a8dc7d9cf
Python
py
import itertools import os import re from abc import ABC, abstractmethod from glob import glob from pathlib import Path import numpy as np import torch from PIL import Image from ..io.image import _read_png_16 from .utils import verify_str_arg from .vision import VisionDataset __all__ = ( "KittiFlow", "Sint...
torchvision/datasets/_optical_flow.py
BSD-3-Clause
15,376
7c728a5af8fd96e25db4a29229717d34756296fb
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. import torch import numpy as np import sys import os import ml3 from ml3.optimizee import ShapedSineModel from ml3.ml3_train import meta_train_shaped_sine as meta_train from ml3.learnable_losses import Ml3_loss_shaped_sine as Ml3_loss from ml3.ml3_test import test_ml3_...
ml3/experiments/run_shaped_sine_exp.py
MIT
3,015
4bc22de903100272385d41a91cfcba72214bc254
Python
py
import time import json import torch import logging import argparse from tqdm import tqdm from modules.multi_gras import MultiGraS from utils import test_rouge, rouge_results_to_str, output2doc_extractive from data_management.vocabulary import Vocabulary from data_management.data_loader import DataLoader logging.basi...
evaluate.py
MIT
3,790
5ebde0bdabb970b55059b80a7ec4318fbdb5eb8c
Python
py
from PIL import Image import numpy as np import torch import torchvision.transforms as transforms import torchvision.transforms.functional as F import torch.nn.functional as functional import torch.utils.data as data import random import time import scipy.io as scio import h5py import math import glob import os class ...
Phase2_Get_Weight_Fast/Dataset/DatasetConstructor.py
MIT
9,435
80525c1fa1fbfb0a08f77cb30b3461d6f6192591
Python
py
import torch.nn as nn class BidirectionalLSTM(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(BidirectionalLSTM, self).__init__() self.rnn = nn.LSTM(input_size, hidden_size, bidirectional=True, batch_first=True) self.linear = nn.Linear(hidden_size * 2, output_s...
modules/sequence_modeling.py
MIT
762
e9d1f23a8899546b448e7efc503205fb808ecfdc
Python
py
from dataset import Dataset from PIL import Image, ImageFilter import torchvision.transforms as transforms import torch.utils.data as tdata import torch import numpy as np from os.path import join, dirname, realpath import os from matplotlib import pyplot as plt class HeartDataset(Dataset): def __init__(self,...
dataset/dataset_HEART.py
MIT
3,007
45b94fd4399c3b8f39ab7e122d7e25d440181d7b
Python
py
import torch import math import random from PIL import Image try: import accimage except ImportError: accimage = None import numpy as np import numbers import types from collections.abc import Sequence, Iterable import warnings from . import functional as F __all__ = ["Compose", "ToTensor", "ToPILImage", "No...
torchvision/transforms/transforms.py
BSD-3-Clause
49,459
10783c8e53db6ec8cae3048922dd87777fa92662
Python
py
# coding=utf-8 # Copyright 2021 The IDEA 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 a...
fengshen/models/megatron_t5/modeling_megatron_t5.py
Apache-2.0
90,005
340099cea7552e22ec76a764e1822991b36a6d7f
Python
py
from typing import List, Tuple import torch from pytorch_lightning import LightningModule from torch import nn import neodroidaudition.audio_utilities.torch_transforms class UNetConvBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int, kernel_size: int): super().__init__() self.conv = ...
neodroidaudition/classification/seperation/audio_unet.py
Apache-2.0
8,506
b25f2ec5b15699c5b713f2b03ea02fad6c492659
Python
py
from collections import OrderedDict import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from tests.base.datasets import TrialMNIST try: from test_tube import HyperOptArgumentParser except ImportError: # TODO: this should be discussed a...
tests/base/models.py
Apache-2.0
4,840
fed694891c2913afb8a4e8a2cc16619b0369835c
Python
py
# -*- coding: utf8 -*- """ ====================================== Project Name: NLP File Name: tplinker_plus_utils Author: czh Create Date: 2021/8/16 -------------------------------------- Change Activity: ====================================== """ import re import copy import json import os import...
nlp/utils/tplinker_plus_utils.py
MIT
42,927
e902692155e2a0c38304dfd0e89884250aab9b31
Python
py
import torch from tqdm import tqdm @torch.no_grad() def predict(test_loader, model, n_samples=20, apply_softmax=True, return_targets=False, delta=1, n_data=None): py = [] targets = [] count = 0 for x, y in test_loader: if n_data is not None and count >= n_data: break x, y...
laplace/util.py
MIT
763
d7b35997a7c7daba80545f3034352d485c28ee61
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 os import pathlib from argparse import ArgumentParser import pytorch_lightning as pl from fastmri.data.mri_data import fetch_dir from...
fastmri_examples/unet/unet_knee_mc_leaderboard_20201111.py
Fair,MIT
6,022
fed6e7f42cd0922561aa5b72298ed318686e921c
Python
py
import itertools from collections import Counter import coloredlogs import logging import torch from sklearn import metrics import numpy as np logger = logging.getLogger('MajorityClassifier Log') coloredlogs.install(logger=logger, level='DEBUG', fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s') class Maj...
models/majority_classifier.py
MIT
2,655
7c56d8a500c80c1ff813c226c3994e9f00063016
Python
py
# standard library imports import os import math from math import sqrt, pi # package imports import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.normal import Normal from torch.distributions.gamma import Gamma from torch.distributions.multivariate_normal impor...
src/bnn/networks/sparse.py
MIT
64,370
5f8629c6a6222648d5b64256004f7a29aac3eca9
Python
py
"""Discrete CNN Q Function.""" import torch from torch import nn from garage.torch.modules import DiscreteCNNModule # pytorch v1.6 issue, see https://github.com/pytorch/pytorch/issues/42305 # pylint: disable=abstract-method class DiscreteCNNQFunction(DiscreteCNNModule): """Discrete CNN Q Function. A Q netwo...
src/garage/torch/q_functions/discrete_cnn_q_function.py
MIT
5,605
6b27d77a9857d9f3c2b45f607e9b9db5258c8171
Python
py
from torch.nn import GRU, LSTM import torch from torch import nn import numpy as np from speechjoey.encoders import RecurrentEncoder from .test_helpers import TensorTestCase from speechjoey.model import build_model from speechjoey.vocabulary import Vocabulary import copy class TestModelInit(TensorTestCase): def...
test/unit/test_model_init.py
MIT
1,971
03ac0ff38cceea2d04d255909a7c274fc6a000f8
Python
py
import torch import torch.nn as nn import torchvision.transforms.functional as T from torchvision.transforms import ToTensor, Lambda, Normalize, Compose, Resize from ..transforms import transform, scale_factor, scale_size from ..utils import bbox2result from PIL import Image class RetinaNet(nn.Module): def __ini...
models/detectors/retinanet.py
Apache-2.0
1,320
3441c442448bd948cd3beb1c14c7f2dd9096a9e1
Python
py
from torch import nn from torch.nn import functional as F from collections import OrderedDict __all__ = ["FCN"] class _SimpleSegmentationModel(nn.Module): __constants__ = ['aux_classifier'] def __init__(self, backbone, classifier, aux_classifier=None): super(_SimpleSegmentationModel, self).__init__()...
segmentation/fcn.py
MIT
2,501
4268404a11a24570abbd723332358f20cc0ec88d
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...
monai/networks/blocks/aspp.py
Apache-2.0
3,774
d7dedbf3097623dd77094f3d9f7fc3fba9b321c9
Python
py
import os from datetime import timedelta import torch.distributed as c10d from torch.autograd import Variable import torch torch.manual_seed(2048) import random random.seed(2048) import numpy as np np.random.seed(2048) from distseq.training import LSTransformerEncoderLayer local_rank = int(os.environ.get("LOCAL_RAN...
test_dist.py
Apache-2.0
1,459
d713434cc442c6533243d720f3425767fb04dab6
Python
py
import torch import albumentations as A from albumentations.pytorch import ToTensorV2 from tqdm import tqdm import torch.nn as nn import torch.optim as optim from model import UNET from utils import ( load_checkpoint, save_checkpoint, get_loaders, check_accuracy, save_predictions_as_imgs, ) # Hyper...
ML/Pytorch/image_segmentation/semantic_segmentation_unet/train.py
MIT
3,204
fed782af579a792ffec18ac191557516e2f68d81
Python
py
#! /usr/bin/env python # Copyright (c) 2019 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
ludwig/features/vector_feature.py
Apache-2.0
8,177
fed78620712d86a0b2df5d0f25173dd32bf59597
Python
py
from __future__ import print_function, absolute_import import argparse import os.path as osp import numpy as np import sys sys.path.append('./') import torch import torch.nn.functional as F from torch import nn from torch.backends import cudnn from torch.utils.data import DataLoader from torch.autograd import Variabl...
examples/main.py
MIT
11,740
429df41f98ceb49d9671e5dae508d073f48d750a
Python
py
# -------------------------------------------------------- # Pytorch Multi-GPU Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Jiasen Lu, Jianwei Yang, based on code from Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import ...
testoid_net.py
MIT
13,803
7c6d0be929ed046a0ca912709300057cff347765
Python
py
import contextlib import json import logging import os from typing import Any, Dict, Optional from unittest import mock import pytest import torch import torch.nn.functional as F from torch import nn, Tensor from torch.optim import Optimizer from torch.utils.data import DataLoader from torchmetrics import Accuracy fr...
tests/plugins/test_deepspeed_plugin.py
Apache-2.0
40,659
fed7a11b3fae061333463432e7cfc85d8bf1d27c
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import math import warnings from typing import Sequence import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import (build_activation_layer, build_conv_layer, build_norm_layer, xavier_init) from mmcv.cnn.bricks....
mmdet/models/utils/transformer.py
Apache-2.0
45,983
fd71966f1b7f9cd266b43852fc18f79a945d4ecc
Python
py
"""Discrete Dueling CNN Module.""" import torch from torch import nn from garage.torch.modules import CNNModule, MLPModule # pytorch v1.6 issue, see https://github.com/pytorch/pytorch/issues/42305 # pylint: disable=abstract-method class DiscreteDuelingCNNModule(nn.Module): """Discrete Dueling CNN Module. A ...
src/garage/torch/modules/discrete_dueling_cnn_module.py
MIT
7,359
fed7eed4767ec84e33d0ec9facfe895bbb2081a1
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. import math import torch import torch.nn.functional as F from detectron2.layers import cat from detectron2.layers.roi_align_rotated import ROIAlignRotated from detectron2.modeling import poolers from detectron2.modeling.proposal_generator import rpn from detectron2.m...
detectron2/export/c10.py
Apache-2.0
20,860
ffb47c6cf19ae07f334b751ccadd071ebbd25e2e
Python
py
# DRL models from ElegantRL: https://github.com/AI4Finance-Foundation/ElegantRL import torch from elegantrl.agent import AgentDDPG from elegantrl.agent import AgentPPO from elegantrl.agent import AgentSAC from elegantrl.agent import AgentTD3 from elegantrl.config import Arguments # from elegantrl.agent import AgentA2C ...
finrl/drl_agents/elegantrl/models.py
MIT
4,762
420f7524d51b83430d79fb4cd2e0317448aaf23b
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import numpy as np import scipy as scp import logging import matplotlib.pyplot as plt from pyvision.logger import Logger from ast import literal_eval import torch import torch.nn as nn...
torchlab/evaluation/legacy/geoprod.py
MIT
20,842
4ba8df14b66429be04fa3378b41466c31910fefe
Python
py
import torch import torch.nn as nn from torchvision import models class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x class FashionClassifier(nn.Module): """ A model that will be used to classify the fashion images. ...
src/models/fashion_classifier.py
MIT
3,867
d768ba279bac215171eb3c327cb5552553d89ba6
Python
py
import torch import torch.nn as nn from torch.nn import functional as F import mmcv from mmcv.cnn import normal_init from mmdet.core import distance2bbox, force_fp32, multi_apply, matrix_nms from mmdet.ops import ConvModule, Scale from ..builder import build_loss from ..registry import HEADS from ..utils import bias_i...
mmdet/models/anchor_heads/condinst_head.py
Apache-2.0
24,862
706a823af6674828e6c3acefdbf53843febb0eb8
Python
py
# SOME AUXILIARY FUNCTION FOR CLEANER NOTEBOOKS import numpy as np import torch import matplotlib.pyplot as plt import seaborn as sns def top10_accuracy_scorer(gt_idx, top10_idx): aciertos = 0 for arr, gt in zip(top10_idx,gt_idx): if gt in arr: aciertos+=1 top_10_...
src/utils.py
MIT
1,430
fed84ef8fa6819d3296056df92acfe2b1e3d0385
Python
py
from pathlib import Path import torchvision.models as models import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from tqdm import tqdm import torch from sklearn.metrics import f1_score from time import perf_counter import argparse import os import sys import config import losses as L from ...
train.py
MIT
13,834
1e763642dfe80c328009d58a8d5eb6c67c3ebb27
Python
py
from __future__ import division from __future__ import print_function import argparse import random import importlib import numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm import tools.utils as utils #############################################################################...
infer.py
MIT
3,100
70035f32b21747771ecc78e3e84e06b1b6cb2062
Python
py
import unittest import cvxpy as cp import numpy as np import numpy.random as npr import torch from torch.autograd import grad from cvxpylayers.torch import CvxpyLayer import diffcp def set_seed(x): npr.seed(x) torch.manual_seed(x) def sigmoid(z): return 1 / (1 + np.exp(-z)) class TestCvxpyLayer(unit...
cvxpylayers/torch/test_cvxpylayer.py
Apache-2.0
11,523
2474c6a88b547711251e88477a062a6a99b6c7ae
Python
py
# 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 required by appli...
examples/speaker_recognition/speaker_reco.py
Apache-2.0
3,176
fed887a98dd9ed50cfea821817e1dcf63ca68f4a
Python
py
import argparse import torch from torchvision import transforms from retinanet import model from retinanet.dataloader import CSVDataset, Resizer, Normalizer from retinanet import csv_eval assert torch.__version__.split('.')[0] == '1' print('CUDA available: {}'.format(torch.cuda.is_available())) def main(args=None)...
csv_validation.py
Apache-2.0
1,942
6b3495c74da6a223a1b720c870479cda44a56824
Python
py
import sys import argparse import os import numpy as np import torch import torch.nn as nn from dataset import UrbanPlanningDataset from metrics import compute_mae, compute_mape, \ compute_ssi, compute_geh, compute_cpl, \ compute_cpc, compute_binned_metric, compute_macro_metric, mae_metric, \ mape_metric, ...
fc_regression_baseline.py
MIT
7,719
fed88e5cbd0ea5aa3659450b015b32edfcd9c5a6
Python
py
from vocoder.models.fatchord_version import WaveRNN from vocoder.vocoder_dataset import VocoderDataset, collate_vocoder from vocoder.distribution import discretized_mix_logistic_loss from vocoder.display import stream, simple_table from vocoder.gen_wavernn import gen_testset from torch.utils.data import DataLoader from...
vocoder/train.py
MIT
4,376
b2449f66ffe8fcb05e7c7aeccb502f70c6c114b5
Python
py
import copy import numpy as np import pytest from sklearn.datasets import load_digits from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import torch import torch.nn as nn from torch_shallow_neural_classifier import TorchShallowNeuralClassifier import utils from torch_model...
test/test_torch_model_base.py
Apache-2.0
4,901
7c2fc715c58e93d9f7647062721f93b0ff8bffff
Python
py
import os import torch import torch.optim as optim import torch.nn.functional as F from torchvision import datasets, transforms def train(rank, args, model, device, dataloader_kwargs): torch.manual_seed(args.seed + rank) train_loader = torch.utils.data.DataLoader( datasets.MNIST( "../data...
mnist_hogwild/train.py
BSD-3-Clause
3,026
12d151b61e7e363a10c9f8adb30281afb4923c76
Python
py
from ray_on_aml.core import Ray_On_AML from azureml.core import Run import numpy as np import torch import torch.optim as optim import torch.nn as nn from torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.nn.functional as F import ray.train.torch from ray import train from ra...
examples/distributed_dl/distributed_ml.py
MIT
2,320
fed8c18c3d1339c960c8aeae780ff666f6ab45b2
Python
py
import numpy as np # from numpy.lib.function_base import gradient import torch from torchvision import datasets, transforms, utils from models.Nets import CNNMnist from options import args_parser from client import * from server import * import copy import time def load_dataset(): trans_mnist = transforms.Compose(...
Lab2/ex2_v2/ex2_code/main.py
MIT
2,873
fed8c7e2d3f9641958b5ec1ebf51172ea4cbf780
Python
py
import os import torch import torch.nn as nn import torch.nn.functional as F from config import LABEL_MAP from model import Criterion, ISRScheduler from utils import convert_ids_to_tokens, safe_loss, process_outputs, get_bow_labels def train_generator(config, vocab, batch, model_G, model_D, optim_G, optim_D, seq_crite...
train.py
MIT
7,027
f9ded2c9f84904547b4a8d191d9a0b23d4cd067b
Python
py
import numpy as np import torch import cv2 import torch.nn as nn from dataloader import DataProcessor, ImbalancedDatasetSampler, threedpreprocess, ModDataProcessor, ModDataProcessor3slices, unsharp_transform from dataloader import remove_calcs, ModDataProcessor3slicesNoCalcs from torch.utils.data import DataLoader, ran...
Faster-RCNN/vocdata/model_class.py
MIT
28,311
fed8f47738e3a26543367a21114a1ac0b6041d94
Python
py
from collections import defaultdict from syft.frameworks.torch.mpc.primitives import PrimitiveStorage from syft.generic.utils import remote, allow_command import torch import syft RING_SIZE = 2 ** 32 ERR_MSG = "You must call PRZS.setup because the seeds where not shared between workers" class PRZS: def __init__...
syft/frameworks/torch/mpc/przs.py
Apache-2.0
4,884
7cae055494e6e901025c9454702b307ab7db0ecf
Python
py
import torch import numpy as np class ROptions: """ When search for the Lyapunov function, we use the 1-norm of |R*(x-x*)|₁. This class specificies the options to search for R. """ def __init__(self): pass def set_variable_value(self, R_val: np.ndarray): pass def R(self) ...
neural_network_lyapunov/r_options.py
MIT
8,895
fcb3d7cd719a268106a3c6bde97d553164d9dc13
Python
py
""" timg_discrim.py """ import torch import torch.nn as nn class Timg_Discrim(nn.Module): def __init__(self): super(Timg_Discrim, self).__init__() self.C = 64 # input is expected to be 512 x 512 # 5 layers of downsampling gets it down to 16 x 16 # self.conv1 = nn.Conv2d(1,...
scripts/experiment/__unfinished_gan_like_model/pytorch_stuff/models/timg_discrim.py
Apache-2.0
1,644
a93989b4fed3c7f9391870652bfd7e059bedf15b
Python
py
import copy import matplotlib.pyplot as plt import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.models as models import torchvision.transforms as transforms from PIL import Image class Normalization(nn.Module): def __init__(self, m...
neuralartstudio/image_style.py
MIT
11,484
5fb1aecb3f3c465cddea3126ede7d708bb6af772
Python
py
r"""Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter To support these two classes, in `./_utils` we define many utility methods and functions to be run in multiprocessing. E.g., the data loading worker loop is in `./_utils/worker.py`. """ import os import threading import iterto...
torch/utils/data/dataloader.py
Intel
67,430
fed94f7d8ee05e43c729343b090ee3eac1ddcd9f
Python
py
''' Script for training models. ''' from torch import optim import torch import torch.utils.data import argparse import torch.backends.cudnn as cudnn import random import json import sys # Import dataloaders import Data.cifar10 as cifar10 import Data.cifar100 as cifar100 import Data.tiny_imagenet as tiny_imagenet # ...
train.py
MIT
13,922
03f6b1a8d58d5bd8f7c3a838fc759f34132eec42
Python
py
from hydroDL.master import basins from hydroDL.app import waterQuality from hydroDL import kPath, utils from hydroDL.model import trainTS from hydroDL.data import gageII, usgs from hydroDL.post import axplot, figplot import torch import os import json import pandas as pd import numpy as np import matplotlib.pyplot as ...
app/waterQual/basinAll/basinRef_tsWRTDS.py
MIT
5,036
28bce4344300577b31a3ce6aba44c9f76c49134b
Python
py
import os import numpy as np import torch import lws from scipy import signal from autokeras.pretrained.base import Pretrained from autokeras.constant import Constant from autokeras.utils import temp_path_generator, ensure_dir, get_device import librosa from autokeras.pretrained.voice_generator.deepvoice3_pytorch im...
autokeras/pretrained/voice_generator/voice_generator.py
MIT
10,828
03e190fc6b85aa30afea327b92353f9e11a3765e
Python
py
import torch import numpy as np import os import sys import torch.nn.functional as F import torch.nn as nn from torch.autograd import Variable BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(BASE_DIR)) class get_transform(nn.Module): def __init__(self, num_classes=16): ...
models/model_seg.py
Apache-2.0
7,856
28e97d75a9055593f94a44ee5c20ca4b1d58c8aa
Python
py
import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import os import random import pandas as pd def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch...
utils.py
MIT
4,016
1e2583fd6f92c89a9a11c2fd8701a340aaa26548
Python
py
r""" Naive gate """ from .base_gate import BaseGate import torch import torch.nn as nn import torch.nn.functional as F import os import os.path as osp import errno # from megatron import print_rank_0 def mkdir_if_missing(dirname): """Creates dirname if it is missing.""" if not osp.exists(dirname): tr...
fmoe/gates/naive_gate.py
Apache-2.0
4,421
fed9bdd614767e5012374c58ea08735764dfd5c0
Python
py
""" Color space conversions ======================= In this tutorial we are going to learn how to convert image from different image spaces using `kornia.color`. """ from matplotlib import pyplot as plt import cv2 import numpy as np import torch import kornia import torchvision ############################# # We u...
examples/color_conversions.py
Apache-2.0
1,721
7c1550ada00ac4025155d44c1000910ab755cb21
Python
py
import torch import math def gelu_new(x): """ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415 """ return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (...
ablang/extra_fns.py
BSD-3-Clause
749
fed9c50484e9908e7694b78bc009a3f0868fea9b
Python
py
import torch from torch import nn from torch.autograd import Variable from torch.nn.parameter import Parameter from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from loss_scaler import DynamicLossScaler, LossScaler FLOAT_TYPES = (torch.FloatTensor, torch.cuda.FloatTensor) HALF_TYPES = (torch.H...
fp16_optimizer.py
BSD-3-Clause
17,381
5e0cef18a0d4f08af790a6c7d01c9a0b8eef8a2d
Python
py
import cv2 import torch import numpy as np MEANS = (104, 117, 123) def caffe_preprocessing(image, size, mean=MEANS): x = cv2.resize(image, (size, size)).astype(np.float32) x -= np.array(mean) x = x.astype(np.float32) return x def np_to_tensor(image): return torch.from_numpy(image).permute(2, ...
ssd/transforms/functional.py
MIT
395
12d0b3c4d51b656f61d7eb414f74a08816369a9c
Python
py
import warnings from typing import Dict, Tuple, Union import numpy as np import torch as th from gym import spaces from torch.nn import functional as F def is_image_space_channels_first(observation_space: spaces.Box) -> bool: """ Check if an image observation space (see ``is_image_space``) is channels-fi...
stable_baselines3/common/preprocessing.py
MIT
8,300
fed9ee6d5dc597d65e3bc7ab40a7972f8f840dff
Python
py
# Author - Abhinand --> https://github.com/abhinand5 # ===================================================================== # IMPORTS # ====================================================================== import torch from torchvision import transforms import os import sys from PIL import Image from model import ...
facemask_detector/detect_face_mask.py
MIT
1,547
a9173b74867d3fa61160f9c117be63d896860504
Python
py
import os import sys import torch import numpy as np from losses import lpips def to_scaled_tensor(imA): # convert to RGB, scale images and cast to pytorch Tensor # expected shape is Nx3xHxW # first convet to fake RGB imA = np.moveaxis(np.transpose(np.tile(np.expand_dims(imA,axis=-1), (1,1,1,3))),-1,0)...
src/metrics/lpips_metric.py
MIT
1,443
5e6227058ee95b5fc3e71dff610be7846ceb6970
Python
py
import torch.nn.functional as F import torch.nn as nn import torch from torch.autograd import Variable from base.common import * class BasePolicy(nn.Module): """ Base policy class """ def __init__(self, opts): # ---- Settings for policy network ---- super(BasePolicy, self).__init__() ...
base/base_policy.py
MIT
12,789
feda172bad66773da1079b69f970c038c7e8c3f1
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths import os import json import cv2 import numpy as np import time from progress.bar import Bar import torch from opts import opts from logger import Logger from utils.utils import AverageMete...
src/test.py
MIT
4,324
feda211d616ef451ee9e02277244b6b1a69f683a
Python
py
# Copyright 2018 Uber Technologies, Inc. All Rights Reserved. # Modifications 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.or...
test/test_torch.py
Apache-2.0
64,843
701c65b3ea74f18c75735bc16850ee0896041960
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pycocotools.coco as coco from pycocotools.cocoeval import COCOeval import numpy as np import json import os import torch.utils.data as data class COCOHP(data.Dataset): # num_classes =15#33 #1#24 chan...
src/lib/datasets/dataset/coco_hp.py
MIT
4,540
700faacd3caf01bcd5f077afae561eae4ab32517
Python
py
from datetime import timedelta import logging import threading import warnings from typing import Generator, Tuple import torch import torch.distributed as dist logger = logging.getLogger(__name__) _init_counter = 0 _init_counter_lock = threading.Lock() def is_available(): return hasattr(torch._C, "_rpc_init...
torch/distributed/rpc/__init__.py
Intel
9,041
1ed3b48939ae283582a238e4503c3cafadc1aed4
Python
py
""" Evaluation for mvtec_ad dataset. Reference from https://github.com/denguir/student-teacher-anomaly-detection. Author: Luyao Chen Date: 2020.10 """ import torch import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import transforms, datasets import cv2 import matplotlib.pyplot a...
evaluate.py
MIT
11,220
d7e22430d0afb02262aa469cb9a606bef037fd7b
Python
py
from dreamcoder.task import Task, EvaluationTimeout import gc from dreamcoder.utilities import * from collections import Counter import math from dreamcoder.domains.regex.groundtruthRegexes import gt_dict gt_dict = {"Data column no. " + str(num): r_str for num, r_str in gt_dict.items()} class AllOrNothingLikelihood...
dreamcoder/likelihoodModel.py
Unlicense
14,937
803ad8d3773251283be09bd95029d58d2a64675a
Python
py
from datetime import datetime from os import makedirs, path import torch.nn as nn import torch.utils.data from sklearn.metrics import (accuracy_score, balanced_accuracy_score, confusion_matrix, f1_score) from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from constrai...
code/experiments/_train_encoder_original.py
MIT
7,802
e9a2f85837d4a62b644dff7212ba5e37abaa2907
Python
py
from typing import Tuple, Union, List, Callable, Optional, cast import torch from torch.distributions import Uniform, Beta from functools import wraps from kornia.utils import _extract_device_dtype def _validate_input(f: Callable) -> Callable: r"""Validates the 2D input of the wrapped function. Args: ...
kornia/augmentation/utils/helpers.py
ECL-2.0,Apache-2.0
9,751
fcb6bcdcac27ae8733ec76a3a466b846b211a415
Python
py
#!/usr/bin/env python3 """PyTorch Inference Script An example inference script that outputs top-k class ids for images in a folder into a csv. Hacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman) """ import os import time import argparse import logging import numpy as np import torch from...
inference.py
Apache-2.0
5,236
1e99ea5bb482617886f99732129b39a16ff7543c
Python
py
import os from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F from core.config import cfg import nn as mynn import utils.net as net_utils from utils.resnet_weights_helper import convert_state_dict # -------------------------------------------------------------------...
lib/modeling/ResNet_bat.py
MIT
14,832
fedabaabc7e05f9b3cfbaed3a479d6cded47636a
Python
py
import numbers from typing import Callable, Optional, Sequence, Tuple, Union import torch from ignite.exceptions import NotComputableError from ignite.metrics.metric import Metric, reinit__is_reduced, sync_all_reduce from ignite.metrics.metrics_lambda import MetricsLambda __all__ = ["ConfusionMatrix", "mIoU", "IoU",...
ignite/metrics/confusion_matrix.py
BSD-3-Clause
16,766
fedabd1f1010a51bfb6ea380051f37ec68bfd971
Python
py
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import argparse import glob import numpy as np import os import shutil import time import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from sklearn.model_selection imp...
lab/wind_turbine.py
MIT-0
6,022
fedabea01fe484b96f6e950f799d0f9de339e927
Python
py
from torch import nn import torch import torch.nn.functional as F import math from einops import rearrange def multi_head_attention(Q, K, V, mask): """Multi-head attention on a batch of Q, K, V Arguments: Q: torch.Tensor shape (B, N, n_head, d_k) K: torch.Tensor shape (B, M, n_head, d_k) ...
src/architectures/transformer.py
MIT
8,441
45c39c4360e39b2361978f18e0f9cd88fc9578a8
Python
py
import shaDow.layers as layers from shaDow import TRAIN, VALID, TEST import numpy as np import torch import torch.nn.functional as F from torch import nn class DeepGNN(nn.Module): NAME2CLS = {"mlp" : layers.MLP, "gcn" : layers.GCN, "gin" : layers.GIN, "sage" ...
shaDow/models.py
MIT
9,306
fedaeffe331e4968a872b41ea4a9c63daa0857b9
Python
py
import torch.nn as nn class B(nn.Module): def __init__(self): super(B, self).__init__() a= nn.Sequential(nn.Conv2d(3,3,3),nn.Conv2d(3,3,3),nn.Conv2d(3,3,3)) b= nn.ReLU() c= nn.Conv2d(3,3,3) self.a=a self.b= b self.c=...
deblurgan/test.py
MIT
450
e99a84b67710569f3420b344d700e9111f4b1a9b
Python
py
import numpy as np import torch import torch.nn as nn from mmcv.cnn import Conv2d, Linear, MaxPool2d, kaiming_init, normal_init from mmcv.runner import force_fp32 from torch.nn.modules.utils import _pair from mmdet.models.builder import HEADS, build_loss @HEADS.register_module() class MaskIoUHead(nn.Module): """...
mmdet/models/roi_heads/mask_heads/maskiou_head.py
Apache-2.0
7,342
104d9b3186cbd17773e3b92884df11c5b6d966f2
Python
py
# Copyright (c) Facebook, Inc. and its 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 subprocess from typing import ClassVar from unittest import TestCase from etcd import EtcdKeyNotFound f...
test/distributed/elastic/rendezvous/etcd_rendezvous_backend_test.py
Intel
4,220
fedafdab7c5dd9554258fc9802181ee1a9228abe
Python
py