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 argparse
import datetime
import gym
import numpy as np
import itertools
import torch
from sac import SAC
#from torch.utils.tensorboard import SummaryWriter
from replay_memory import ReplayMemory
import os
parser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args')
parser.add_argument('--env-n... | main.py | MIT | 5,648 | d7266bd2c3c9bc58a6087848869977161584f42e | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("../")
import argparse
from torch.utils.data import DataLoader
from deeploglizer.models import Transformer
from deeploglizer.common.preprocess import FeatureExtractor
from deeploglizer.common.dataloader import load_sessions, log_dataset
from deep... | demo/transformer_demo.py | Apache-2.0 | 3,561 | 299076166549bbfa15607ce8b99293219569f7a3 | Python | py | |
#
# Copyright (c) 2021, NVIDIA 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 ... | tests/conftest.py | Apache-2.0 | 2,499 | 2990919f5487e7b3019b781ea681414e1c9a99e4 | Python | py | |
import os
import numpy as np
import pytest
import torch
import ignite.distributed as idist
from ignite.contrib.metrics.regression import GeometricMeanAbsoluteError
from ignite.engine import Engine
from ignite.exceptions import NotComputableError
def test_zero_sample():
m = GeometricMeanAbsoluteError()
with ... | tests/ignite/contrib/metrics/regression/test_geometric_mean_absolute_error.py | BSD-3-Clause | 8,915 | 299098697df38c84afbddd58a2c3b2f0f13dc148 | Python | py | |
"""Utility functions to help setup the model, optimizer, distributed compute, etc.
"""
import typing
import logging
from pathlib import Path
import sys
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader, RandomSampler, Dataset
from torch.utils.data.distributed import DistributedSampl... | tape/utils/setup_utils.py | BSD-3-Clause | 4,424 | d75f0e0b589e95f6fed888feb36fda454155c08d | Python | py | |
from __future__ import absolute_import
import math
import numpy as np
import sys
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import init
def conv3x3_block(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
conv_layer = nn.Conv2d(in_planes, out_planes, k... | lib/models/stn_head.py | MIT | 3,932 | d7f0f5631205769d33d400da39fca2e306eb60d8 | Python | py | |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from ddsp.synth import SynthModule
class Generator(SynthModule):
"""
Generic class for trainable signal generators.
"""
def __init__(self):
super(Generator, self).__init__()
self.apply(self.init_parameters)
de... | ddsp/generators.py | MIT | 2,904 | 2990c284914bae515c130b6f19c5b65b3cd91c3d | Python | py | |
import numpy as np
import torch
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from utils import seed_everything
from dataset import ImageDataset, get_transforms
from trainer import CycleGAN
from visualize import unnorm
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
''' ... | main.py | MIT | 1,866 | dfc34f06a4325f43ac49fd1f3efbcd29408e80a6 | Python | py | |
from typing import Tuple
import torch
from torch.optim.optimizer import Optimizer
from torch.nn import Module
from piepline.utils.utils import dict_recursive_bypass
from piepline.train_config.train_config import BaseTrainConfig
__all__ = ['DataProcessor', 'TrainDataProcessor']
class DataProcessor:
"""
Dat... | piepline/data_processor/data_processor.py | MIT | 9,006 | e91dedc0d1fd2bd4d672869049179346be3ba76f | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 08:30:20 2019
@author: nsde
"""
#%%
from data import two_moons
from sklearn.cluster import AgglomerativeClustering
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.distributions as D
#%%
class arg... | vae_cluster_apporch.py | MIT | 8,047 | 4b4f7b99ee8978e566c1735aa51b54e8d729c441 | Python | py | |
import math
from typing import Any, Tuple
import numpy as np
import torch
from pytorch_lightning import LightningDataModule
from torch import Tensor
from torch.utils.data import DataLoader, Dataset
from pl_bolts.utils import _SKLEARN_AVAILABLE
from pl_bolts.utils.warnings import warn_missing_pkg
if _SKLEARN_AVAILABL... | pl_bolts/datamodules/sklearn_datamodule.py | Apache-2.0 | 8,669 | 704f671c06f9073a3247732a068210d8dcf02ce9 | Python | py | |
"""Tests for net.py
Although NeuralNetClassifier is used in tests, test only functionality
that is general to NeuralNet class.
"""
from functools import partial
import pickle
from unittest.mock import Mock
from unittest.mock import patch
from pathlib import Path
import numpy as np
import pytest
from sklearn.metrics... | skorch/tests/test_net.py | BSD-3-Clause | 52,007 | d7f5ee055dd2cec6860ef91de8e8198e84f02aac | Python | py | |
"""
create model
Creator: Xiaoshui Huang
Date: 2020-06-19
"""
import torch
import numpy as np
from random import sample
import se_math.se3 as se3
import se_math.invmat as invmat
# a global function to flatten a feature
def flatten(x):
return x.view(x.size(0), -1)
# a global function to calculate max-pooling
de... | model.py | MIT | 18,235 | 299181123f157d3dce38cdcf99832a9682ad59a2 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import copy
from models.initialize import *
import random
from DataUtils.Common import *
from .muti_hands import positional_encoding
from models.muti_hands import multihead_attention, feedforward
torch.manual_seed(seed_num)
random.see... | models/Transformers.py | Apache-2.0 | 5,265 | 129abac44ded773e0841e52e2d6230da33b5878a | Python | py | |
import numpy as np
import torch
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import GridSearchCV
import results_manager as utils
import feature_selection as fsel
# Hyperparameters for gbr on mnist:
# n_estimators = 190, learning_rate = 0.046, max_depth = 5, subsample = 0.75
# Hy... | trajectories_dataset.py | MIT | 5,756 | f99409c469cca2f44eef4c637cb1718b897a2731 | Python | py | |
import unittest
import torch
from torch import Tensor
from pietoolbelt.metrics.torch.detection import _calc_boxes_areas, _compute_boxes_iou, f_beta_score, calc_tp_fp_fn
__all__ = ['PyTorchTest']
class PyTorchTest(unittest.TestCase):
def test_calc_boxes_areas(self):
boxes = torch.FloatTensor([[1, 1, 2, 2... | tests/metrics/torch/detection.py | MIT | 2,590 | 52be1c9f50f0be47ec549c1f21de8b38619acb32 | Python | py | |
import torch
from util import pad
from metrics import compute_metrics
def compute_validation_outputs(model, val_iter, field, optional_names=[]):
loss, predictions, answers = [], [], []
outputs = [[] for _ in range(len(optional_names))]
for batch_idx, batch in enumerate(val_iter):
l, p = model(batch... | validate.py | BSD-3-Clause | 4,276 | e62bd6b68899286db628689a858f07a128938085 | Python | py | |
import torch
from losses.style.style_loss import StyleLoss
class AlignLossBuilder(torch.nn.Module):
def __init__(self, opt):
super(AlignLossBuilder, self).__init__()
self.opt = opt
self.parsed_loss = [[opt.l2_lambda, "l2"], [opt.percept_lambda, "percep"]]
if opt.device == "cuda":
... | losses/align_loss.py | MIT | 1,612 | 2991bc3e58ffa944d6845f33ce2d5c00d945edd7 | Python | py | |
import torch
from torch.nn import Parameter
from torch_scatter import scatter_add
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.utils import add_self_loops
from ..inits import glorot, zeros
class GCNConv(MessagePassing):
r"""The graph convolutional operator from the `"Semi-supervised
... | torch_geometric/nn/conv/gcn_conv.py | MIT | 3,106 | 1e09cf02c1bee90b011699594ae7d1ccfe81cc0e | Python | py | |
"""Transducer speech recognition model (pytorch)."""
from argparse import Namespace
from collections import Counter
from dataclasses import asdict
import logging
import math
import numpy
import chainer
import torch
from espnet.nets.asr_interface import ASRInterface
from espnet.nets.pytorch_backend.ctc import ctc_for... | espnet/nets/pytorch_backend/e2e_asr_transducer_for_tt.py | Apache-2.0 | 20,062 | 4275292db3c961b9b3675e137e70a5810ed0f652 | Python | py | |
# Licensed under The MIT License [see LICENSE for details]
# based on code from Ross Girshick
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import sys
import numpy as n... | train_model.py | MIT | 19,233 | 5e18d447823a3a4c94d49bef9a8939213b09b417 | Python | py | |
"""
cnn + self-attention for 1-d signal data, pytorch version
Shenda Hong, Jan 2020
"""
import numpy as np
from collections import Counter
from tqdm import tqdm
from matplotlib import pyplot as plt
from sklearn.metrics import classification_report
import torch
import torch.nn as nn
import torch.optim... | model/acnn1d.py | Apache-2.0 | 3,699 | 12e807525ea067d124f4f6ba3867c64fe67d3bfc | Python | py | |
# importing libraries
from facenet_pytorch import MTCNN, InceptionResnetV1
import torch
from torchvision import datasets
from torch.utils.data import DataLoader
from PIL import Image
import cv2
import time
import os
# initializing MTCNN and InceptionResnetV1
print('1')
mtcnn0 = MTCNN(image_size=240, margin=0, keep_al... | reconocimiento.py | MIT | 3,646 | ff95bdb288e60a2e87296383e00d954282c52406 | Python | py | |
###########################################################################
# Searching for A Robust Neural Architecture in Four GPU Hours, CVPR 2019 #
###########################################################################
import torch
import torch.nn as nn
from copy import deepcopy
from .search_cells import N... | NAS/AngleNAS/NAS-Bench-201/lib/models/cell_searchs/search_model_gdas_nasnet.py | Apache-2.0 | 5,687 | 24edffd19331bed1a3c0430eb3c12a334621a13b | Python | py | |
# Copyright (c) 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. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import torch
import torch.nn as nn... | codes_src/fairseq/models/masked_lm_bert.py | Unlicense | 11,153 | 28dba63106317cdd6e667aa120bf4edf8b7c1757 | Python | py | |
import torch
from torch.utils.data import Dataset
from ..models import GaussianMixture
class GaussianMixtureDataset(Dataset):
"""
Gaussian Mixture Dataset as described in
`Revisiting Reweighted Wake-Sleep for Models with Stochastic Control Flow` [https://arxiv.org/abs/1805.10469]
"""
def __init_... | ovis/datasets/gmm.py | MIT | 942 | 423193c215889d7aea4ba443281f01281bcc76ac | Python | py | |
import torch
from torch.autograd import Variable
import torch.nn as nn
def cosine_sim(im, s):
"""Cosine similarity between all the image and sentence pairs
"""
return im.mm(s.t())
def order_sim(im, s):
"""Order embeddings similarity measure $max(0, s-im)$
"""
YmX = (s.unsqueeze(1).expand(s.... | loss.py | Apache-2.0 | 4,677 | 1ee07fbaf4cf925b1791ae0021f03f0081941890 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from timm.models.registry import register_model
from timm.models.vision_transformer import _cfg
__all__ = [
"pvt_tiny_256", "pvt_small_256", "pvt_mediu... | vtpack/models/standard/pvt.py | Apache-2.0 | 12,413 | 24f41c41d37ac1ec511b900da6cc609ca63da429 | Python | py | |
import torch
import torch.nn.functional as F
from torch.nn import Module, ModuleList, Dropout
from torch import optim
from graphgallery.nn.models import TorchKeras
from graphgallery.nn.layers.pytorch import GraphConvolution
from graphgallery.nn.metrics.pytorch import Accuracy
class GCN(TorchKeras):
def __init__... | graphgallery/nn/models/pytorch/gcn.py | MIT | 1,793 | 29923342b0daa66be0e62ef427cfa2c699e3d98a | Python | py | |
"""Implements the Uniform distribution."""
import math
from numbers import Number
import torch
from torch.autograd import Variable
from probtorch.distributions.distribution import *
from probtorch.util import expanded_size
__all__ = [
"Uniform"
]
class Uniform(Distribution):
r"""
Continuous uniform distr... | probtorch/distributions/uniform.py | Apache-2.0 | 2,641 | 2992375f8f77ae8d72cbf74c5e22493b53e3b145 | Python | py | |
# flake8: noqa
from tempfile import TemporaryDirectory
from pytest import mark
import torch
from torch.utils.data import DataLoader, TensorDataset
from catalyst import dl
from catalyst.settings import IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES, SETTINGS
def train_experiment(device, engine=None):
with TemporaryDirecto... | tests/pipelines/test_multilabel_classification.py | Apache-2.0 | 4,429 | 4b612ea0f96dbaf1b6dd5b4f4409d5ef5a73d9f1 | Python | py | |
'''LeNet in PyTorch.'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class MyLeNet(nn.Module):
def __init__(self):
super(MyLeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.... | models/Old/mylenet.py | MIT | 2,576 | 343fd69567ad8f5a46dc8816026e968a289f0813 | Python | py | |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2021-Present The THUAlign Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import glob
import time
import socket
import string
import shutil
import argparse
import subprocess
import numpy as ... | thualign/bin/inferrer.py | BSD-3-Clause | 21,682 | 299250b28b8524e889a43f2f8ebb1daf2b0cdd09 | Python | py | |
import os
import yaml
import json
import logging
import shortuuid
import copy
import torch
import argparse
import shutil
from dataclasses import dataclass
from typing import List, Dict
from socket import gethostname
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from... | megatron/neox_arguments/arguments.py | Apache-2.0 | 39,363 | 299265f8f1a87eb59903260c57098e61a74e4d95 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from copy import deepcopy
from typing import Any, Callable, List, Optional, Tuple, Union
import torch
import torch.nn as nn
from torch import Tensor
from combustion.nn import MatchShapes, MobileNetBlockConfig
class _MobileUnetMeta(type):
def __new__(cls: Any, name,... | src/combustion/models/mobile_unet.py | Apache-2.0 | 6,468 | 29926824dd73479e0882de517afa35fe5cbe5c21 | Python | py | |
import torch.utils.data
from depthaware.data.base_data_loader import BaseDataLoader
def CreateDataset(opt):
dataset = None
if opt.dataset_mode == 'nyuv2':
# from data.nyuv2_dataset import NYUDataset
from depthaware.data.nyuv2_dataset_crop import NYUDataset,NYUDataset_val
dataset = NYUD... | depthaware/data/custom_dataset_data_loader.py | MIT | 2,646 | 29927ac2ede4a28fda0cbad96ab097925b2030d2 | Python | py | |
import torch
def adv_loss(loss_type, t_config, device):
"""
Configures adverserial losses.
NOTE: Departure from this function being a class is really just done to save memory space, and
have it such that we don't always have to check in which case we fall everytime we want to evaluate the loss
... | losses/adversarial.py | MIT | 3,480 | 459919363390e41e27a50ff6894c12351c99bac5 | Python | py | |
import torch
import torch.nn as nn
'''class BasisModelTorch(nn.Module):
def __init__(self, nfunctions, scale, **kwargs):
super().__init__()
self._degree = nfunctions
#self._degree = nfunctions
self._scale = scale
self.register_buffer('_centers' ,torch.linspace(0.0, 1.01, sel... | torchTryOut.py | MIT | 1,681 | 2992b1e1b341c0b3d7212c53fb9544abe6f3790d | Python | py | |
# This file implements the WideResNet networks created by the authors of the Places365 Dataset.
# It was extracted from https://github.com/CSAILVision/places365 by Bolei Zhou
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet10... | pytorch_transfer_and_eval/wideresnet.py | MIT | 6,867 | fcd9db40906603cbffc6357ae3270b93477b347a | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from rfvision.models.builder import NECKS
@NECKS.register_module()
class GlobalAveragePooling(nn.Module):
"""Global Average Pooling neck.
Note that we use `view` to remove extra channel after pooling. We do not
use `squee... | rfvision/components/necks/gap_neck.py | Apache-2.0 | 1,240 | 2992c5ce220f36e6f78b55667e63c76a5cf19827 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Encoder definition."""
import logging
import torch
from espnet.nets.pytorch_backend.conformer.convolution import ConvolutionModule
from espnet.nets.pytorch_backend.conformer.... | espnet/nets/pytorch_backend/conformer/encoder.py | Apache-2.0 | 8,413 | 459556e38f80adfda83f10c80f9e88d97360b0bb | Python | py | |
import torch
from librosa.filters import mel as librosa_mel_fn
from audio_processing import dynamic_range_compression
from audio_processing import dynamic_range_decompression
from stft import STFT
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
supe... | layers.py | BSD-3-Clause | 3,725 | 5f400684ba9c35c464ae35c0adc4cf7f107578c4 | Python | py | |
# Copyright (c) 2017-present, Facebook, Inc.
# 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. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from parlai.core.agents im... | parlai/agents/coopgame_agent/coopgame_agent.py | BSD-3-Clause | 13,142 | 2992f5fdd61256940a5eba43c058f856c563ef27 | Python | py | |
import numpy as np
import torch
from lib.utilities import config
def random_board_batch(min_density, max_density, batch_size, device):
'''Creates random boards
Each board has players assigned to each position with probability p
where p is chosen uniformly at random from [min_density, max_density]
once for e... | pytorch-implementation/lib/pretraining/data.py | MIT | 1,596 | 45771f52934b8ab6fd7d8fcc69aad214bc4d1b42 | Python | py | |
import os
import csv
import datetime
from collections import namedtuple, defaultdict
import librosa
from copy import deepcopy
import queue
import random
from threading import Thread
from tqdm import tqdm
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch
... | task1_b_train.py | MIT | 16,915 | 299321bc2135dcdcb57ac5e0dfe6bb951c9dee14 | Python | py | |
import argparse
import warnings
from opts import add_decoder_args, add_inference_args
from utils import load_model
warnings.simplefilter('ignore')
from decoder import GreedyDecoder
import torch
from data.data_loader import SpectrogramParser
#from data_loaderWin import SpectrogramParser
from model import DeepSpeech... | transcribe_to_file.py | MIT | 4,280 | 4b4a8bf9ccb07bd91cf98bf1bef96ff10179c1a4 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# 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 logging
from pathlib import Path
import hydra
import torch
import torch.nn.functional as F
from torchvision import ... | pl_hydra/train.py | Unlicense | 3,180 | 299341499197dd7bb66c065deb9c010be3fb2ba0 | Python | py | |
# Copyright 2021 RangiLyu.
#
# 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, so... | tools/train.py | Apache-2.0 | 4,281 | 29935aceffac2052eee448b3f90b0106f3465f1e | Python | py | |
import torch
from rdkit import Chem
from dgllife.model import DGMG, DGLJTNNVAE
def test_dgmg():
model = DGMG(atom_types=['O', 'Cl', 'C', 'S', 'F', 'Br', 'N'],
bond_types=[Chem.rdchem.BondType.SINGLE,
Chem.rdchem.BondType.DOUBLE,
Chem.rdch... | apps/life_sci/tests/model/test_generative_models.py | Apache-2.0 | 1,446 | 29936cee962422a7f65110f5a068134f5453cace | Python | py | |
import datetime
import torch
from sklearn.metrics import precision_recall_fscore_support as prfs
from utils.parser import get_parser_with_args
from utils.helpers import (get_loaders, get_criterion,
load_model, initialize_metrics, get_mean_metrics,
set_metrics)
impor... | train.py | MIT | 7,010 | 299373d9c59332b6fd9916f7a1c75d3f69921d72 | Python | py | |
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class ShuffleAttention(nn.Module):
"""Constructs a Channel Spatial Group module.
Args:
k_size: Adaptive selection of kernel size
"""
def __init__(self, channel, groups=32):
super(ShuffleAttention, self).__init... | model/sa_attention.py | MIT | 1,674 | 1ec0f2bb2dd6cd3a67fe551397f08c58c3e16105 | Python | py | |
import csv
import os
import sys
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv3d, Module, Softmax, BatchNorm3d, BatchNorm2d, Conv2d, Dropout
from rand_walk_code import *
import random
import time
# Hyperparameters
num_epochs... | fast_jtnn/testfile.py | MIT | 5,883 | a9975de9766bd14e48fa524a988af0d8fd61c544 | Python | py | |
# Copyright (c) 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. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import torch
from fairseq import ... | fairseq/tasks/fairseq_task.py | MIT | 10,614 | 2993865dabd633853062af271d1e0088ac355211 | Python | py | |
import torch
from network.ocrnet import HRNet_Mscale
from loss.utils import CrossEntropyLoss2d
from torchvision.datasets import Cityscapes
import numpy as np
from torchvision import transforms
# ----- Global variables ----- #
batch_size = 1
val_batch_size = 1
num_gpus = torch.cuda.device_count()
device = torch.device... | multitask_depth_seg_sn/nicolas/train.py | MIT | 3,533 | 299388247f52d3c8c2775091434c39787fd50235 | Python | py | |
#!/usr/bin/env python
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, Namespace
from pathlib import Path
from typing import Optional
import cv2
import numpy as np
import torch
from config import Config, load_config
from dataloaders.loader import get_transform
from models.encoder import EncoderCNN
... | run.py | MIT | 7,869 | e9c62dcc9a099aeea7a24585ff64437f1ba50dd1 | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, 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 cop... | named-entity-recognition/run_ner.py | Apache-2.0 | 13,591 | 420a415b092976ec7e847fa184c6c95b721bf0c5 | Python | py | |
# pylint: disable=W0221
# pylint: disable=W0613
# pylint: disable=W0223
import argparse
from argparse import ArgumentParser
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_lightning.metrics import Accuracy
class IrisClassification(pl.LightningModule):
... | examples/IrisClassification/iris_classification.py | Apache-2.0 | 3,684 | e952ba33788fd9f8b58ce6bc173a0d9af0fcde4f | Python | py | |
from collections import Counter
import numpy as np
import torch
from pokemon_constants import AGENT_1_ID, AGENT_2_ID, NULL_ACTION_ID, STATE_DIM
class SharedInfo():
def __init__(self):
self.num_agents = 2
self.num_completed_battles = [0] * self.num_agents
self.reset()
def num_battles_... | pokemon/shared_info.py | MIT | 5,156 | 1ebcf3085fdd2d2e66f1fcd423f4bd2a1d27065d | Python | py | |
# load modules
import os
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import numpy as np
import models
import create_masks
import argparse
parser = argparse.ArgumentParser(description='Trainer code for masked resnet based on seed value')
parser.add_argument('--see... | Projects/Ensembling/CIFAR100/trainer_masked_resnet.py | Apache-2.0 | 3,595 | 428ad17ac5f4cffe203d3cb6e580df114ca16341 | Python | py | |
#!/usr/bin/env python
""" ImageNet Training Script
This is intended to be a lean and easily modifiable ImageNet training script that reproduces ImageNet
training results with some of the latest networks and training techniques. It favours canonical PyTorch
and standard Python style over trying to be able to 'do it all... | Imagenet_train/train.py | MIT | 34,786 | 2993f88c2a3842f51dba5e04183a4ccc7536916c | Python | py | |
# Modified from https://github.com/mathcbc/advGAN_pytorch/blob/master/main.py
import torch
from advGAN import AdvGAN
from target_models import MNIST_target_net
import utils
if __name__ == "__main__":
training_parameters = {
"EPOCHS": 60,
"BATCH_SIZE": 128,
"LEARNING_RATE": 0.001
}
... | train_advGAN_model.py | MIT | 2,762 | 7092890bd1071c81bfdd2ea17f734c159d23c2af | Python | py | |
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 PanXu, Inc. All Rights Reserved
#
"""
tensor 的工具
Authors: PanXu
Date: 2021/02/15 12:32:00
"""
import torch
def is_tensor_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, epsilon: float = 1e-9) -> bool:
"""
判断两个 tensor 是否相等, 如果两个 t... | easytext/utils/nn/tensor_util.py | MIT | 797 | 7076ad94364237d37823e51ca4871d9b894d5bbd | Python | py | |
from torch.utils import data
from torchvision import transforms as T
from torchvision.datasets import ImageFolder
from PIL import Image
import torch
import os
import random
from data.sparse_molecular_dataset import SparseMolecularDataset
class SparseMoleCular(data.Dataset):
"""Dataset class for the CelebA dataset... | data_loader.py | MIT | 1,407 | d7c7f9fb4f4c472ba7ad11af1dc45353bbfa13f0 | Python | py | |
import argparse
import torch
from pathlib import Path
import h5py
import logging
from tqdm import tqdm
import pprint
from . import matchers
from .utils.base_model import dynamic_load
from .utils.parsers import names_to_pair
'''
A set of standard configurations that can be directly selected from the command
line usin... | hloc/match_features.py | Apache-2.0 | 4,638 | d79977f7d23bcbcf598f7243c555b336ac73355f | Python | py | |
import math
from argparse import ArgumentParser
import torch
import torchvision
import pytorch_lightning as pl
from pytorch_lightning import LightningModule
class Linear2p5(pl.LightningModule):
"""
Virtual staining 3D -> 2D
linear 3D convolution + maximum projection
to use
root_dir = 'runs'
... | MPLearn/virtual_staining/linear_model.py | Apache-2.0 | 3,259 | e65f0cb753a003406219108e49df629f4701a995 | Python | py | |
import sys
sys.path.append( 'C:\\CODE\\vdataset' )
from vdataset.vdataset import VDataset
from vdataset.labelmap import LabelMap
import torch
from torchvideotransforms import video_transforms, volume_transforms
# DEVICE SELECTING
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Executin... | tests/test.py | MIT | 1,950 | 299486dfd44eabf4acde930ea80f1417fe821c18 | Python | py | |
import os
import copy
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from tqdm import tqdm
from pathlib import Path
import dataset, vocab, utils
import models.ehr_lstm as model
class Traine... | src/trainer.py | MIT | 20,350 | 5e24b09dfd6bdf44848e270c1b1a9c38e90ed954 | Python | py | |
import torch
import bhabana.utils.generic_utils as gu
import torch.nn as nn
import bhabana.utils.constants as Constants
from bhabana.models import EncoderLayer
class Encoder(nn.Module):
''' A encoder model with self attention mechanism. '''
def __init__(
self, n_src_vocab, n_max_seq, n_layers=6,... | bhabana/models/transformer_encoder.py | Apache-2.0 | 2,529 | 2994a07d8e03b1c2e82d5b3935eef2c43a4939a5 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math, copy, time
from torch.autograd import Variable
import matplotlib.pyplot as plt
class EncoderDecoder(nn.Module):
"""
A standard Encoder-Decoder architecture. Base for this and many
other models.
"""
... | mg/model/MelodyRNN/tran_transformer.py | Apache-2.0 | 9,157 | f9c66377136162c71c99a23ca4a805ff04c9efa3 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
def pos_table(n, dim):
"""Create a table of positional encodings."""
def get_angle(x, h):
return x / np.power(10000, 2 * (h // 2) / dim)
def get_angle_vec(x):
return [get_angle(x, j) for j in range(dim)]
tab = np.array([get_angle... | AttentionNeuron/solutions/torch_modules.py | Apache-2.0 | 7,349 | 2994b7638cfdbc0eab1c743f682cb395d76814c8 | Python | py | |
import os
import numpy as np
import torch
from torch import nn
from aw_nas import utils
from aw_nas.final.cnn_trainer import CNNFinalTrainer #, _warmup_update_lr
from aw_nas.utils.common_utils import nullcontext
from aw_nas.utils.exception import expect
def _warmup_update_lr(optimizer, epoch, init_lr, warmup_epochs,... | aw_nas/final/det_trainer.py | MIT | 8,177 | 2994db11b2cfb32a26b81d885c244e758e258f87 | Python | py | |
import torch.utils.data as data
import logging
logger = logging.getLogger('base')
class HanziDataset(data.Dataset):
def __init__(self, opt):
pass
def __getitem__(self, index):
pass
def __len__(self):
pass
| data/hanzi_dataset.py | MIT | 248 | 1eb2949bdd35f5f71b1ff59dce5f04e06bbb0bd3 | Python | py | |
import torch
import torch.nn as nn
import math
from models.efficientnet import EfficientNet
from models.bifpn import BIFPN
from models.module import RegressionModel, ClassificationModel, Anchors, ClipBoxes, BBoxTransform
from torchvision.ops import nms
MODEL_MAP = {
'efficientdet-d0': 'efficientnet-b0',
'effi... | models/efficientdet.py | MIT | 4,120 | 29951e10b33b2d1c433b9d386926d4340d3f1dab | Python | py | |
import torch
from torch.utils.data import Dataset
import numpy as np
from pathlib import Path
from tts_modules.synthesizer.utils.text import text_to_sequence
class SynthesizerDataset(Dataset):
def __init__(self, metadata_fpath: Path, mel_dir: Path, embed_dir: Path, hparams):
print("Using inputs from:\n\t... | src/tts_modules/synthesizer/data/dataset.py | MIT | 3,222 | f952cd4f3229a99d9fdaa112451b3f3231d86f51 | Python | py | |
# coding=utf-8
# Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. 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/... | src/transformers/models/wav2vec2/modeling_wav2vec2.py | Apache-2.0 | 93,815 | 5eb042b6ddb1efae2474419f96721913c0489155 | Python | py | |
import math
import bisect
import imgaug
import numpy as np
import torch
# 分布式pytorch。pytorch分布式目前只支持Linux。
import torch.distributed as dist
from torch.utils.data import Sampler, ConcatDataset, BatchSampler
from concern.config import Configurable, State
def default_worker_init_fn(worker_id):
np.random.seed(work... | DB/data/data_loader.py | Apache-2.0 | 9,440 | 29956f0f135811eb3f28f5e993b99a9aa0a97943 | Python | py | |
import torch as tc
import os
import pickle
import pdb
def copy_param(tar , src):
'''把src的参数copy给tar'''
tar_param = list(tar.parameters())
src_param = list(src.parameters())
assert len(tar_param) == len(src_param)
for i in range(len(src_param)):
with tc.no_grad():
tar_param[i].data = src_param[i].data.cl... | utils.py | MIT | 1,700 | 29957ffbe3e292e5722daf6622c27f5cd5899fea | Python | py | |
import os
import random
import numpy as np
import torch
from torch import nn
class eval_mode(object):
def __init__(self, *models):
self.models = models
def __enter__(self):
self.prev_states = []
for model in self.models:
self.prev_states.append(model.training)
... | sac/utils.py | MIT | 3,846 | 29958a47245f06931054c8a6747d9022d95f9d68 | Python | py | |
import numpy as np
import torch
from forks.pytorch_a2c_ppo_acktr_gail.a2c_ppo_acktr import utils
from forks.pytorch_a2c_ppo_acktr_gail.a2c_ppo_acktr.envs import make_vec_envs
def evaluate(actor_critic, ob_rms, env_name, seed, num_processes, eval_log_dir,
device):
eval_envs = make_vec_envs(env_name, ... | forks/pytorch_a2c_ppo_acktr_gail/evaluation.py | MIT | 1,630 | 2995dab809b6dd036175c891567839c5508b1c0c | Python | py | |
# -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modificatio... | tests/test_layers_linear.py | Apache-2.0 | 7,977 | ff9ba3b19e43622a8e22d0a08d2766984f742705 | Python | py | |
import os
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from skimage import io
import numpy as np
## Unet model
class double_conv(nn.Module):
def __init__(self, in_ch, out_ch):
super(double_conv, self).__init__()
self.conv = nn.Sequential(
... | Models.py | MIT | 7,483 | 249594e22be4c2645c0b8f60d74ae2529b8b8228 | Python | py | |
import torch as T
from torch.nn.functional import math
def affine_2d(translation=None, rotation=0, scale=None, shear=None):
if translation is None:
translation = [0,0]
if scale is None:
scale = [1,1]
if shear is None:
shear=[0,0]
transf = T.zeros((3,3))
c = T.cos(T.Tensor([... | transformations/matrices.py | Apache-2.0 | 4,972 | 2995f4a5adec657e18eaf7feb7fb51bb77da48f3 | Python | py | |
import argparse
import cProfile
import logging as L
import os
import random
import tempfile
from typing import Any, Optional
import numpy as np
import torch
from torch import multiprocessing
from torch.autograd.profiler import profile
from mlprogram import distributed, logging
from mlprogram.entrypoint.configs import... | tools/launch.py | MIT | 7,341 | e999bdbc61583911eee8ae36c6357d7be97e12ae | Python | py | |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import torch
import omegaconf
import mbrl.env.continuous_dubins as dubins_env
import mbrl.env.reward_fns as reward_fns
import mbrl.env.termination_fns as termination_fns
import mbrl.models as models
import mbrl.planning as planning
import mbrl... | playground/pets_dubins.py | MIT | 6,480 | 12f6a69fd0573ee6b9b0a6c81a158a82f44d6769 | Python | py | |
"""
Copyright 2019 Johns Hopkins University (Author: Jesus Villalba)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
import os
from collections import OrderedDict as ODict
import logging
import torch
import torch.nn as nn
from ..utils import MetricAcc # , TorchDataParallel
from .torch_trainer import... | hyperion/torch/trainers/xvector_trainer_deep_feat_reg_from_wav.py | Apache-2.0 | 9,840 | 2996432221d932bacc01317c695337ca60e68945 | Python | py | |
'''Code from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix'''
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import inspect, re
import numpy as np
import os
import collections
# Converts a Tensor into a Numpy array
# |imtype|: the desired type of the converted num... | object_branch/utils/visutil.py | MIT | 2,506 | 5f3bff0fd37c57b45f520409e2734ab83c7c8575 | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from collections import namedtuple
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from pytorch_pretrained_bert.modeling import ... | utils_nlp/models/bert/sequence_classification.py | MIT | 9,956 | 03a3246049eac737f7cd0a534493923e717345f5 | Python | py | |
import importlib
import os
import torch
import torch.nn as nn
from datasets.hdf5 import get_test_loaders
from unet3d import utils
from unet3d.config import load_config
from unet3d.model import get_model
#logger = utils.get_logger('UNet3DPredictor')
threshold = 0.8
def _get_output_file(out_path, dataset, suffix='pr... | predict.py | MIT | 2,665 | 29965dcca2d2dae38c85bb81a9da638681e84f29 | Python | py | |
from __future__ import print_function
import itertools
import sys
from datetime import datetime
import numpy as np
import torch
from .IID_losses import IID_loss
from .eval_metrics import _hungarian_match, _original_match, _acc
from .transforms import sobel_process
def _clustering_get_data(config, net, dataloader, ... | code/utils/cluster/cluster_eval.py | MIT | 13,005 | 7ca93d23c6b0cf0e101865bafeb805e7fe07497d | Python | py | |
from __future__ import print_function
import sys
import logging
import argparse
import torchvision.datasets as dset
from torch.utils.data import Dataset
from sklearn import metrics
from scipy import stats
from collections import OrderedDict
import random
import os
import os.path
from functools import partial
from pa... | naslib/utils/utils.py | Apache-2.0 | 34,445 | 29968b37a470fb131d7ba70e7eb5b7fc3c7a5f68 | Python | py | |
import numpy as np
import argparse
import os
import torch
import torch.nn as nn
from smoke.modeling.detector import build_detection_model
from smoke.config import cfg
from smoke.utils.model_serialization import load_state_dict
def arg_parse():
parser = argparse.ArgumentParser(description="SMOKE Prunning script")... | tools/prunning/prune_smoke_resnet_v1.py | MIT | 20,592 | 29968c7e263697da93060a06532f174cbd454e83 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
from mmcv.cnn import build_conv_layer, build_norm_layer
from torch import nn
from mmdet3d.ops import spconv
from mmdet.models.backbones.resnet import BasicBlock, Bottleneck
class SparseBottleneck(Bottleneck, spconv.SparseModule):
"""Sparse bottleneck block for Part... | mmdet3d/ops/sparse_block.py | Apache-2.0 | 5,952 | 52e343a18e93886f2fc0ce5e4f8eff71ae88ab53 | Python | py | |
import cv2
import sys
import os
import torch
import numpy as np
import torch.utils.data
import utils.img
class GenerateHeatmap():
def __init__(self, output_res, num_parts):
self.output_res = output_res
self.num_parts = num_parts
sigma = self.output_res/64
self.sigma = sigma
... | data/MPII/dp.py | BSD-3-Clause | 6,421 | 2996c98816ce0de7ad8f2ddd2b3b831bab8931c2 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from detectron2.modeling.backbone import build_backbone
from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY
from detectron2.modeling.meta_arch.panoptic_fpn import \
combine_semantic_and_instance_outputs
from detectro... | adet/modeling/blendmask/blendmask.py | BSD-2-Clause | 7,657 | 2996dabb22c4f5a56250f95101096b5404525d33 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from model.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm):
super(_ASPPModule, self).__init__()
self.a... | model/aspp.py | MIT | 3,599 | 299702da32c7b3b73783305cd0ded3b234be8a3a | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
DENSENETS = {
"densenet121": models.densenet121,
"densenet161": models.densenet161,
"densenet169": models.densenet169,
"densenet201": models.densenet201,
}
DIMENSIONALITIES = {
"densenet121": [
... | models/laddernet_model/laddernet.py | Apache-2.0 | 8,914 | 2997207ec99a573fb08a42f4648e1068d909bc1e | Python | py | |
import numbers
import warnings
from collections.abc import Mapping, Sequence
from functools import partial
import torch
import torch.nn as nn
from torch.utils.data.distributed import DistributedSampler
import ignite.distributed as idist
from ignite.contrib.handlers import (
LRScheduler,
MLflowLogger,
Nept... | ignite/contrib/engines/common.py | BSD-3-Clause | 25,061 | 80291f0cdfec40af2cf0ad8a7eec6637e41350ba | Python | py | |
'''
FILENAME: pix2pix_data.py
AUTHORS: Pan Shaohua
START DATE: Friday February 25th 2022
CONTACT: shaohua.pan@quvideo.com
INFO: preparing data for training with pix2pix model
'''
import sys
from matplotlib.pyplot import bar_label
sys.path.append('/data1/shaohua/code/GANToy')
imp... | dataset/pix2pix_data.py | MIT | 2,095 | 7c6875636951cd79cc5f941885eea6ddfaca80bb | Python | py | |
import os
import time
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torchvision.models import resnet18
def get_time():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(... | clustre/helpers/datasets.py | MIT | 1,602 | cc014e4af6e4f618ffbaa12dcef62adddd5f4f80 | Python | py | |
import torch
from torch_geometric.nn.conv import MessagePassing
from 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 Sets
for 3D Classification and Segmentation"
... | torch_geometric/nn/conv/point_conv.py | MIT | 2,855 | 29979658bfb9d966308a9292ae1f7ae786bc493a | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.