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 gym
import ptan
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
HIDDEN_SIZE = 128
BATCH_SIZE = 16
TGT_NET_SYNC = 10
GAMMA = 0.9
REPLAY_SIZE = 1000
LR = 1e-3
EPS_DECAY=0.99
class Net(nn.Module):
def __init__(self, obs_size, hidden_size, n_actions):
su... | z_externals/handson_second_edition/Chapter07/06_cartpole.py | MIT | 3,027 | 3adf1c6d1b1dcfdf7d4944c59c6e933ca2bcd031 | Python | py | |
import torch
import random
import numpy as np
import torch.nn as nn
import mmd
import visdom
import os
import matplotlib.pyplot as plt
from models.DaNN_model import DaNN
from proto_data_utils.Data_generator_normalize import data_generate
from proto_data_utils.train_utils import weights_init, weights_init2, set_seed
fro... | Comparison/venv/Include/DaNN_main.py | MIT | 15,446 | 03956f28e1df2c57c40ce4c29c4ca863ff397e95 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.distribution import sample_from_discretized_mix_logistic
from utils.display import *
from utils.dsp import *
import numpy as np
from pathlib import Path
from typing import Union
class ResBlock(nn.Module):
def __init__(self, dims):
... | wavernn/models/fatchord_version.py | MIT | 15,523 | 1e4d45b4d8f66ad4486cca26cd00c6aadb6098df | Python | py | |
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit import RDLogger
RDLogger.DisableLog("rdApp.*")
from rdkit.Chem import rdmolops
import numpy as np
from molgpka.utils.ionization_group import get_ionization_aid
import torch
from torch_geometric.data import Data
def one_hot(x, allowable_set):
if x... | molgpka/utils/descriptor.py | MIT | 4,317 | b2fa1dfa81e09ffca49ea9505c39b3735a942f2f | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import kaiming_init
from mmdet.core import auto_fp16, force_fp32
from mmdet.ops import ConvModule
from ..registry import HEADS
@HEADS.register_module
class FusedSemanticHead(nn.Module):
"""Multi-level fused semantic segmentation head.
in_1 ... | mmdet/models/mask_heads/fused_semantic_head.py | Apache-2.0 | 3,555 | 3adf41af4fd53e66a041d01817919362a9578d07 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: zcy
# @Date: 2019-01-13 16:54:20
# @Last Modified by: zcy
# @Last Modified time: 2019-02-11 11:52:32
import logging # 引入logging模块
import os
import torch.utils.model_zoo as model_zoo
from torch import load as TorchLoad
from models.classifiers.Vgg_... | models/classifiers/vgg.py | MIT | 4,357 | 3adf4551a2f04f912e56e8a0209048a259ad083f | Python | py | |
# -*- coding: utf-8 -*-
"""ViT CNN RoPE.ipynb
Automatically generated by Colaboratory.
"""
import torch, math
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
!pip install torchsummary
from torchsummary import summary
import time
... | Models/HybridViTRoPE.py | CC0-1.0 | 10,950 | 459e85bbe824300330f5d5e7dc601522eb178142 | Python | py | |
import copy
import inspect
import logging
import os
import warnings
from typing import List, Optional, Union, Tuple, Callable, Dict
import numpy as np
import pandas as pd
import torch
import torch.distributions as distributions
from tqdm import tqdm
from matplotlib import pyplot as plt
from sklearn.cluster import KMea... | pyscutils/posterior_nolibsize.py | BSD-3-Clause | 74,613 | 1054a446fe1f74b6ca96ed9d6c8fa8e22767fc44 | Python | py | |
#!/usr/bin/env python
import os
from pathlib import Path
from typing import Dict, List
import fire
import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from transformers.utils.logging import get_logger
logger = get_logger(__name__)
def remove_prefix(text: str, prefix: str):
if text.star... | examples/research_projects/seq2seq-distillation/convert_pl_checkpoint_to_hf.py | Apache-2.0 | 2,478 | 5f3c984f3724c1cb46ffcdc9e57b20a391a423cf | Python | py | |
import os
import torch
import numpy as np
import torch.utils.data
import matplotlib.pyplot as plt
from torch.autograd import Variable
import torchvision
from torchvision import datasets, models, transforms
from model import fixed_transforms, fixed_dataloader
plt.ion() # interactive mode: pyplot functions automaticall... | model/utils.py | MIT | 10,274 | 1ec9278e3fabb885cf07948160e33287e1b9cd92 | Python | py | |
import torch.nn as nn
from model.model_zoo import GoalGAN, GoalGANDiscriminator
def init_weights(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
nn.init.kaiming_normal_(m.weight)
def get_model(cfg):
"""
Loads Generator and Discriminator
"""
generator = GoalGAN... | model/get_model.py | MIT | 485 | 3adfc3a35135229a60cec722f347680ce7732c46 | Python | py | |
# Copyright 2021 cstsunfu. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | dlk/core/losses/mse.py | Apache-2.0 | 5,004 | 5e412201538f07c9c8f8ba697931b6a274c31a59 | Python | py | |
import scipy.io
import torch
import numpy as np
import os
import argparse
import json
parser = argparse.ArgumentParser(description='Evaluating')
parser.add_argument('--loss_type', default='soft', type=str)
parser.add_argument('--name', default='resnet_50', type=str, help='output model name')
parser.add_argument('--att... | evaluate_adv.py | MIT | 3,434 | 52ba96dd100f9cd099f3425dae20f029ee242b1d | Python | py | |
#!/usr/bin/env python3
from torch_geometric.utils import remove_isolated_nodes
import torch
from torch_geometric.data import Data
import spectrum
from itertools import compress
from heapq import heappush, heappop, _heappop_max
def dict_graph_to_f_t_c_graph(graph_dict):
_from = []
_to = []
_char = []
f... | python/graph_utils.py | Apache-2.0 | 7,582 | e9cfde6925df6d5a709eb404ecfeeea7dece5379 | Python | py | |
import copy
from typing import Optional, Any
import torch
from torch import nn,Tensor
import torch.nn.functional as F
from torch.nn import Module
from torch.nn import MultiheadAttention
from torch.nn import ModuleList
from torch.nn.init import xavier_uniform_
from torch.nn import Dropout
class TIF(nn.Module):
de... | pysot/models/utile/trantime.py | Apache-2.0 | 15,420 | 42a5c90316490b7b562aaf249969d56ba964055b | Python | py | |
"""
Meta-tests on ALL languages.
Uses allennlp predict wrapper, which requires a .tar.gz file, which are now created for every language: takes long!
"""
from allennlp.models.archival import archive_model
from get_language_dataset import get_language_dataset
from params_all_in_one_file import get_params
from allennlp.mo... | metatest_all.py | MIT | 4,863 | 3adff9bdaf6132f9e3611a05898212e24380a743 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import rospy
from typing import Any, Dict, List, Optional
import glob
import os
import time
import subprocess
from collections import deque
from test_env_exploration4 import GazeboEnv
import numpy as np
import gym.spaces as spaces
from base.spaces ... | TD3/ppo_exploration_42.py | MIT | 33,195 | 3ae0245e39f276568736d4c4f6c8ed3e3ef6a3df | Python | py | |
"""
nets.py
========================
torch.nn modules that can be used as the classification method.
"""
import itertools as it
import torch
import torch.nn as nn
from src.features import window as window_module
class Model(nn.Module):
"""Abstract base class for all the post-signature models we consider. Each sub... | src/models/nets.py | MIT | 26,911 | 29f3414a41dc2371c8a3d22765c351b302a3ba5c | Python | py | |
## TODO: define the convolutional neural network architecture
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init_... | models.py | MIT | 2,720 | 3ae0367f4c5548554319dec499c9b533734bdb49 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import collections
import itertools
import time
import torch
import torch.distributed as dist
import communication
import runtime_utilities
IMAGE_CLASSIFICATION = "image_classification"
TRANSLATION = "translation"
SPEECH_TO_TEXT = "speech_to_te... | runtime/runtime.py | MIT | 29,629 | 3ae04bda67cc7ff97c80609f533c7ed542a24a6c | Python | py | |
import torch as th
from torch.utils.data import Dataset
import pandas as pd
import os
import numpy as np
import ffmpeg
import math
from data_utils import convert_to_float
from yuv_reader import read_yuv420p
class VideoLoader(Dataset):
"""Pytorch video loader."""
def __init__(
self,
cs... | slowfast/extract_feature/video_loader.py | MIT | 5,721 | 3ae056dc090d05fa9dcc98a994021b8063abb178 | Python | py | |
from __future__ import absolute_import
import torch
from torch import nn
class CenterLoss(nn.Module):
"""Center loss.
Reference:
Wen et al. A Discriminative Feature Learning Approach for Deep Face Recognition. ECCV 2016.
Args:
num_classes (int): number of classes.
feat_dim (int): fe... | layers/center_loss.py | MIT | 2,358 | 45734a7caf44d239577170757f2e741d180523a8 | Python | py | |
# -*- coding:utf-8 -*-
from collections import OrderedDict
import torch.nn as nn
from mmdet.models.utils import brick as vn_layer
class YOLOV3(nn.Module):
# 用于递归导入权重
custom_layers = (vn_layer.Stage, vn_layer.Stage.custom_layers, vn_layer.HeadBody, vn_layer.Transition,
vn_layer.Head)
... | tools/darknet/yolov3.py | MIT | 6,332 | 3ae05ceeef3689c56e067a04dfa9492b7d77fa6e | Python | py | |
# train.py
from utils import *
from config import Config
from sklearn.model_selection import train_test_split
import numpy as np
from tqdm import tqdm
import sys
import torch.optim as optim
from torch import nn, Tensor
from torch.autograd import Variable
import torch
from sklearn.metrics import accuracy_score
def get... | Model_TextCNN/old_code/train.py | MIT | 3,445 | 3ae068b2333320fc2df10e17abb45e53ac8933ee | Python | py | |
import os
import os.path
import numpy as np
import torch
import torch.nn as nn
from torch.cuda.amp import autocast as autocast
from . import networks
from . import feature2face_G
from .base_model import BaseModel
from .losses import GANLoss, MaskedL1Loss, VGGLoss
class Feature2FaceModel(BaseModel): ... | models/feature2face_model.py | MIT | 10,420 | 24d5a9828c2489746a0d84319d15ab8604fa8761 | Python | py | |
""" torchsummary.py """
from typing import Any, Dict, Generator, List, Optional, Sequence, Union
import torch
import torch.nn as nn
from torch.utils.hooks import RemovableHandle
from .formatting import FormattingOptions, Verbosity
from .layer_info import LayerInfo
from .model_statistics import CORRECTED_INPUT_SIZE_TY... | torchsummary/torchsummary.py | MIT | 8,862 | fd9c2b1436c3f67d1c6888f0f566df18a956142a | Python | py | |
import unittest
from tramp.channels import (
AbsChannel, SgnChannel, ReluChannel, LeakyReluChannel, HardTanhChannel,
MultiConvChannel, LinearChannel, DiagonalChannel, UpsampleChannel
)
from tramp.ensembles import Multi2dConvEnsemble
import numpy as np
import torch
def empirical_second_moment(tau_z, channel):
... | tramp/tests/test_channels.py | MIT | 14,563 | 1e85e0203196f9e38367eeba323aceb8d0d0104b | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers.crf import CRF
from .transformer.modeling_albert import AlbertPreTrainedModel
from .transformer.modeling_albert import AlbertModel
from .layers.linears import PoolerEndLogits, PoolerStartLogits
from torch.nn import CrossEntropyLoss
... | unlp/supervised/ner/nmodels/albert_for_ner.py | MIT | 6,459 | 5ec5c2a79c9c391b0cce489476e335df41275cf0 | Python | py | |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# NOTICE FILE in the root directory of this source tree.
#
from logging import getLogger
import math
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn... | MASS-unsupNMT/src/model/transformer.py | MIT | 29,599 | 12803975660bfc4ba4802aac79142780de205767 | Python | py | |
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""You may copy this file as the starting point of your own model."""
import zipfile
from hashlib import sha384
from os import listdir
from os import path
import numpy as np
import PIL
from skimage import io
from torch.utils.data impor... | openfl-workspace/torch_unet_kvasir/src/data_loader.py | Apache-2.0 | 4,962 | 3ae0b8e65e6965c923389669eeff32b1e1687235 | Python | py | |
'''
EXTD Copyright (c) 2019-present NAVER Corp. MIT License
'''
#-*- coding:utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
import torch
import argparse
import torch.nn as nn
import torch.utils.data as data
import torch.bac... | demo.py | MIT | 4,315 | 3ae0fec4f90b44c09d428d270699d8433d514d74 | Python | py | |
import torch
import numpy as np
def func(dat, pho=10, alpha=1, lambda1=1):
cuda = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.tensor(dat, device=cuda).float()
n = x.size()[0]
batch_num = x.size()[1]
w = torch.rand(n, n, device=cuda, requires_grad=True)
de... | ylearn/causal_discovery/dag.py | Apache-2.0 | 2,821 | 3ae112670c0d1962bed6802d117e85b42dfbb8ca | Python | py | |
from __future__ import absolute_import
import argparse
import os
import re
from collections import OrderedDict
import torch
def convert_old_parameters(params):
"""Convert parameters from the old model to the new one."""
# type: OrderedDict -> OrderedDict
new_params = []
for k, v in params.items():
... | laia/utils/convert_old_model_checkpoint.py | MIT | 1,495 | 3ae12cebe3cf2b6d5b1e436637b73fb2fb8abe7a | Python | py | |
import sys
import torch
import torch._utils
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
from SPPE.src.models.FastPose import createModel
from SPPE.src.utils.img import flip, shuffleLR
try:
torch._utils._rebuild_tensor_v2
except AttributeError:
def _rebuild_tensor_v2(stor... | joints_detectors/Alphapose/SPPE/src/main_fast_inference.py | MIT | 1,925 | ff782469885215e83fa820d0bd9d0bbe886050a2 | Python | py | |
#!/usr/bin/env python3
#
# Copyright 2021 Xiaomi Corporation (Author: Fangjun Kuang)
#
# See ../../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of ... | egs/librispeech/ASR/pruned_transducer_stateless2/decode.py | Apache-2.0 | 17,153 | d7d6b1202ad85a60fef47dc947725cf5d4fb9bc4 | Python | py | |
from utils.argument import get_main_argument
from utils.log import get_logger
from os.path import join, exists
from os import makedirs
import torch
import json
import random
import numpy as np
import warnings
import os
def init_rng(seed=0):
random.seed(seed)
np.random.seed(seed)
torch.random.... | utils/context.py | MIT | 4,723 | 4b795aa951f728e0f84eb79995b8cca09ad8de6e | Python | py | |
import torch
import numpy as np
import cv2
from model import UNet, LC2RGB
import time
img_path = "test.jpg"
model = UNet()
model.load_state_dict(torch.load("model/0.pth", map_location = torch.device("cpu")))
img = cv2.imread(img_path)
img = cv2.resize(img, (256, 256))
img = 2*(img/255) - 1
output = model.generate(t... | ml/test.py | MIT | 590 | e98da5ccf3f87522813d99eecad6f24931d7ef3a | Python | py | |
from __future__ import division
from __future__ import print_function
import time
import argparse
import pickle
import os
import datetime
import torch.optim as optim
from torch.optim import lr_scheduler
from utils import *
from modules import *
parser = argparse.ArgumentParser()
parser.add_argument('--no-cuda', act... | train.py | MIT | 16,102 | 5e275c55c6b7ab4b42f85f573eb2870744fdaadd | Python | py | |
import os
from datetime import datetime
import pickle
import numpy as np
from sacred import Experiment
from sacred.commands import print_config, save_config
from sacred.observers import FileStorageObserver
from torch.nn.utils import clip_grad_norm_
from torch.optim.lr_scheduler import StepLR
from torch.utils.data im... | evaluate.py | MIT | 3,387 | 107225a88f70687c3324436173c04a5a47e15988 | Python | py | |
# --------------------------------------------------------
# SiamMask
# Licensed under The MIT License
# Written by Qiang Wang (wangqiang2015 at ia.ac.cn)
# Revised for THOR by Axel Sauer (axel.sauer@tum.de)
# --------------------------------------------------------
from __future__ import division
import argparse
impo... | thor/trackers/SiamMask/siammask.py | MIT | 5,842 | 3ae1773af3c79db375687b969e1d255b7e429ca4 | Python | py | |
import pathlib
import math
import json
from tqdm import tqdm
import pandas as pd
import numpy as np
import cv2
import torch
import os
from .dataset import BaseDataset
from libs.utils.image import load_image, Resize
from libs.utils.heatmap import heatmap_from_kps
from libs.utils.image import mean_std_normalize
import to... | libs/dataset/cofw_dataset.py | MIT | 4,507 | 3ae181d57f196b2c9936035c32aa19e69d87f60e | Python | py | |
# -*- coding: utf-8 -*-
r"""
malware_gan.malware_gan
~~~~~~~~~~~~~~~
MalGAN complete architecture.
Based on the paper: "Generating Adversarial Malware Examples for Black-Box Attacks Based on GAN"
By Weiwei Hu and Ying Tan.
"""
import logging
import os
from enum import Enum
from typing import List, T... | malware_gan/malware_gan.py | MIT | 18,617 | 705a5e99db6e8dbbe51da58a0750711dd4ac1f25 | Python | py | |
import torch
import torch.nn as nn
class UNet3D(nn.Module):
def __init__(self, in_channel, n_classes):
self.in_channel = in_channel
self.n_classes = n_classes
super(UNet3D, self).__init__()
self.ec0 = self.encoder(self.in_channel, 32, bias=False, batchnorm=False)
self.ec1 =... | pytorch/model.py | MIT | 3,599 | fdbf5d346c596b15ed39108d549e413e9a296110 | Python | py | |
from copy import deepcopy
import pytest
import torch
from mmgen.models.architectures.cyclegan import ResnetGenerator
class TestResnetGenerator:
@classmethod
def setup_class(cls):
cls.default_cfg = dict(
in_channels=3,
out_channels=3,
base_channels=64,
... | tests/test_modules/test_cyclegan_archs.py | Apache-2.0 | 1,520 | 3ae1952ada8fd01e184e53b668010b16f121a876 | Python | py | |
"""
UNET model same as that of Facebook's but with processing steps included in the model.
"""
import torch
from torch import nn
from torch.nn import functional as F
# This is a normalized ifft2D with ifftshift already included.
from data.data_transforms import ifft2, nchw_to_kspace, complex_abs
class ConvBlock(nn.... | models/k_unet_model.py | MIT | 5,080 | cc2f767ebab08292aa4a8b6125db29d80c297f85 | Python | py | |
from __future__ import absolute_import, division, print_function
import argparse
import csv
import logging
import os
import random
import sys
import json
import numpy as np
import pandas as pd
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
Tensor... | run_ssidw.py | MIT | 35,288 | ffa2c80c9001d48c8c31fde7aa2a2b1f671088a3 | Python | py | |
import torch
import os
import torch.utils.data as data
import numpy as np
from tqdm import tqdm
from collections import defaultdict
from lib.loss import DescriptorLoss, TransformationLoss, ClassificationLoss
class Trainer():
'''
Trainer class of the pairwise registration network.
Args:
... | lib/pairwise/training.py | MIT | 8,554 | b2a9a9c81afb5f70e577b13f8af15997094083a9 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LM(nn.Module):
def __init__(self, word_size,
word_dim, hidden_dim):
super(LM, self).__init__()
self.word_size = word_size
self.word_dim = word_dim
self.hidden_dim = hidden_dim
# EMBEDDIN... | src/lm.py | MIT | 1,816 | 3ae210b013c8abae354c6391362a0c10d829571f | Python | py | |
import torch
import torch.utils.data as data
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import torchvision
from torchvision import datasets, transforms
from to... | detectactions-I3DPose/ava_test.py | MIT | 8,419 | 3ae2143d70f13342290f0b7458370c53f57bdc1d | Python | py | |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
... | P2_Image_Captioning/model.py | MIT | 3,481 | 3ae226dea6edeed8262e0743e47c96c888e700fd | Python | py | |
import torch
import torch.nn as nn
import math
import numbers
from torch.nn import functional as F
import numpy as np
def LoG(imgHF):
weight = [
[0, 0, 1, 0, 0],
[0, 1, 2, 1, 0],
[1, 2, -16, 2, 1],
[0, 1, 2, 1, 0],
[0, 0, 1, 0, 0]
]
weight = np.array(weight)
... | codes/models/modules/loss.py | Apache-2.0 | 6,996 | 24d9225403df1454ef1f130792eade9a1f831973 | Python | py | |
import matplotlib.pyplot as plt
import numpy as np
import torch
def multiclass_accuracy(y_pred,y_true):
top_p,top_class = y_pred.topk(1,dim = 1)
equals = top_class == y_true.view(*top_class.shape)
return torch.mean(equals.type(torch.FloatTensor))
def view_classify(img, ps):
ps = ps.data.numpy().s... | Neural_Networks_Pytorch/utils.py | MIT | 714 | 03b7bd2c3da444b189dda90c8a325e4bd8010633 | Python | py | |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import os
import logging
import numpy as np
import time
import weakref
import torch
import detectron2.utils.comm as comm
from detectron2.utils.events import EventStorage
__all__ = ["HookBase", "TrainerBase", "SimpleTrainer... | detectron2/engine/train_loop.py | Apache-2.0 | 9,710 | 03be5a079329cdf8e1378cb23c2d0c509f4fca81 | Python | py | |
import torch
import numpy as np
from utils.utils import model_device
from callback.progressbar import ProgressBar
from sklearn.metrics import f1_score
class Predictor(object):
def __init__(self,
model,
logger,
n_gpu
):
self.model = model
... | mltc/predict/predictor.py | MIT | 2,002 | dfd0043b812be5de6ecb710f1d4c8dad86d25865 | Python | py | |
import cv2 as cv
import os
import numpy
import numpy as np
import torch
# uv = torch.tensor([[[345, 240], # 0
# [300, 225],
# [255, 195],
# [210, 180],
# [180, 180],
# [195, 255], # 5
# [120, 255],... | add_effects.py | MIT | 7,260 | 7c549564e45daff8ce610d594333d99a0a7ae439 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
def dot_prod_attention(h_t, src_encoding, src_encoding_att_linear, mask=None):
"""
:param h_t: (batch_size, hidden_size)
:param src_encoding: (batch_size, src_sent_len, hidden_size * 2)
:param src_encoding_att_linear: (batch_size, src_... | nn_self/attention.py | MIT | 3,436 | 3ae2540293fa4532806ee9b44bb74a195808412a | Python | py | |
import os
from pathlib import Path
from unittest import TestCase
import numpy as np
import pytest
from datasets.utils.file_utils import DownloadConfig, cached_path, temp_seed
from .utils import require_tf, require_torch
class TempSeedTest(TestCase):
@require_tf
def test_tensorflow(self):
import ten... | tests/test_file_utils.py | Apache-2.0 | 2,895 | 3ae262934c114d7c901f247eef16108785921718 | Python | py | |
import torch
from nam.config.base import Config
def defaults() -> Config:
config = Config(
device='cuda' if torch.cuda.is_available() else 'cpu',
seed=2021,
## Data Path
data_path="data/GALLUP.csv",
experiment_name="NAM",
regression=False,
## training
... | nam/config/default.py | MIT | 1,312 | 7cce3806893b3c61cf5ad107e45d47d7e1cd8a20 | Python | py | |
import os
import glob
import torch
from bs4 import BeautifulSoup
from torchsenti.datasets.utils import download_and_extract_archive
class ProsAndCons:
"""
dataset is from www.cs.uic.edu/~liub/FBS/pros-cons.rar
"""
resources = ('https://www.cs.uic.edu/~liub/FBS/pros-cons.rar')
def __init_... | torchsenti/datasets/pros_and_cons.py | MIT | 2,692 | 12e669f10ca108e894f82652a98ccc62ea59c421 | Python | py | |
# This file is covered under the Apache 2.0 License listed here
# <https://github.com/fartashf/vsepp/blob/master/LICENSE> as it is a
# Derivative Work of the repo.
import torch
from torch import optim
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence, pad_pa... | parlai/agents/vsepp_caption/modules.py | BSD-3-Clause | 6,872 | 3ae281523b33f70e81cfbed3251f99fc56847743 | Python | py | |
import argparse
import os
from tqdm import tqdm
import time
import datetime
import torch
import torch.nn as nn
import torch.multiprocessing as mp
import torch.distributed as dist
import torch.backends.cudnn as cudnn
import tensorboardX
import numpy as np
import lib
from lib.utils import adjust_learning_rate, cross_entr... | dist_train.py | Apache-2.0 | 12,487 | e957f52e35566ba78969165b60ac84d9487f25a6 | Python | py | |
""" Parts of the U-Net model """
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_c... | unet/unet_parts.py | BSD-3-Clause | 2,591 | 3ae292ef809578c7635344f45ea1937c93da8d0e | Python | py | |
import torch
class LossScaler:
def __init__(self, scale=1):
self.cur_scale = scale
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
return False
# `overflow`... | loss_scaler.py | BSD-3-Clause | 4,397 | 45b4f5e11dd6034bf9b22a9c916dacf52c9d9de3 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import functools
ENCODER_RESNET = [
'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152',
'resnext50_32x4d', 'resnext101_32x8d'
]
ENCODER_DENSENET = [
'densenet121', 'densenet... | model.py | MIT | 9,975 | 3ae2a8b3b909e0183752e3f651adb4abcfd701a7 | Python | py | |
# Copyright 2020 The OATomobile 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 applica... | oatomobile/baselines/torch/dim/train.py | Apache-2.0 | 10,389 | 3ae2bbc8be5cd8ef51ec6e4f1092fcd48b77f183 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
class A2C():
def __init__(self,
args,
actor_critic,
value_loss_coef,
entropy_coef,
lr=None,
eps=None,
alpha=None,
ma... | a2c_ppo_acktr/algo/a2c_acktr.py | MIT | 2,444 | 80359e2f10c702ba81fdb9bf2aca3e4d8d8afdd2 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | built-in/PyTorch/Official/cv/image_object_detection/Faster_Mask_RCNN_for_PyTorch_Dynamic_Shape/detectron2/modeling/poolers.py | Apache-2.0 | 11,098 | 5eb58d787c6cdf9bb2a36b046c4d738f8bc5d00f | Python | py | |
from __future__ import absolute_import, division, print_function, unicode_literals
import torch
import torch.nn as nn
from torch import Tensor # noqa: F401
from torch.nn import _VF
from torch._jit_internal import Tuple, Optional, List # noqa: F401
from torch.nn.utils.rnn import PackedSequence
import numbers
def ap... | venv/Lib/site-packages/torch/nn/quantized/dynamic/modules/rnn.py | Apache-2.0 | 17,326 | 5e945b92151b8c4a989f53f7bf48c265ba36fce7 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'han'
import math
import h5py
import torch
import torch.nn.functional as F
import numpy as np
from dataset.preprocess_data import PreprocessData
from utils.functions import masked_softmax, compute_mask, masked_flip
class GloveEmbedding(torch.nn.Module):
... | models/layers.py | MIT | 38,472 | f9e4492d178b8953ef7d1c2c5186dc752ff474e7 | Python | py | |
# -*- coding: utf-8 -*-
# Function that loads a checkpoint and rebuilds the model
import torch
from torch import nn
from collections import OrderedDict
from torchvision import datasets, transforms, models
def save_checkpoint(model, checkpoint_path, output_categories):
'''
Save the trained deep... | image_classifier/model_lib.py | MIT | 3,726 | 3ae33afc12f8987d0c85ee05a95ac1ec3a4be0c6 | Python | py | |
import pytorch_lightning as pl
from lightning_GSDRUNet import GradMatch
from data_module import DataModule
from pytorch_lightning import loggers as pl_loggers
import os
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from argparse import ArgumentParser
import random
import torch
if __name__ == '__... | GS_denoising/main_train.py | MIT | 2,687 | 3ae33c5313544bc1b422decb71e0b620e273da0a | Python | py | |
import torch
class BaseModel(torch.nn.Module):
"""Base PyTorch model for all models.
To do: add some useful common features
"""
def __init__(self):
super(BaseModel, self).__init__()
class Vocabulary(object):
"""A look-up table that allows you to access `Lexeme` objects. The `Vocab`
... | fastNLP/models/base_model.py | Apache-2.0 | 2,599 | 24dfdb850423b6e202e8a76a8524210363b96366 | Python | py | |
import json
import numpy as np
import torch
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer
stop_words = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his... | construct_label_desc.py | MIT | 3,301 | 3ae34aeb83bdef472da34839330a0a2a141e858b | Python | py | |
# Copyright 2018 University of Basel, Center for medical Image Analysis and Navigation
#
# 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
#
# U... | examples/affine_registration_2d.py | Apache-2.0 | 3,516 | 3ae34d9c57f78ace9719a4bcc072629f230b7539 | Python | py | |
import torch
import torch.nn.functional as F
import numpy as np
import albumentations as A
# boxes = (cls, x, y, w, h)
def horizontal_flip(images, boxes):
images = np.flip(images, [-1])
boxes[:, 1] = 1 - boxes[:, 1]
return images, boxes
# images[np.unit8], boxes[numpy] = (cls, x, y, w, h)
def augment(im... | utils/augmentations.py | MIT | 1,703 | 801587cd0ad05754df778c99f8d60b4ce9bb8336 | Python | py | |
from __future__ import print_function
import sys
import os
import argparse
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
from torch.autograd import Variable
import sys
sys.path.append(".")
from data import VOC_ROOT, VOC_CLASSES as labelmap
from PIL... | test/test.py | MIT | 4,001 | 4b674bf9515d214aef23cb53e73a2cf3ea69bb28 | Python | py | |
#!/usr/bin/env python
"""
BSD 2-Clause License
Copyright (c) 2021 (monika.heinzl@edumail.at)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copy... | basecaller-modules/early_stopping.py | BSD-2-Clause | 4,745 | 3ae37e7ec67d796425ab73ab4fbb18f341dd957d | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from typing import Dict, List, Optional
import torch
import torch.nn as nn
from fairseq import search, utils
from fairseq.data im... | fairseq/sequence_generator.py | MIT | 40,767 | 3ae3885730cd8df358b4c68ef0124ff6ac6bb86f | Python | py | |
#!/usr/bin/env python3
# Copyright 2018-present, HKUST-KnowComp.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Data processing/loading helpers."""
import numpy as np
import logging
import unicodedata
from torch.utils... | wrmcqa/reader/data.py | BSD-3-Clause | 4,044 | 5f24a41dffed701991067f9abaf82053921dfcd3 | Python | py | |
from __future__ import print_function
#from __future__ import division, print_function
import matplotlib
matplotlib.use('Agg')
import os
import errno
import numpy as np
from PIL import Image
import sys
from copy import deepcopy
import argparse
import math
import torch.utils.data as data
import torch
import torch.nn.ini... | train_OriNet_test_on_graffity.py | MIT | 18,895 | 7c59f6b655f36a08d3c87782049565ec9d06c114 | Python | py | |
import os
import time
from multiprocessing import Process
from typing import Tuple
from collections import OrderedDict
import flwr as fl
import numpy as np
from flwr.server.strategy import FedAvg
import torch
import dataset
from SimpleNet import SimpleNet
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() el... | examples/simulation_pytorch_legacy/simulation.py | Apache-2.0 | 4,098 | 1e8e5129ae745a6aafa96b97dc424b536404e94b | Python | py | |
# standard lib
import random
import math
import pdb
# 3rd-party lib
import numpy as np
import torch
from torch.nn.modules.batchnorm import _BatchNorm
# mm lib
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner,
... | gaiadet/apis/train.py | Apache-2.0 | 6,810 | 3ae3c73b06e861273a4d229f5482983a542d9eed | Python | py | |
import torch
class PullAwayLoss(torch.nn.Module):
"""
Pull Away Loss for the Energy-Based GANs
References
----------
`Paper <https://arxiv.org/abs/1609.03126>`_
"""
def __init__(self, weight=1.):
"""
Parameters
----------
weight : float
weight f... | dlutils/losses/pull_away.py | MIT | 1,154 | 5fc3decdc668a48e3c95f4a9966adfaf107689b9 | Python | py | |
import json
import torch
import torch.legacy.optim as optim
from pprint import pprint
def rosenbrock(tensor):
x, y = tensor
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
def drosenbrock(tensor):
x, y = tensor
return torch.DoubleTensor((-400 * x * (y - x ** 2) - 2 * (1 - x), 200 * (y - x ** 2)))
alg... | 3rdparty/pytorch/test/optim/test.py | MIT | 1,148 | 459bc0f29e2d449baf3845e2435388d5a32cd101 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.parallel
from misc.config import cfg
from torch.autograd import Variable
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=Fa... | model.py | MIT | 10,484 | fce0954926c8f5f0ac9319c165c734db1fa68432 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class NoisyLinear(nn.Linear):
def __init__(self, in_features, out_features, sigma_init=0.017, bias=True):
super().__init__(in_features, out_features, bias=bias)
self.sigma_weight = nn.Parameter(
torch.Tenso... | catalyst/contrib/modules/noisy.py | Apache-2.0 | 2,664 | d73b5fee0e8d288e22d56f66c60933df1ade1000 | Python | py | |
""" Audio encoder """
import math
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from onmt.utils.rnn_factory import rnn_factory
from onmt.encoders.encoder import EncoderBase
class AudioEncoder(EncoderBase):
"""
... | onmt/encoders/audio_encoder.py | MIT | 5,485 | a960a2aa806daf2bc74ccf93b29ab4cc95f6a4ab | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This software and supporting documentation are distributed by
# Institut Federatif de Recherche 49
# CEA/NeuroSpin, Batiment 145,
# 91191 Gif-sur-Yvette cedex
# France
#
# This software is governed by the CeCILL license version 2 under
# French law ... | contrastive/data/datasets.py | MIT | 14,632 | 3ae4868b025271b9c089f205e0c70968525fafd5 | Python | py | |
import datetime
import glob
import json
import librosa
import lmdb
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
import pyarrow
import python_speech_features as ps
import threading
import time
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functio... | processor_v2.py | MIT | 77,607 | 3ae48e04a9e63d806365b6c7a1306135c3eb5f35 | Python | py | |
import setuptools
from setuptools import setup
install_deps = ['numpy>=1.20.0', 'scipy', 'natsort',
'tifffile', 'tqdm', 'numba',
'torch>=1.6',
'opencv-python-headless',
'fastremap'
]
gui_deps = [
'pyqtgraph>=0.11.0rc0',
... | setup.py | BSD-3-Clause | 1,850 | 3ae4940a45ec844e237f2568381d06bb57321929 | Python | py | |
import os
import torch
import cv2
import torch.nn as nn
import numpy as np
from PIL import Image
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
STEREO_SCALE_FACTOR = 5.4
def rot_from_axisangle(vec):
"""Convert an axisangle rotation into a 4x4 transformation matrix
(adapte... | tools.py | MIT | 7,909 | 29fa02f4a81209d636725e82549663ce9e01e798 | Python | py | |
import copy
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchtext.data import Batch
def averge_models(models, device=None):
final_model = copy.deepcopy(models[0])
if device:
models = [model.to(device) for model in models]
final_model = final_model.to(device)
averaged_paramete... | pytorch/utils/utils.py | MIT | 7,689 | 3ae4b2634727a7a3c18f2473fe0c51212182326b | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
from os import path as osp
import mmcv
import torch
from mmcv.ops import Voxelization
from mmcv.parallel import DataContainer as DC
from mmcv.runner import force_fp32
from torch.nn import functional as F
from mmdet3d.core import (Box3DMode, Coord3DMode, ... | mmdet3d/models/detectors/mvx_two_stage.py | Apache-2.0 | 20,932 | 1eba10df637efe6d46d8f5af0b1645719ea4f545 | Python | py | |
import os
import torch
import torch.nn as nn
import torch.utils as utils
import torch.nn.init as init
import torch.utils.data as data
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset
import torch.nn.functional as F
import torchvision.models as models
import ... | gakushu.py | MIT | 6,055 | 3ae4edb34e4b501966ad524af59f66540dbef2c3 | Python | py | |
from pathlib import Path
from marius.tools.preprocess.dataset import LinkPredictionDataset
from marius.tools.preprocess.utils import download_url, extract_file
import numpy as np
from marius.tools.preprocess.converters.torch_converter import TorchEdgeListConverter
from marius.tools.preprocess.converters.spark_converter... | src/python/tools/preprocess/datasets/ogbl_wikikg2.py | Apache-2.0 | 2,861 | 3ae4faf8ee74dfb345e737fd125ed60a438e784c | Python | py | |
import torch
from torch_geometric.nn import dense_diff_pool
def test_dense_diff_pool():
batch_size, num_nodes, channels, num_clusters = (2, 20, 16, 10)
x = torch.randn((batch_size, num_nodes, channels))
adj = torch.rand((batch_size, num_nodes, num_nodes))
s = torch.randn((batch_size, num_nodes, num_cl... | test/nn/dense/test_diff_pool.py | MIT | 608 | ff940cbba61957c94faf03fc9b755ef33195cb9a | Python | py | |
# Copyright 2018 The Texar Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | examples/torchtext/batchfirst_bptt.py | Apache-2.0 | 3,216 | a941b5d9deb4016425c88bd9d476912181920a69 | Python | py | |
from typing import Dict, Union, Set
import logging
from overrides import overrides
import torch
from stog.data.fields.field import Field
from stog.data.vocabulary import Vocabulary
from stog.utils.checks import ConfigurationError
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class LabelField... | stog/data/fields/label_field.py | Apache-2.0 | 4,803 | 3ae5186ad8fa447f94a2b837d4c091886f124e61 | 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/metrics/metrics_test.py | Apache-2.0 | 8,211 | 3ae52216cdf89eb08b136cfe0b95bd841b670ac2 | Python | py | |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... | nnunet/network_architecture/custom_modules/conv_block_for_modify_dense.py | Apache-2.0 | 14,261 | 3ae5351da26768aa8ba2a8768341b0b1dae7f744 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.