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 torch import nn
from ..components import AdditiveAttention
class Decoder(nn.Module):
def __init__(self, output_size, hidden_size, embedding_dim, max_length, enc_dim, device, dropout_p=0.1, pad_token=0):
super(Decoder, self).__init__()
self._hidden_size = hidden_size
self... | nntoolbox/sequence/models/decoder.py | Apache-2.0 | 2,837 | 3a13f5ab4912e3290b8a54b3aee4a7da5cfaa1e1 | Python | py | |
import random
import tempfile
import torchvision
import data.transform as transform
import data.utils as utils
class VideoDecoder(object):
"""
Video decoder for cross-modal (audio-visual) contrastive task. Sample
audio/visual clips from the videos. Audio/visual clips are randomly
sampled from every ... | evaluation/code/data/contrast.py | MIT | 5,970 | 3a13f853279ac38f3515df2a18bef442b379344c | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
from typing import List, Optional
import pytorch_lightning as pl
from mmf.common.sample import SampleList
from mmf.common.test_reporter import TestReporter
from mmf.datasets.multi_dataset_loader import MultiDataLoader
from mmf.utils.build import build_m... | mmf/datasets/multi_datamodule.py | BSD-3-Clause | 3,509 | 3a13fe9db4aae301effb998e4f066d72bcb5dc59 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from archai.common.utils import AverageMeter
from collections import defaultdict
from typing import Iterable, Optional, Tuple, List
import torch
from torch import nn
import torch.nn.functional as F
from overrides import overrides
... | archai/algos/xnas/xnas_op.py | MIT | 4,182 | 42387a621abe90a13c4fb16b328f23e59fb1160c | Python | py | |
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchtrain import Module
class DeepLog(Module):
def __init__(self, input_size, hidden_size, output_size, num_layers=2):
"""DeepLog model used for training and predicting logs.
P... | deeplog/deeplog.py | MIT | 5,676 | 3a14153fdb3fb651f65a97d13131568eb3e322ab | Python | py | |
import tempfile
from pathlib import Path
import torch
import pytest
import numpy as np
import SimpleITK as sitk
from ..utils import TorchioTestCase
from torchio.data import io, ScalarImage
from torchio.data.io import ensure_4d, nib_to_sitk, sitk_to_nib
class TestIO(TorchioTestCase):
"""Tests for `io` module."""... | tests/data/test_io.py | Apache-2.0 | 6,678 | b23b8685449bb50024db455f93857fa283153b29 | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import random
import shutil
import warnings
import cv2
import click
import h5py
import numpy as np
from sklearn.metrics import jaccard_similarity_score, precision_score, recall_score, f1_score
import torch
from torch import n... | scripts/train_object_detector_localizer.py | MIT | 24,206 | 3a144a5769cb431765ddea9ac8e7d04e396b1217 | Python | py | |
from typing import List, Union
from collections import OrderedDict
from pathlib import Path
import torch
from torch import nn
import torchvision
from catalyst import utils
from catalyst.contrib.models.cv.segmentation.encoder.core import ( # noqa: WPS450, E501
_take,
EncoderSpec,
)
RESNET_PARAMS = { # noqa:... | catalyst/contrib/models/cv/segmentation/encoder/resnet.py | Apache-2.0 | 4,222 | 28b87336381eeb03f15df5fc44f96682dc7f31a9 | Python | py | |
"""Wrapper of AllenNLP model. Fixes errors based on model predictions"""
import logging
import os
import sys
from time import time
import torch
from allennlp.data.dataset import Batch
from allennlp.data.fields import TextField
from allennlp.data.instance import Instance
from allennlp.data.tokenizers import Token
from ... | gector/gec_model.py | Apache-2.0 | 12,357 | b28776fd9f17f816bff9f413003896078a68d042 | Python | py | |
from pytorch_tabnet.tab_model import TabNetClassifier
import torch
import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn import metrics
d_train = pd.read_csv("https://s3.amazonaws.com/benchm-ml--main/train-0.1m.csv")
d_test = pd.read_csv("https://s3.amazonaws.com/benchm-ml--main/test.... | analysis/tabnet/old-keep/tabnet-min.py | MIT | 1,330 | 7c7205a26d746175fb1c6ee928e0705e279fd79a | Python | py | |
#!/usr/bin/env python3
""" 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 al... | train.py | Apache-2.0 | 40,596 | 10d839befc55f2d96c60f3e73f0d3edeeccfa7ce | Python | py | |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class QMixerRainbow(nn.Module):
def __init__(self, args):
super(QMixerRainbow, self).__init__()
self.args = args
self.n_agents = args.n_agents
self.state_dim = int(np.prod(args.state_shape)... | src/modules/mixers/qmixrainbow.py | Apache-2.0 | 2,111 | 10244aa21740acc8a958e6cf20224f4d51c8d93f | Python | py | |
import pytest
import torch
from pytorch_pfn_extras.nn import Ensure, ensure
class TestEnsure:
def test_wrong_initialization(self):
with pytest.raises(ValueError, match='both arguments'):
Ensure(shape=None, dtype=None)
@pytest.mark.parametrize(
'shape', [(), (1,), (1, 1), (2,), (2... | tests/pytorch_pfn_extras_tests/nn_tests/modules_tests/test_ensure_shape.py | MIT | 5,530 | 1e758cb9e74d5c1257935b8f813f236c663f817e | Python | py | |
import sys
import time
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
from roi_align import RoIAlign
from torch.autograd import Variable
class ImageCropper(nn.Module):
def __init__(self, img_size):
super(ImageCropper, self).__init__()
self.isCuda = False
... | plugins/pytorch/mdnet/img_cropper.py | BSD-3-Clause | 2,675 | 52eba794c2d28e0d2d97883f2fb97a3861ba46b0 | Python | py | |
import logging
from contextlib import contextmanager
import torch
logger = logging.getLogger("nlstruct")
subset_list = []
@contextmanager
def no_subset():
global subset_list
redos = [undo_subset() for undo_subset in list(subset_list)]
yield
subset_list = [redo() for redo in redos]
def index_shape... | deep_multilingual_normalization/utils.py | MIT | 5,829 | 651e0b147533a89843af1f7d018afc286b621a4e | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import copy
import io
import itertools
import json
import logging
import numpy as np
import os
import pickle
from collections import OrderedDict
import pycocotools.mask as mask_util
import torch
from pycocotools.coco import COCO
from pycocotools.cocoe... | adet/evaluation/visible_evaluation.py | BSD-2-Clause | 24,162 | 3a151e4e9632e3625aa373559e62de93b8810441 | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 19:13:50 2021
@author: behnood
"""
#from __future__ import print_function
import matplotlib.pyplot as plt
#%matplotlib inline
# from numpy import linalg as LA
import os
#os.environ['CUDA_VISIBLE_DEVICES'] = '3'
import numpy as np
#from models import *
... | MiSiCNet_Sim2Git.py | Apache-2.0 | 8,883 | 3a153c523e1b29ab4c4c254b6210230be7742f94 | Python | py | |
import torch
from torch.autograd import Function
import torch.nn as nn
def threshold_and_support(z, dim=0):
"""
z: any dimension
dim: dimension along which to apply the sparsemax
"""
sorted_z, _ = torch.sort(z, descending=True, dim=dim)
z_sum = sorted_z.cumsum(dim) - 1 # sort of a misnomer
... | nnow/activations.py | MIT | 1,688 | 3a154f336dc8fcbcbdb2efb2a6ab8c4dea83ed06 | 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/models/preact_resnet.py | MIT | 6,768 | 3a156eace45757d5c3919d29e5bbdb4824fcaf17 | Python | py | |
from pathlib import Path
import numpy as np
import torch
import json
path_root = DIR_THIS = Path('.').absolute()
def full_path(fn, path=None):
if path is None:
return Path(fn)
else:
return Path(path) / fn
def load_tensor(fn, to_cuda=False, path=None):
fn = full_path(fn, path)
fn = ... | goodok_mlu/io.py | MIT | 2,455 | 3a1589202147127320dd23f212c98ae6293ac451 | Python | py | |
import argparse
import json
import os
from torch.optim import optimizer
from tqdm import tqdm
import wandb
import numpy as np
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
torch.backends.cudnn.benchmark... | transfuser/train.py | MIT | 14,820 | b22db7ea00a3ed5e759dd9dde195180835121381 | Python | py | |
import argparse
import json
import os
import pickle
import sys
import sagemaker_containers
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data
from model import LSTMClassifier
from utils import review_to_words, convert_and_pad
def model_fn(mod... | Project/serve/predict.py | MIT | 3,088 | e61cd4afceb0591ca63aef8574502fcc0d3a6149 | Python | py | |
import argparse
import os
import re
import time
import torch
import pandas as pd
from kernel_utils import VideoReader, FaceExtractor, confident_strategy, predict_on_video_set
from training.zoo.classifiers import DeepFakeClassifier
if __name__ == '__main__':
parser = argparse.ArgumentParser("Predict test videos")
... | predict_folder.py | MIT | 2,196 | a97a543981f8eee0f5a27007b7b36a3fdc0262d1 | Python | py | |
from typing import Callable
from torch import nn, Tensor
from annotated.norm import LayerNorm
from annotated.utils import clones
SUBLAYERS_IN_ENCODER_LAYER = 2
class Encoder(nn.Module):
"""Core encoder is a stack of N layers"""
def __init__(self, layer: nn.Module, num_layers: int):
super(Encoder, ... | annotated/encoder.py | MIT | 2,390 | 3a15aac5afe8aa8f99296d817aac84b4da850a88 | Python | py | |
from torchvision import transforms
from PIL import Image
import numpy as np
import pandas as pd
import os
from glob import glob
import torch
from torchvision.transforms import functional as F
class ScaledCenterCrop(torch.nn.Module):
"""Crops the given image at the center.
If the image is torch Tensor, it is e... | utils.py | MIT | 7,278 | 3a15c508f298d0a8214204217c659f3ccf604665 | Python | py | |
import copy
import math
import warnings
from functools import partial
from typing import List
from typing import Optional
from typing import Union
import attr
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from pytorch_lightning.utilities import AttributeDict
from sklearn.linear_model impo... | moco.py | MIT | 24,790 | 1085b2ab5d899217844414501453074dc3cec41f | Python | py | |
import time
from pathlib import Path
import fire
import numpy as np
import torch
import torch.nn.functional as F
import tqdm
from torch import distributed, nn
from torch.utils import data
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets, transforms
import spconv
from spconv.test_utils... | test/fake_train.py | Apache-2.0 | 5,025 | 652a869ffee77351ac4d09bc20eaf7198ebb13fc | Python | py | |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import beanmachine.ppl as bm
import pytest
import torch
import torch.distributions as dist
from beanmachine.ppl.inference.proposer.hmc_propo... | src/beanmachine/ppl/inference/proposer/tests/hmc_proposer_test.py | MIT | 1,839 | 3a15e78a9ecd9c28e60aa02623d30aa78d00a60b | 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 numpy as np
import torch.utils.data
from fairseq.data import data_utils
import logging
logger = logging.getLogger(__name__)
class Ep... | fairseq/data/fairseq_dataset.py | MIT | 6,771 | 5e720b1353ccb49087feadd33b4d12f15a637d44 | Python | py | |
import os
from data import common
from data import srdata
import numpy as np
import scipy.misc as misc
import torch
import torch.utils.data as data
class DIV2K(srdata.SRData):
def __init__(self, args, train=True):
super(DIV2K, self).__init__(args, train)
self.repeat = args.test_every // (args.n_... | code/data/div2k.py | MIT | 1,930 | 5f786dbedee86356cc41c1f958d64bc1f7fdd4ac | Python | py | |
import torch
import random
import numpy as np
"""
Code to reproduce a PyTorch bug which I found during the thesis
see: https://github.com/pytorch/pytorch/issues/18934
"""
random.seed(0)
x = [1, 2, 3]
xt = torch.tensor(x)
np.random.shuffle(xt)
np.random.shuffle(x)
print(xt)
print(x)
| utils/everybody_gangsta_until_not.py | MIT | 289 | d78740815fb1f01f6f67380a70a30802be72d242 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable-msg=import-error
# pylint: disable-msg=no-member
# pylint: disable-msg=not-callable
"""
parallel_cnn_lstm_run.py is written for run parallel cnn_lstm model
"""
import time
import logging
import matplotlib.pyplot as plt
import torch
from torch import opt... | src/ABCDM_run.py | MIT | 14,121 | 3a163a715a3c70c05952fe48d5078f404d682e1d | Python | py | |
from pathlib import Path
import sys
import os
sys.path.append(Path(__file__).resolve().parent.parent)
install_path = str(Path(__file__).resolve().parent.parent)
import numpy as np
import pandas as pd
import pickle as pkl
from utils.geohash import GeoHash
import torch
import random
def setup_seed(seed):
torch.manu... | project/utils/common.py | MIT | 3,869 | 3a166fa41809d2010550675fa3c04a387913b603 | Python | py | |
import pytest
import os
import numpy as np
import torch
import tensorflow as tf
if 'PATH_TO_OPEN3D_ML' in os.environ.keys():
base = os.environ['PATH_TO_OPEN3D_ML']
else:
base = '.'
gpus = tf.config.list_physical_devices('GPU')
if gpus:
# Use first GPU and restrict memory growth.
try:
tf.config... | tests/test_models.py | MIT | 6,315 | 5e279d5b79ffea013d8cb0a9c661bf44fbc2e630 | Python | py | |
from __future__ import absolute_import
from __future__ import division
import torch
import torch.nn as nn
class TripletLoss(nn.Module):
"""Triplet loss with hard positive/negative mining.
Reference:
Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737.
Im... | torchreid/losses/hard_mine_triplet_loss.py | MIT | 1,819 | 3a1688efdc4bfbe40bfad4b0252649ed75613e68 | Python | py | |
import argparse
import warnings
warnings.simplefilter('ignore')
from decoder import GreedyDecoder
from torch.autograd import Variable
from data.data_loader import SpectrogramParser
from model import DeepSpeech
import os.path
import json
parser = argparse.ArgumentParser(description='DeepSpeech transcription')
parse... | transcribe_New.py | MIT | 4,136 | 24ef527bd29d6e94a4401bb729f8bc9f80cff93d | Python | py | |
from typing import Union, Type
from torch import nn
from src.backbone.layers.conv_block import conv1x1, resnet_normal_init, resnet_zero_init, BasicBlock, BottleNeck
class ResNet32(nn.Module):
def __init__(self,
block_list: tuple = (3, 3, 3),
channels: tuple = (16, 32, 64),
... | src/backbone/resnet32.py | Apache-2.0 | 2,871 | fde9189d2d32d92ad5ec5411f04b2f16634606dc | Python | py | |
# Copyright (c) 2020 Horizon Robotics and ALF Contributors. 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... | alf/test/case.py | Apache-2.0 | 2,779 | 4b42bff5ae37d6a18365b5c9753dae12de5c252c | Python | py | |
import torch
import torch.nn as nn
from torch_scatter import scatter
from graphgym.config import cfg
from graphgym.models.register import register_pooling
def global_example_pool(x, batch, size=None):
size = batch.max().item() + 1 if size is None else size
return scatter(x, batch, dim=0, dim_size=size, reduce... | graphgym/contrib/pooling/example.py | MIT | 379 | 3a171bde12a3b70986c995b65b52732bcbdd9888 | Python | py | |
import logging
import torch.nn as nn
from mmcv.cnn import constant_init, kaiming_init
from mmcv.runner import load_checkpoint
from mmdetection.core import auto_fp16
from ..backbones import ResNet, make_res_layer
from ..registry import SHARED_HEADS
@SHARED_HEADS.register_module
class ResLayer(nn.Module):
def __... | mmdet/models/shared_heads/res_layer.py | Apache-2.0 | 2,242 | 3a172fff1d681a23e63b71494e6007e80e29f43e | Python | py | |
# import libraries
#{{{
# a hack for backwards compatibility
try:
import binutil # required to import from dreamcoder modules
except ModuleNotFoundError:
import bin.binutil # alt import if called as module
from json.decoder import JSONDecodeError
from syntax_robustfill import SyntaxCheckingRobustFill
from i... | bin/rbBaseline.py | MIT | 21,367 | 3a17438cb4f46946cb55d94d2d348426594ced9f | Python | py | |
# Differentiable plasticity: simple binary pattern memorization and reconstruction.
#
# Copyright (c) 2018 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:... | simple.py | Apache-2.0 | 15,942 | 3a1753863de8dd8002c88a3640d7743541d6ea25 | Python | py | |
import torch
from DsCML.common.utils.metric_logger import AverageMeter
class SegAccuracy(AverageMeter):
"""Segmentation accuracy"""
name = 'seg_acc'
def __init__(self, ignore_index=-100):
super(SegAccuracy, self).__init__()
self.ignore_index = ignore_index
def update_dict(self, p... | DsCML/models/metric.py | MIT | 2,318 | 1e674ae719c29a9496b86c7cddc6a7d5c48ac703 | Python | py | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : addNet.py
@Contact : fh.li@foxmail.com
@Modify Time 2020/4/13 8:50 AM
'''
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : newidea.py.py
@Contact : fh.li@foxmail.com
@Modify Time 2020/4/9 10:49 AM
'''
import argparse
imp... | addNet.py | MIT | 7,558 | 3a177d78a850c9f4ee33cd87df6808bbd89a7611 | Python | py | |
import torch
import matlab.engine
from Iterative import ValueIterative
from model import SystemModel
from network import Critic, Actor
if __name__ == '__main__':
# 导入训练好的模型
TestPolicy = ValueIterative()
TestPolicy.Model.Player = torch.load('./ModelData/Player.ckpt')
TestPolicy.Model.... | main.py | MIT | 2,005 | 5e944d41e35a909f6d6dc57d51c9b3fa9a1afdcc | Python | py | |
# DL
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastai.layers import SelfAttention
# PyTorch training framework
import pytorch_lightning as pl
from pytorch_lightning.metrics.functional import accuracy
from .layers import SpatialTransformer
class MyLightningModule(pl.L... | src/caciolai-FER/model/models.py | MIT | 16,121 | 3a1787df8a244cca36696f29aa593c2075af3a11 | Python | py | |
import json
import pandas as pd
import os
import matplotlib.ticker as mtick
import math
import torch
import matplotlib.pyplot as plt
# TODO: shift inside each class?
def init_weights(m):
"""
Initialise weights acc the Xavier initialisation and bias set to 0.01
:param m:
:return: somethibf
... | src/vanilla_pytorch/utils.py | MIT | 3,006 | 3a17bc60019b2cf8ec41afea00af1eb68b4073d6 | Python | py | |
"""
Script for a {Conditional} Variational Autoencoder to generate(synthesize) sounds.
"""
# Dependencies
import torch
import torch.nn as nn
# Defining the Classes corresponding to the Conditional Encoder and Decoder first
class c_Enc(nn.Module):
"""
Class specifying the conditional encoder architecture(data cond... | Network/vae_krishna.py | MIT | 7,825 | 3a17ce278665d4155658036e2cbca3493117c574 | Python | py | |
from TRPO.functions.const import *
from torch.distributions.kl import register_kl
from torch.distributions import Normal, Categorical
@register_kl(Normal, Normal)
def kl_normals(dist1, dist2):
mean1, mean2 = dist1.mean, dist2.mean
logstd1, logstd2 = Tlog(dist1.stddev), Tlog(dist2.stddev)
var1, var2 = dist1... | nets/dist.py | MIT | 594 | 12ef8ec0be25912316014714ff41ffd9206f0d0b | Python | py | |
from torch.utils import data
from models.model_selector import ModelSelector
import pytorch_lightning as pl
from data import DataHandler
class TrainingLauncher:
def __init__(
self,
path_to_data,
model_name,
num_classes=3,
data_type="image_folder",
augmentation=None,... | train.py | MIT | 903 | d7c6fc43914b7573644bc5952eae31bf060dff5f | Python | py | |
import torch.nn as nn
from ..registry import DETECTORS
from mmdet.core import bbox2result
from .base import BaseDetector
from .. import builder
@DETECTORS.register_module
class CIRDetector(BaseDetector):
def __init__(self,
backbone,
neck=None,
bbox_head=None,
... | mmdet/models/detectors/Mydetector.py | Apache-2.0 | 2,628 | a961d8b2637fcac25e575e2fa85b85107c915771 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
import numpy as np
def accuracy_SBM(scores, targets):
S = targets.cpu().numpy()
C = np.argmax( torch.nn.Softmax(dim=1)(scores).cpu().detach().numpy() , axis=1 )
... | train/metrics.py | MIT | 863 | 3a183caca723938a4c8e5fd020e198c7867b51de | Python | py | |
import os
import numpy as np
import time
from torch.utils.data import TensorDataset
from torch.autograd import Variable
import torch
import torch.nn as nn
import torch.nn.functional as ff
import argparse
from sklearn.preprocessing import MinMaxScaler
class encoder_RNN(nn.Module):
"""
DA-RNN encoder module
"""
... | model_file/run_da_predictions.py | Apache-2.0 | 7,512 | 24d1dca7a94493698c8e85ac7f71b620f0e962f7 | Python | py | |
import torch
import copy
class TargetNet:
"Wrapper around model which provides copy of it instead of trained weights"
def __init__(self, model: torch.nn.Module):
self.model = model
self.target_model = copy.deepcopy(model)
def __call__(self, *args):
return self.target_model(*args)... | src/common.py | MIT | 881 | 24b8e5732921e08622574a47eaf1ce6534084e27 | Python | py | |
from typing import List, Dict, Tuple
import numpy as np
import torch
from gensim.models import FastText
from omegaconf import DictConfig
from torch import nn
from torch.utils.data import Dataset
from src.utils.text_utils import pad_sequences, build_matrix
class NerDataset(Dataset):
def __init__(self, ner_data: ... | src/datasets/text_dataset.py | MIT | 3,918 | e9a4cdf709aafad291f462e3acf89749be3f6838 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy
import soft_renderer as sr
class Renderer(nn.Module):
def __init__(self, image_size=256, background_color=[0,0,0], near=1e-6, far=100,
anti_aliasing=True, fill_back=True, eps=1e-6,
cam... | soft_renderer/renderer.py | MIT | 4,372 | 3a1871ca1a60ac58f36407a6c3bae99e8a8df86c | Python | py | |
import torch
import pprint
import numpy as np
from typing import Any, List, Union, Iterator, Optional
class Batch(object):
"""Tianshou provides :class:`~tianshou.data.Batch` as the internal data
structure to pass any kind of data to other methods, for example, a
collector gives a :class:`~tianshou.data.Ba... | tianshou/data/batch.py | MIT | 7,397 | 8015b8674df49f56462f4341feb470005e021805 | Python | py | |
# coding: utf-8
#
# # The annotated transformer
#
# This file may contain code from: https://github.com/harvardnlp/annotated-transformer
#
# ## Original license:
#
# MIT License
#
# Copyright (c) 2018 Alexander Rush
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of t... | src/data/training_data.py | BSD-3-Clause | 7,857 | 1e3965a943206b8fee1a1d07a8f851da6922ea5a | Python | py | |
#!/usr/bin/env python
# Copyright (c) 2019, The Personal Robotics Lab, The MuSHR Team, The Contributors of MuSHR
# License: BSD 3-Clause. See LICENSE.md file in root directory.
import threading
import matplotlib.cm as cm
import matplotlib.colors as mplcolors
import rospy
import torch
from geometry_msgs.msg import Po... | src/rhcdebug.py | BSD-3-Clause | 9,895 | 3a188c479229323950d36ac115187923b7c4b0e3 | Python | py | |
#!/usr/bin/env python
import sys
import os
import wandb
import socket
import setproctitle
import numpy as np
from pathlib import Path
from gym import spaces
import torch
from onpolicy.config import get_config
from onpolicy.envs.env_wrappers import SubprocVecEnv, DummyVecEnv
def make_env(args):
from MultiVehicle... | onpolicy/scripts/render/render_mve.py | MIT | 6,015 | ff8ef7ca2c144b35c3a5bbd5c4e058bb56194800 | Python | py | |
import numpy as np
import json
from pathlib import Path
from urllib import parse
import requests
from torchvision.datasets import CocoDetection
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def download_data(save_dir):
save_dir = Path(save_dir)
assert save_dir.is_dir()
# Annotations... | Manufacture/paper/recycle-master/data_utils.py | MIT | 4,163 | e9584c7c24a1ba83584ba9c1cf0db8614b397f00 | Python | py | |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import models.modules.PoseAttention as M
class HourglassAttention(nn.Module):
"""docstring for HourglassAttention"""
def __init__(self, nChannels = 256, numReductions = 4, nModules = 2, poolKernel = (2,2), poolStride = (2,2), upSam... | models/PoseAttention.py | MIT | 4,776 | 3a18f8add0951ce6342a6ce62283ff72e4650eb0 | Python | py | |
""" adapted from https://github.com/r9y9/tacotron_pytorch """
""" LSA from https://github.com/NVIDIA/tacotron2 """
import torch
from torch import nn
class BahdanauAttention(nn.Module):
"""
BahdanauAttention
This attention is described in:
D. Bahdanau, K. Cho, and Y. Bengio, "Neural Machine Trans... | model/attention.py | MIT | 6,019 | 3a18fc345f99ec9433c4f0e98e094202f8149b4e | Python | py | |
"""
Copyright (c) 2019-2022 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | tests/torch/test_nncf_network.py | Apache-2.0 | 43,627 | 3a18fd466ad31ed7ad750dd5299f958f05f5104a | Python | py | |
#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# 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 ag... | baselines/scripts/layout2im/data/coco_custom_mask.py | MIT | 20,522 | f97e6da0b7373b3c1696ea49e1691dc82fa562ea | Python | py | |
#Adapted from https://github.com/huggingface/transformers/blob/21da895013a95e60df645b7d6b95f4a38f604759/src/transformers/modeling_gpt2.py
import logging
import math
import os
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
# from transformers.configuration_gpt2 import GPT2Config
from transf... | modeling_gpt2.py | BSD-3-Clause | 36,817 | 3a18fff1da93fb3e28fc521b79751736a27bc522 | Python | py | |
import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import random
import torch.nn.functional as F
class CycleGANModel(BaseModel):
"""
This class implements the CycleGAN model, for learning image-to-image translation without paired data.
... | models/cycle_gan_model.py | BSD-3-Clause | 11,757 | 3a1905202d230c08092171ce028bba6e97a8d32d | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: zcy
# @Date: 2019-02-11 11:53:24
# @Last Modified by: zcy
# @Last Modified time: 2019-03-05 12:43:54
import os
import json
import argparse
import torch
from collections import Iterable
import data_loader.data_loaders as module_data
import mode... | classifier.py | MIT | 10,549 | fcbb6999c67949816cad7c41290c2b07fc7db975 | Python | py | |
import torch
from priors import Prior
class PriorNormal(Prior):
def __init__(self, mu=0.0, std=1.0, device="cpu"):
super(PriorNormal, self).__init__()
self.mu = mu
self.std = std
def sample(self, name, param):
mu, std = self._get_params_by_name(name)
if (mu is None)... | priors/normal.py | Apache-2.0 | 948 | 7c3fd5f5dedab1278d86e3b723018e168382013e | Python | py | |
#from post_rec.alphaservices.HTTPServers.flask_http import AlphaHTTPProxy
from post_rec.alphaservices.HTTPServers.tornado_http import AlphaHTTPProxy
import numpy as np
import random
import os
from post_rec import AlphaConfig, AlphaPathLookUp
import torch
from torch.utils.data import TensorDataset, DataLoader, Sequenti... | post_rec/retrievers/relation_searcher.py | MIT | 4,914 | d793362f5d3c7cdf2e1a0675c98dab089e211ab8 | Python | py | |
# ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (ht... | util/box_ops.py | Apache-2.0 | 4,281 | 3a195cc62e0fb56663805f3b4cc74a8f54af732d | Python | py | |
import re
import monai
import torch
class Losses(object):
def __init__(self,config):
'''
Compute the losses
Args:
config['configparser']: The configuration parser
Returns:
'''
loss_type = config['Losses']['losses']
self.num_classes = int(config['D... | losses/common.py | MIT | 1,919 | a93103fd3ba7186429b5ec714126f77817ec08ab | Python | py | |
import math
import random
import collections
import numpy as np
import torch
from scipy import ndimage
from .rand import Constant, Uniform, Gaussian
class Base(object):
def sample(self, h, w, t):
return h, w, t
def tf(self, img, k=0):
return img
def __call__(self, img, reuse=False):
... | backup/transforms_bk.py | MIT | 7,762 | 3a19826cd9c6f8158256ffb1a77eeba852856983 | Python | py | |
import torch
import optuna
from cogdl.utils import build_args_from_dict
from cogdl.models import build_model
from cogdl.datasets import build_dataset
from cogdl.tasks import build_task
class HyperSearch(object):
"""
This class does not need to be modified
Args:
Hyper-parameter search script
... | examples/hyper_search.py | MIT | 3,793 | 800f1056ac6e93413b608f14f19428554426d707 | Python | py | |
# -*- coding: utf-8 -*-
# @Author: yulidong
# @Date: 2019-07-27 01:06:36
# @Last Modified by: yulidong
# @Last Modified time: 2019-08-03 00:33:04
""" Training perception and control """
import argparse
from os.path import join, exists
from os import mkdir
import matplotlib.pyplot as plt
import torch
im... | train_corner.py | Apache-2.0,MIT | 15,279 | 3a199bf607897cfd57c9a2d2fa96c401817fb0ed | Python | py | |
import copy
import math
import logging
from tqdm import tqdm
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm_
from c2nl.config import override_model_args
from c2nl.models.seq2seq import Seq2seq
from c2nl.models.transformer import Transformer
from c2nl.utils.copy_utils im... | main/model.py | MIT | 15,389 | 3a19ab8e669dc42ada8298c67712188fb2525e39 | Python | py | |
# Copyright (c) 2019 NVIDIA Corporation
import logging
from abc import abstractmethod
from typing import Dict, Set, Tuple, Optional, List
import torch as t
import torch.nn as nn
from ...core import NeuralModule, DeviceType, WeightShareTransform
from ...utils.helpers import rgetattr, rsetattr, get_cuda_device
class ... | nemo/nemo/backends/pytorch/nm.py | Apache-2.0 | 11,663 | 3a19b1617fb07c9dbe50bf982c8ffa5ff0eb5cb4 | Python | py | |
import argparse
import csv
import os
from pathlib import Path
import random
from typing import Any, Dict, Tuple
import numpy as np
import pandas as pd
import torch
import yaml
from pytorch_lightning import LightningModule, LightningDataModule, Trainer, seed_everything
from pytorch_lightning.core.memory import ModelSum... | scripts/train.py | Apache-2.0 | 8,956 | 340f6d5952b032857968196aaa0c5870ed58a845 | Python | py | |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Hang Zhang
## Email: zhanghang0704@gmail.com
## Copyright (c) 2020
##
## LICENSE file in the root directory of this source tree
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""ResNeSt models"""
im... | torchsat_imc/models/classification/resnest/resnest.py | MIT | 3,669 | 3a1a032956ac16fdcccaaf646805cf215505d3f6 | Python | py | |
import sys
import torch
from .util import plot_every, datestr, get_git_revisions # pylint: disable=E0401
def register(mf):
mf.set_scope("..") # one up
# log also the projects & subprojects state
modules, shas, diffs = get_git_revisions()
mf.register_defaults({
"steps": 0,
"dir": ".... | grp_modules/util/log/base/__init__.py | MIT | 733 | 3a1a4157a69310f0f5e598fd6ef211c7a87b228b | Python | py | |
import copy
import os
import time
import torch
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
from models.utils import get_cpu_copy, save_checkpoint
class Trainer:
def __init__(
self, model, device, criterion, optimizer, scheduler,
checkpoint_dir=None, writer_dir=Non... | trainers/trainer.py | MIT | 10,345 | fd7d0658de0483885a56192fc8e60ca9657b004f | Python | py | |
import torch
import numpy
class Config(object):
"""模型参数配置"""
def __init__(self, base_path, embedding_name):
self.vocab_path = base_path + '/vocab.pkl'
self.train_path = base_path + '/train.txt' # 训练集
self.dev_path = base_path + '/dev.txt' # 验证集
self.test_path = base_path + ... | text_class_model/models/fasttext.py | MIT | 2,823 | 3a1a5ad623b47f0346993e9a388649f6b55be841 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Modified by Sangrok Lee and Youngwan Lee (ETRI), 2020. All Rights Reserved.
import contextlib
import copy
import io
import itertools
import json
import logging
import numpy as np
import os
import pickle
from collections import OrderedDict
import p... | centermask/evaluation/coco_evaluation.py | Apache-2.0 | 20,543 | 10f2cec4f1f4c40033526b2fe0b63fe9c8c5869c | Python | py | |
"""
This script is used to process and generate dataset from original heart beat audio files.
"""
import warnings
import torch
from torch.utils.data import TensorDataset
import os
import pandas as pd
import librosa
import librosa.display
import glob
import matplotlib.pyplot as plt
import keras
import IPython.display a... | src/DatasetGeneration/heartbeat.py | MIT | 8,899 | 3a1a84fb9efe8f5e1ed6870bbf5c1e8e91cb9677 | Python | py | |
# coding:utf-8
import logging
import time
import os
import torch
from torch import nn, optim
import numpy as np
import tqdm
from utils import Storage, cuda, BaseModel, SummaryHelper, get_mean, storage_to_list, \
CheckpointManager
from network import Network
class Seq2seq(BaseModel):
def __init__(self, param):
ar... | models/seq2seq-pytorch-bert/seq2seq.py | Apache-2.0 | 6,785 | 3a1a99d46425d0f750e26981e574f8c3b69afa69 | Python | py | |
from .operations import *
class Cell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(Cell, self).__init__()
if reduction_prev:
self.preprocess0 = FactorizedReduce(C_prev_prev, C)
else:
self.preprocess0 = ReLUConvB... | Transfer/SSDLite/vision/ssd/backbones/DARTS/networks.py | Apache-2.0 | 4,955 | 4549f33a15f255e234bed969b72bde42fca245a4 | Python | py | |
import os
from data import common
import numpy as np
import scipy.misc as misc
import torch
import torch.utils.data as data
class Demo(data.Dataset):
def __init__(self, args, train=False):
self.args = args
self.name = 'Demo'
self.scale = args.scale
self.idx_scale = 0
self... | code/data/demo.py | MIT | 1,128 | 3a1acf9561b8924df920761def80919e26b390e9 | 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, Optional, Tuple
import torch
import torch.nn.functional as F
from fairseq import utils
from torch import Tensor, nn
... | fairseq/model_parallel/modules/multihead_attention.py | MIT | 12,558 | e92a3f6a71c7225b293a941020749046d2c628d5 | Python | py | |
from typing import Any, Optional, Union
import PIL.Image
import torch
from torchvision.prototype import features
from torchvision.prototype.utils._internal import query_recursively
def query_image(sample: Any) -> Union[PIL.Image.Image, torch.Tensor, features.Image]:
def fn(input: Any) -> Optional[Union[PIL.Image... | torchvision/prototype/transforms/_utils.py | BSD-3-Clause | 649 | 24d794a2cb4f282a6a217e50c802e7a2351c4944 | Python | py | |
import torch
import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as F
from .ResNet import ResNet
import math
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1):
super(BasicConv2d, self).__init__()
s... | models/segtran_modified/code/networks/pranet/PraNet_ResNet.py | MIT | 9,999 | 4bb1ea6d91093f0a404f83f21d8da40644b907c7 | Python | py | |
import math
import torch
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR
def get_constant_schedule(optimizer: Optimizer, last_epoch: int = -1):
"""
Create a schedule with a constant learning rate, using the learning rate set in optimizer.
Args:
optimizer (:class:`... | spanet/network/learning_rate_schedules.py | BSD-3-Clause | 6,143 | a987bbcfe6aff92f1cf759ccfb45a0a602ac6580 | Python | py | |
import io
import cv2
import time
import math
import ctypes
import multiprocessing
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image
from multiprocessing import Pool
from mpl_toolkits.mplot3d import Axes3D
try:
import torch
from torch.autograd import Variable
excep... | L04Emsemble/Bases.py | MIT | 22,295 | 3a1b1527554b56c3323c33132cd574f161b02cac | Python | py | |
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. 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 ap... | src/transformers/trainer.py | Apache-2.0 | 156,681 | 3a1b22f7957c542bf8efaae5f5ea2ee19a43b878 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from datetime import datetime
from pandas import read_csv
from numpy import vstack
from sklearn.metrics import mean_squared_error, mean_absolute_error
import numpy as np
from torchvision import transforms, datasets
cla... | WholesalePred/Algorithms/NeuralNetworkTest.py | MIT | 2,774 | 3a1b5d2d590f401b7299db3c46edb5221dafa356 | Python | py | |
import torch
model_dt = {}
def register(name):
def decorator(cls):
model_dt[name] = cls
return cls
return decorator
def make(name, **kwargs):
if name is None:
return None
model = model_dt[name](**kwargs)
if torch.cuda.is_available():
model.cuda()
return model
... | models/models.py | MIT | 662 | 3a1b63f92310662a2aaf96e0fa9905d7cf7739ae | Python | py | |
import numpy as np
import torch.nn as nn
import torch
import torch.optim as optim
from RNN_Cell import OrthoRNNCell, RNNCell, OrthoRNNCell2
from cells import RNNCell1, RNNCell2, RNNCellLT, EURNNCell
from LSTM import LSTM
from expRNN.exprnn import ExpRNN, ExpRNN2
import argparse
from expRNN.initialization import (henaff... | utils.py | MIT | 7,558 | 03bc6f5f305238678e2f8ea97c302ff700a38729 | Python | py | |
import torch
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from .utils import Dtype, Stream, load_kernel
CUDA_NUM_THREADS = 1024
kernel_loop = '''
#define CUDA_KERNEL_LOOP(i, n) \
for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
i < (n); ... | projects/DensePose/sannet/lib/sa/functions/subtraction2_refpad.py | Apache-2.0 | 12,388 | 1e6f10e64f74fbc4ff0b8a99f4e308517d8e5b96 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import config as c
from utils import (
save_model,
load_model,
get_transforms,
get_loader,
get_error
)
from model import ResNet50
from dataset import ImageDataset
def train(model, loader, optimizer, loss_fn, scheduler):
model.train(... | siamese_resnet/training.py | MIT | 2,736 | ff079e5cb273513f63c11ed1539b54d212275c78 | Python | py | |
from typing import Dict, List
import logging
from overrides import overrides
from pytorch_transformers.tokenization_auto import AutoTokenizer
import torch
from allennlp.common.util import pad_sequence_to_length
from allennlp.data.vocabulary import Vocabulary
from allennlp.data.tokenizers.token import Token
from allen... | allennlp/data/token_indexers/pretrained_transformer_indexer.py | Apache-2.0 | 4,678 | 7cb68933b24c4aa6bda8ff89ac1c45d372082dfb | Python | py | |
# !/usr/bin/env python
# coding=UTF-8
"""
@Author: WEN Hao
@LastEditors: WEN Hao
@Description:
@Date: 2021-08-03
@LastEditTime: 2022-04-15
文本对抗攻击的原样本、对抗样本的类,包含切词,POS等基本操作,
主要基于TextAttack的AttackedText类进行的实现
"""
import math
import re
import warnings
from collections import OrderedDict, Counter
from copy import deepcop... | utils/attacked_text.py | MIT | 27,767 | 3a1bb54851d4f28e4423073ad5b6cb9bc9e0a655 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.