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 |
|---|---|---|---|---|---|---|---|
#! /usr/bin/env python3
""" Evalaute the model on simulations. """
import argparse
import json
import multiprocessing
import os
from os import path
import pickle
from statistics import mean
import time
from matplotlib import pyplot
import numpy as np
import torch
import models
import train
import utils
manager = mu... | model/test_all.py | BSD-3-Clause-Clear | 8,792 | 3a891b3c24c48ab589ca6f7dfebb6411a194a40d | Python | py | |
import torch
import torch.nn as nn
from .ConvBlock import ConvBlock
from .MaxPoolBlock import MaxPoolBlock
from .ParametricModule import ParametricModule
class InceptionBlock(ParametricModule):
__options__ = dict(
input_channels=None,
feature_channels=None,
output_channels=None,
p... | networks/modular_downscaling_model/base_modules/InceptionBlock.py | MIT | 3,520 | 5f05dc36e8a50892cbf5ee691e85ccb858e6c186 | Python | py | |
import math
import os
import numpy as np
import scipy.sparse as sparse
import sklearn.preprocessing as preprocessing
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.nn.pytorch import NNConv, Set2Set
from dgl.nn.pytorch.conv import GINConv
from dgl.nn.pytorch.glob import AvgPoolin... | cogdl/models/nn/dgl_gcc.py | MIT | 26,699 | f9dea8fa98c269de30d4452f8a78523b8f8ca712 | Python | py | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Version : Python 3.6
import os
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
from transformers import AdamW
from transformers import get_linear_schedule_with_warmup
from transformers import WEIGHTS_NAME, CONFIG_NAME
from config... | run.py | MIT | 6,124 | d7a57f5b198de1daf7a4d29b27a29b76ff4cfe67 | Python | py | |
import torch
import torch.nn as nn
from typing import Any
from satflow.models.base import register_model, BaseModel
from satflow.models.losses import get_loss
from pl_bolts.optimizers.lr_scheduler import LinearWarmupCosineAnnealingLR
from metnet import MetNet
@register_model
class LitMetNet(BaseModel):
def __ini... | satflow/models/pl_metnet.py | MIT | 3,881 | 5e5531d2201670db0ba24aba198238f66ab24763 | Python | py | |
from __future__ import division
import time
import os
import argparse
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
parser ... | train_model.py | MIT | 10,216 | 6527af2a95d8a7c04ef41a0566f73177082ad74a | Python | py | |
import numpy as np
from PIL import Image
from src.data.rand_augment import RandAugmentMC
import torchvision.transforms as transforms
def pad(x, border=4):
return np.pad(x, [(0, 0), (border, border), (border, border)], mode='reflect')
class RandomPadandCrop(object):
"""Crop randomly the image.
Args:
... | src/data/transforms.py | MIT | 3,601 | 03b5ce01d0f87924fc81dae8ba95563290869701 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
'''
This class defines the encoder architecture
'''
def __init__(self, input_size, hidden_size, bottleneck):
super().__init__()
self.linear1 = nn.Linear(input_size, hidden_size)
self.mean = nn.Linear(hidde... | src/model.py | MIT | 1,296 | f9ac3769b56baa86b3eefca73eb1193108bab9df | Python | py | |
import os
import imageio
import numpy as np
import torch
import model
import matplotlib.pyplot as plt
# select color or gray-scale
# color = 'gray'
color = 'color'
# define the noise level
sigma = 25
# load a test image
y = imageio.imread(os.path.join('data','water-castle.png')).astype(np.float32)/255
if color =... | denoise.py | MIT | 1,752 | 3a89bff6762faf70a1030765e9541f870d64c409 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, kaiming_init
from mmcv.runner import _load_checkpoint, load_checkpoint
from mmcv.utils import print_log
from ...utils import get_root_logger
from ..builder import BACKBONES
from .resnet3... | mmaction/models/backbones/resnet3d_slowfast.py | Apache-2.0 | 22,312 | d717b935839007ecd375ab674f2672be73a1d686 | Python | py | |
import torch
import torch.nn as nn
debug=False
# Custom Layers
class Attention(nn.Module):
def __init__(self, feature_dim, step_dim, bias=True, **kwargs):
super(Attention, self).__init__(**kwargs)
self.supports_masking = True
self.bias = bias
self.feature_dim = feature_dim... | Models/attentionLayer.py | MIT | 5,321 | 7070a6a97bea1b0f7d1d915a1255f96156c72d7b | Python | py | |
from . import register_trainer, BaseTrainer, Evaluation, EVALUATE_DICT, EarlyStopping
import torch
from torch.optim.lr_scheduler import StepLR
import torch.nn.functional as F
from ..model import MODEL_DICT, BaseModel
from .evaluate import Logloss
from typing import Union
from ...datasets import utils
from copy import d... | autogl/module/train/graph_classification.py | MIT | 17,789 | b285b793f50e18cf373ea4b1577e6603f0197408 | Python | py | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import torch
from sklearn.metrics import roc_curve,roc_auc_score
def get_default_device():
"""Pick GPU if available, else CPU"""
if torch.cuda.is_available():
return torch.device('cuda')
else:
... | utils.py | BSD-3-Clause | 2,164 | 3a8a28fee5a9d22e11c727cf0e1c454f23d2d495 | Python | py | |
from pathlib import Path
from numbers import Number
from typing import Union, Tuple, Optional
import torch
import numpy as np
import SimpleITK as sitk
from ....data.io import sitk_to_nib
from ....data.subject import Subject
from ....typing import TypeTripletFloat
from ....data.image import Image, ScalarImage
from ...... | torchio/transforms/preprocessing/spatial/resample.py | Apache-2.0 | 9,839 | 28dfc99f917537865f3eaade58892986249dcb2f | Python | py | |
"""
Losses
"""
# pylint: disable=C0301,C0103,R0902,R0915,W0221,W0622
##
# LIBRARIES
import torch
##
def l1_loss(input, target):
""" L1 Loss without reduce flag.
Args:
input (FloatTensor): Input tensor
target (FloatTensor): Output tensor
Returns:
[FloatTensor]: L1 distance betwee... | lib/loss.py | MIT | 884 | 3a8a8cd88ce174e1c3f2cc575f39d3f45cd9b177 | Python | py | |
import torch
import json
import os.path
from gridgru import GRIDGRU
from lstm import PTLSTM
from simple_layers import RNNLinear
def find_data_file(jpath):
(r, e) = os.path.splitext(jpath)
return r + '.0'
def tensor_from_tensordef(td, storage):
t = torch.FloatTensor()
offset = td['offset']
tsize = torch.Size... | LanguageModel.py | MIT | 8,492 | 5f3b8bf36c8797ae8b8c59b1ba5a7acac40091f7 | Python | py | |
import torch
from .base import Energy
__all__ = ["DoubleWellEnergy", "MultiDimensionalDoubleWell"]
class DoubleWellEnergy(Energy):
def __init__(self, dim, a=0, b=-4.0, c=1.0):
super().__init__(dim)
self._a = a
self._b = b
self._c = c
def _energy(self, x):
d = x[...,... | bgflow/distribution/energy/double_well.py | MIT | 1,357 | 1ec1e0bcd3b5b29807509e4dea8aa0981b327bc1 | 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... | packages/pytea/pytest/benchmarks/transformers/examples/distillation/run_squad_w_distillation.py | MIT | 36,202 | 3a8af71267f005ef51afd481f9c99e06854fd3c1 | Python | py | |
import cv2
import numpy as np
import torch
import torch.nn as nn
class Sobel(nn.Module):
"""Sobel layer."""
def __init__(self,
isotropic=False,
out_channels=2,
use_threshold=False,
to_grayscale=True):
super(Sobel, self).__init__()
... | openmixup/models/utils/layers/sobel.py | Apache-2.0 | 7,871 | 12e80151a85e8ddc77c89164e1a4ae98122e857f | Python | py | |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import time
import torch
import torch.nn as nn
from torch.autograd import gradcheck
from dcn_v2 import DCNv2
from dcn_v2_func import DCNv2Function
from dcn_v2 import DCNv2Pooling
from dcn... | src/lib/models/networks/DCNv2/test.py | MIT | 9,286 | 3a8b2e4b7fa6c3239e78ef427f10b06746060525 | Python | py | |
import os
import pickle
import tempfile
from unittest import TestCase
import numpy as np
import pandas as pd
import pyarrow as pa
from absl.testing import parameterized
import datasets.arrow_dataset
from datasets import concatenate_datasets, load_from_disk, temp_seed
from datasets.arrow_dataset import Dataset
from da... | tests/test_arrow_dataset.py | Apache-2.0 | 71,549 | b2d8f7059ef0df4d66d9a701b5f86d920ec1d189 | Python | py | |
import os.path as osp
import mmcv
import numpy as np
from mmcv.parallel import DataContainer as DC
from torch.utils.data import Dataset
from .transforms import (ImageTransform, BboxTransform, MaskTransform,
Numpy2Tensor)
from .utils import to_tensor, random_scale
from .extra_aug import ExtraA... | mmdet/datasets/custom.py | Apache-2.0 | 11,686 | d791c5265c8cbda8dee9ab4fe50d805f5b2523ac | Python | py | |
import copy
import json
from os import PathLike
from typing import Any, Dict, Iterable, Set, Union
import torch
from numpy.testing import assert_allclose
from allennlp.commands.train import train_model_from_file
from allennlp.common import Params
from allennlp.common.testing.test_case import AllenNlpTestCase
from all... | allennlp_test/testdata/allennlp/common/testing/tmp.py | Apache-2.0 | 9,154 | 3a8b7692ff3efbdab6eb5762f9e2c4148352d7a0 | Python | py | |
import torch
from torchfm.layer import FactorizationMachine, FeaturesEmbedding, FeaturesLinear
class FactorizationMachineModel(torch.nn.Module):
"""
A pytorch implementation of Factorization Machine.
Reference:
S Rendle, Factorization Machines, 2010.
"""
def __init__(self, field_dims, e... | torchfm/model/fm.py | MIT | 762 | d75cf04f19f351e7142db0b6c3bbf88fd5aaceeb | Python | py | |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Donny You (youansheng@gmail.com)
# CPN fot Parts Detection.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.nn as nn
import torch
import math
from models.backbones.backbone_selector impor... | models/pose/single/cpn.py | Apache-2.0 | 6,587 | d76d4c8d499b342be025863be0307cf381c4947d | Python | py | |
from transformers import BertTokenizer
from model import Seq2Seq_bert, LSTM_G, LSTM_A
from baseline_module.baseline_model_builder import BaselineModelBuilder
from data import AGNEWS_Dataset, IMDB_Dataset, SNLI_Dataset, SST2_Dataset
from config import AttackConfig
from torch.utils.data import DataLoader
from calc_BertSc... | create_perturb_text.py | Apache-2.0 | 13,673 | 3a8b9eb08a824e3b965074ea93d8cb7741df2607 | Python | py | |
""" Checkpoint Saver
Track top-n training checkpoints and maintain recovery checkpoints on specified intervals.
Hacked together by / Copyright 2020 Ross Wightman
"""
import glob
import operator
import os
import logging
import torch
from .model import unwrap_model, get_state_dict
_logger = logging.getLogger(__nam... | timm/utils/checkpoint_saver.py | Apache-2.0 | 6,139 | 1ee29ee6b6a9a97e7148b8d444dafe89ef06a493 | Python | py | |
import cv2
import os
import numpy as np
import torch
from his_evaluators.metrics.yolov3 import YoLov3HumanDetector, pad_to_square, resize
if __name__ == "__main__":
# device = torch.device("cuda:0")
device = torch.device("cpu")
sample_dir = "./data"
img_names = os.listdir(sample_dir)
detector =... | thirdparty/his_evaluators/tests/human_detector_test.py | MIT | 1,634 | 5f6f0393132e67d9ec545a822ef1756346883342 | Python | py | |
#!/usr/bin/env python
# coding: utf-8
# ## Tacotron 2 inference code
# Edit the variables **checkpoint_path** and **text** to match yours and run the entire code to generate plots of mel outputs, alignments and audio synthesis from the generated mel-spectrogram using Griffin-Lim.
# #### Import libraries and setup ma... | inference_one_hot.py | BSD-3-Clause | 2,667 | 5f90fb2cc9197e4ca8dca496a9f88c139ec125bc | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | pytorch_lightning/plugins/training_type/training_type_plugin.py | Apache-2.0 | 5,686 | d7c3b4d4d77e1a647916ac060cf766a8d52379a2 | Python | py | |
from overrides import overrides
import torch
import torch.nn as nn
import torch.nn.functional as F
from claf.decorator import register
from claf.model.base import ModelWithTokenEmbedder
from claf.model.reading_comprehension.mixin import SQuADv1
from claf.modules import attention, initializer
from claf.modules import f... | claf/model/reading_comprehension/docqa.py | MIT | 10,468 | 3a8c1297d52bc6b6c8b2daa1e0d91a9e2d84b53d | Python | py | |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# This s... | onnxruntime/python/tools/transformers/models/gpt2/gpt2_beamsearch_tester.py | MIT | 16,816 | 3a8c17a3b7c7e67eb4ba2bcc1f57eef5535fbaa8 | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, dim):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1, bias=False)
self.bn1 = nn.GroupNorm(2, dim, eps=1e-4)
self.re... | lib/layers/resnet.py | MIT | 2,335 | 4b7e370adc293e6a978250141230ff8711fa47dd | Python | py | |
import os
import time
import torch
import argparse
import scipy.io
import warnings
from torch.autograd import Variable
from torchvision import datasets, transforms
import dataset
from darknet import Darknet
from utils import *
from MeshPly import MeshPly
from raptor_specific_utils import *
import pdb
def valid(datac... | valid.py | MIT | 13,664 | 03eeaecd9691da8f534955a788eacd9f32622557 | Python | py | |
import torch
class SobolEngine(object):
r"""
The :class:`torch.quasirandom.SobolEngine` is an engine for generating
(scrambled) Sobol sequences. Sobol sequences are an example of low
discrepancy quasi-random sequences.
This implementation of an engine for Sobol sequences is capable of
samplin... | venv/Lib/site-packages/torch/quasirandom.py | Apache-2.0 | 5,061 | 7c83ee67ae840e5e59909aaa26c8a32692f799a6 | Python | py | |
# -------------------------------------#
# 对数据集进行训练
# -------------------------------------#
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.utils.data import DataLoader
from nets.yolo import YoloBody
from nets.yolo_training import YOLOLoss, weights_ini... | Deep-Learning-Notes/Object Detection/yolox/train.py | MIT | 10,597 | 3a8c50b5f54c8f493fd2a9c0324c7a5c339e64f9 | Python | py | |
import torch.utils as utils
import argparse
import os
import random
import time
import numpy as np
import torch
import sys
# sys.path.append('/home/lthpc/yifeis/pose/StablePose/')
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
from datasets.tless.dataset... | test-tless.py | MIT | 13,103 | e9335198fbda1cedfd19ec4f585162aaf9da9f79 | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | torchmetrics/retrieval/hit_rate.py | Apache-2.0 | 4,283 | 3a8c5616a9203307d5cdef90c89e1dbe1efbd6c1 | Python | py | |
"""model.py - Model and module class for EfficientNet.
They are built to mirror those in the official TensorFlow implementation.
"""
# Author: lukemelas (github username)
# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch
# With adjustments and added comments by workingcoder (github username).
... | models/ClassicNetwork/efficientnet.py | Apache-2.0 | 17,478 | 3a8c583b864cd06eeb36067229d7b0fc3fb7d580 | Python | py | |
#!/usr/bin/env python
# coding: utf-8
from collections import OrderedDict
import os
import sys
import math
import json
import random
import pickle
import argparse
import functools
from collections import Counter
import nltk
import pandas
import numpy as np
from PIL import Image, ImageEnhance
import torch
from torch... | code/visualize_attentions.py | Apache-2.0 | 11,684 | e9cf6b44ef8a094306b69483ba1375362ed3c782 | Python | py | |
# Copyright (c) Open-MMLab. All rights reserved.
import copy
from collections import defaultdict
from itertools import chain
from torch.nn.utils import clip_grad
from mmcv.utils import TORCH_VERSION, digit_version
from ..dist_utils import allreduce_grads
from ..fp16_utils import LossScaler, wrap_fp16_model
from .hook... | mmcv/runner/hooks/optimizer.py | Apache-2.0 | 13,146 | 3a8c64cf62c76f3e63edfa861b98457c36a2d44d | Python | py | |
import argparse
import json
import os
import pickle
import sys
import sagemaker_containers
import torch
import torch.optim as optim
import torch.utils.data
from torchvision import datasets
import torchvision.transforms as transforms
import numpy as np
import torchvision.models as models
from model import convClassifie... | train/train.py | Apache-2.0 | 7,880 | 7032509438bdf9329c124f5d3e2365367b489be7 | Python | py | |
import gym
import numpy as np
from envs.deep_cure_env import DeepCure, random_base_infect_rate, random_lifetime, ForeignCountry
import matplotlib.pyplot as plt
from plotting import plot
from stable_baselines3 import DQN, A2C
import torch as th
from stable_baselines3.common.callbacks import EvalCallback
def l... | deep_cure_learning/stable.py | MIT | 1,201 | 03f110d365b3946e9e147e0f50399be224c45657 | Python | py | |
import unittest
import numpy as np
from meta_learn.GPR_mll import GPRegressionLearned
from meta_learn.GPR_meta_mll import GPRegressionMetaLearned
from gpytorch.kernels import CosineKernel
import torch
class TestGPR_mll(unittest.TestCase):
def setUp(self):
## --- generate toy data --- #
torch.ma... | tests/test_GPR.py | MIT | 13,381 | 5e04a9863a4ab25575ee643f1d6816cfcb50d8dd | Python | py | |
import pytest
import torch
from tests.pytorch_pfn_extras_tests.dataset_tests.tabular_tests import (
dummy_dataset,
) # NOQA
@pytest.mark.parametrize(
'batch_size,mode',
[(1, dict), (2, dict), (8, dict), (1, tuple), (2, tuple), (8, tuple)],
)
def test_with_dataloader(batch_size, mode):
size = 10
... | tests/pytorch_pfn_extras_tests/dataset_tests/tabular_tests/test_with_torch_dataloader.py | MIT | 992 | 3a8cd07a5166f33874fc7c19b144bfc363f9bfb9 | Python | py | |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from typing import List
import pytest
from torch.utils.data import DataLoader
from composer import Trainer
from composer.callbacks.early_stopper import EarlyStopper
from composer.core.time import Time, TimeUnit
from composer.trainer.dev... | tests/callbacks/test_early_stopper.py | Apache-2.0 | 1,768 | 3a8cd1a76ac2e93dd8afdd5505ec86f78ae68917 | Python | py | |
"""Private module; avoid importing from directly.
"""
import abc
from typing import List, Tuple
import fannypack
import torch
import torch.nn as nn
from overrides import overrides
from .. import types
class DynamicsModel(nn.Module, abc.ABC):
"""Base class for a generic differentiable dynamics model, with addit... | torchfilter/base/_dynamics_model.py | MIT | 7,426 | 3a8cd8956e7cf6991626f80ad928a917a290534a | Python | py | |
"""This script solves a global optimization function by finding the location
of its global optimum.
Currently, only MSN algorithm is avaiable to solve this problem.
"""
from __future__ import print_function
import sys, os
# Append SYSPATH in order to access different modules of the library
sys.path.insert(0, os.path.ab... | solving_scripts/function/solve_function_msn2.py | MIT | 2,072 | 3a8cf1012a0004c14f40ac053894ef3573866a0c | Python | py | |
# %% Load packages
import numpy as np
import torch
from eeyore.chains import ChainLists
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.constants import dtype
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.constants import (
num_chains, pred_interval_x1, pred_interval_x2, pred_iter_thres
)
fr... | bnn_mcmc_examples/examples/mlp/noisy_xor/setting1/mcmc/power_posteriors/benchmark_pred_posterior_vals_on_grid.py | MIT | 2,250 | b2c2b1f6bf792674a04248b0c16dfa0430b1ce1f | Python | py | |
from typing import Tuple
import math
import torch
import torchaudio
from torch import Tensor
__all__ = [
'get_mel_banks',
'inverse_mel_scale',
'inverse_mel_scale_scalar',
'mel_scale',
'mel_scale_scalar',
'spectrogram',
'fbank',
'mfcc',
'vtln_warp_freq',
'vtln_warp_mel_freq',
... | torchaudio/compliance/kaldi.py | BSD-2-Clause | 48,210 | e9189b217295570a1bb1e5d720682777caf8559e | Python | py | |
# Ke Chen
# knutchen@ucsd.edu
# HTS-AT: A HIERARCHICAL TOKEN-SEMANTIC AUDIO TRANSFORMER FOR SOUND CLASSIFICATION AND DETECTION
# Some layers designed on the model
# below codes are based and referred from https://github.com/microsoft/Swin-Transformer
# Swin Transformer for Computer Vision: https://arxiv.org/pdf/2103.14... | src/open_clip/htsat.py | CC0-1.0 | 38,132 | 45a0510c879f68bbcb96fffe221b0f0ec1d7d217 | Python | py | |
from torchvision import datasets
import argparse, os
import numpy as np
import torch
import torchvision.models as models
from submodlib.functions.facilityLocation import FacilityLocationFunction
from submodlib.helper import create_kernel
from submodlib.functions.disparityMin import DisparityMinFunction
from submodlib.... | build_dataset.py | MIT | 14,541 | 650c5c91070922caa17b7f1f3ff1cebecd459b40 | Python | py | |
import torch
# https://machinelearningmastery.com/divergence-between-probability-distributions/
def kl_divergence(p, q):
return torch.sum(p * torch.log2(p / q), dim=1)
def js_divergence(p, q):
m = 0.5 * (p + q)
return 0.5 * kl_divergence(p, m) + 0.5 * kl_divergence(q, m)
def inception_score(p_yx, eps=... | gans/helpers/metrics.py | Apache-2.0 | 666 | b2f1191ad0f2e480edc851aa0a67d820d224d1c8 | Python | py | |
# -*- coding: utf-8 -*-
"""
@Author: Lyzhang
@Date: 2019.1.24
@Description: The trainer of our parser.
"""
import os
import logging
import random
import numpy as np
import progressbar
import torch
import torch.nn as nn
from util.DL_tricks import *
import torch.optim as optim
from config import *
from model.stacked_par... | model/stacked_parser_tdt_xlnet/trainer.py | Apache-2.0 | 12,617 | 3a8d48d65937ef0afe11906263463821d37478a6 | Python | py | |
import numpy as np
from torch.utils.data import Dataset
from ....builder import DATASETS
from ....datasets.transforms import Compose
from ....datasets import builder
@DATASETS.register_module()
class MemDPCDataset(Dataset):
def __init__(self,
data_dir,
data_source,
... | pyvrl/models/pretraining/memdpc/memdpc_dataset.py | MIT | 2,323 | 24be13a9e10b03fa9c4cf28d966570ad6fdea8fc | Python | py | |
## Edited and reused from https://github.com/nyu-dl/bert-gen/blob/master/bert-babble.ipynb
import os
import random
import numpy as np
from numpy.core.fromnumeric import shape
import torch
from transformers import BertForMaskedLM, BertTokenizer
from torch.distributions.categorical import Categorical
from datetime imp... | ml_privacy_meter/ml_privacy_meter/attack/mlm_mia/codes/get_enorm_transformer.py | MIT | 12,314 | 459aa26187e43a53f22f51f66809f9815d72f546 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['ghost_net']
def _make_divisible(v, divisor, min_value=None):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
if new_v < 0.9 * v:
new_v += ... | nets/ghostnet.py | MIT | 7,499 | 3a8d610327e0126928fc80d70391429030a39e28 | Python | py | |
import torch
import numpy as np
import random
import torch.nn.functional as F
class RandomHorizontalFlip(object):
def __call__(self, sample):
x, y = sample
assert type(x) is np.ndarray and type(y) is np.ndarray
if random.random() < 0.5:
x = x[:, :, -1::-1]
y = y[:, ... | dataloaders/myTransform.py | MIT | 1,093 | fcb16096f6cdf46de8c8e0fc9fe8c63d55dd949c | Python | py | |
from data import WiderFaceDetection, detection_collate, preproc, cfg_mnet, cfg_re50
from models.retinaface import SinvNet
from utils.retinaface import load_model, detect
import cv2
import numpy as np
import torch
cfg = cfg_re50
cfg['min_sizes']= [[12, 16],[24, 32],[48, 64],[96, 128],[192, 256],[256,512]]
cfg['steps'] ... | demo.py | MIT | 1,924 | 3a8d638661176295d589e0d4a9929eeb9d1b9d0d | Python | py | |
import utils.utils as utils
from utils.video_utils import create_video_from_intermediate_results
import torch
from torch.optim import Adam, LBFGS
from torch.autograd import Variable
import numpy as np
import os
import argparse
def build_loss(neural_net, optimizing_img, target_representations, content_feature_maps_in... | neural_style_transfer.py | MIT | 10,312 | 4296fed444a97dcd3eae83495dbae2967fd681ba | Python | py | |
# coding:utf-8
import functools
import logging
import time
import copy
import json
import math
import importlib
import pickle
import random
import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
from torch.autograd import Variable
from .... import extensions as E
from ..utils.pair_helpe... | unn/models/heads/pair_head_group/pair_head.py | Apache-2.0 | 69,811 | d7a77ed72556e1f023ba2f17183b0290353de357 | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import torch
from torch.nn import CrossEntropyLoss
import copy
import logging
class BaseLossConf(object):
@staticmethod
def get_conf(**kwargs):
# judge loss num & setting
kwargs['multiLoss'] = True if... | losses/BaseLossConf.py | MIT | 1,647 | b24584860f80e17a048a39b6348c81c4633a2bcc | Python | py | |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... | pennylane/collections/sum.py | Apache-2.0 | 2,195 | 3a8d8a56818c1e640a69ec21a0bdf50dce1bf650 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
class DataProvider():
def __init__(self, dataset, **kw):
self.args = kw
self.dataset = dataset
self.epoch = 0
self.DataLoader = None #data.DataLoader(self.dataset, *... | data/DataProvider.py | MIT | 1,084 | 24e31462fbe999a3b68b404c0ac0a1ab5969615f | Python | py | |
from collections import namedtuple
import torch
from FrEIA.framework import *
from FrEIA.modules import *
import sys
sys.path.insert(0, '../../')
from hint import *
from data import prepare_uci_loaders, Power as model
n_parameters = model.n_parameters
#################################################... | configs/uci_data/power_hint_8.py | MIT | 2,672 | d7c7fe2aced24a8dd5a0b12e61e3d6cb881eb28e | Python | py | |
# Copyright 2020 Nick Guletskii
#
# 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 ... | ori3nt8/training/model.py | Apache-2.0 | 5,081 | 3a8db077f5dd181d13799c1880702341cbd3a295 | Python | py | |
import torch as tc
from drl.utils.stats import standardize
def make_tensor():
return tc.arange(10).float()
def test_standardize():
tensor = make_tensor()
standardized = standardize(tensor)
tc.testing.assert_close(actual=standardized.mean(), expected=tc.tensor(0.))
tc.testing.assert_close(actual... | drl/utils/test_stats.py | MIT | 365 | 3a8db5b10d3b600a5992d132aac3a7b77be2b7c5 | Python | py | |
import copy
import torch
from torch.utils.data import DataLoader
import numpy as np
from tqdm import tqdm
from loading import DataLoading
from config import Params
from model import ESimCSE
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
def compute_loss(query, key, queue, tao=0.05):
'''
@function: 计算对比损失函... | esimcse/train2.py | Apache-2.0 | 9,395 | 3a8dd6fab73fa6e844099b69dfdb75f389fef197 | Python | py | |
#!/usr/bin/env python
# coding: utf-8
# # Testing cosmogan
# Sep 4, 2020
# Author: Venkitesh Ayyar. vpa@lbl.gov
#
# Borrowing pieces of code from :
#
# - https://github.com/pytorch/tutorials/blob/11569e0db3599ac214b03e01956c2971b02c64ce/beginner_source/dcgan_faces_tutorial.py
# - https://github.com/exalearn/epiCorv... | code/5_3d_cgan/1_main_code/main.py | BSD-3-Clause-LBNL | 30,071 | 7c1f1f43549c5d04a4876064c3ff5fc2b055adcf | Python | py | |
import torch
from torch import nn
from torchvision.ops import MultiScaleRoIAlign
from ..._internally_replaced_utils import load_state_dict_from_url
from ._utils import overwrite_eps
from .backbone_utils import resnet_fpn_backbone, _validate_trainable_layers
from .faster_rcnn import FasterRCNN
__all__ = ["KeypointRCN... | torchvision/models/detection/keypoint_rcnn.py | BSD-3-Clause | 18,284 | 7cd975ea6a09d12bcf075b3fd51c32ec7f39b23c | Python | py | |
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Union
from copy import deepcopy
import torch
from transformers.tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase
@dataclass
class DataCollatorForKmerModeling:
"""
Data collator used for Kmer modeling. Inputs... | src/model/data_collator.py | Apache-2.0 | 6,694 | 3a8df112aae74df2c5cb45fb1bbcc5c2e8334df8 | Python | py | |
import torch.nn as nn
import torch
import torch.nn.functional as F
import util.util as util
from .InnerCosFunction import InnerCosFunction
class InnerCos(nn.Module):
def __init__(self, crit='MSE', strength=1, skip=0, layer_to_last=3, device='gpu'):
super(InnerCos, self).__init__()
self.crit = crit
... | models/shift_net/InnerCos.py | MIT | 2,265 | 3a8df3b955cb3a4d84dfcbcbfb4b2413f75d47ea | Python | py | |
# Copyright 2019 Lorna 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 l... | nets/resnet_test.py | Apache-2.0 | 6,006 | 7cb8d223b4c676b9a68d950f5ee6c5f76481e816 | Python | py | |
"""
Modified from https://github.com/agrimgupta92/sgan/blob/master/sgan/data/trajectories.py.
This module contains:
Classes:
1. Pytorch Time series dataset class instance
2. Weighted train and test dataset loader with respect to class distribution
Helpers:
1. Class distribution in the dataset
"""
import logging
imp... | traja/dataset/dataset.py | MIT | 16,026 | 3a8e1413d8414f7e17f7e8144695477e67b259ee | Python | py | |
import sys
#sys.path.append('../')
from .base import AudioModel
from ..utils.stft import STFT, torch_spectrogram
import torch
class PyTorchAudioModel(AudioModel):
def __init__(self, model, decoder, device, sample_rate=16000):
self.model = model
self.device = device
self.model.to(self.device)... | Models/pytorch_model.py | MIT | 4,949 | 3a8e33ecce7490133cf642105bc6615d99ce74ff | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from collections import OrderedDict
from torch.autograd import Variable
from CSPDarknet import *
import cv2
use_attention = False
# CBL的构建
def conv2d(filter_in, filter_out, kernel_size, stride=1):
pad = (kernel_size - 1) // 2 if ker... | src/robot_learning/object_detect/scripts/noattneck.py | Apache-2.0 | 8,548 | 459b94a45df349bea892723b0da5654127470bc5 | Python | py | |
import math
import torch
import torch.nn as nn
def evaluate_jaccard(outputs, targets):
eps = 1e-15
jaccard_targets = (targets == 1).float()
jaccard_outputs = torch.sigmoid(outputs)
intersection = (jaccard_outputs * jaccard_targets).sum()
union = jaccard_outputs.sum() + jaccard_targets.sum()
... | losses.py | BSD-3-Clause | 1,136 | 3a8e54e0718672f77f98ac61835fa628418dcd75 | Python | py | |
import torch.nn.functional as F
import time
import torch
from utils import tps
def regression_loss(prediction_normalized, meta, alpha=1., **kwargs):
pred = prediction_normalized[0]
kp = meta['keypts_normalized'].to(pred.device)
B, nA, _ = pred.shape
return F.smooth_l1_loss(pred * alpha, kp * alpha)
... | model/loss.py | MIT | 9,968 | 5ec5a8a3f016e80765b5ab26b78a5311c7dd2a7f | Python | py | |
from __future__ import absolute_import, division, print_function, unicode_literals
import torch
import torch.nn as nn
from tests import utils
class TestLSTM(utils.TorchGlowTestCase):
def test_lstm_basic(self):
"""Basic test of the PyTorch lstm Node on Glow."""
class SimpleLSTM(nn.Module):
... | torch_glow/tests/nodes/lstm_test.py | Apache-2.0 | 4,744 | 340a379d5a4a50b11bc1a36fe9a598263d183dc4 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Edge Loss.
"""
from __future__ import annotations
from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn.modules.loss import _Loss
from onevision.factory import LOSSES
from onevision.nn.loss.charbonnier_loss i... | src/onevision/nn/loss/edge_loss.py | MIT | 7,412 | 4bc20c54c7f765d60ed0e35a42ceb14b1686a9b6 | Python | py | |
'''
@Author: WANG Maonan
@Date: 2021-02-06 19:24:50
@Description: 全连接网络, 用来直接使用统计特征来分类
@LastEditTime: 2021-02-06 19:35:11
'''
import numpy as np
import torch
import torch.nn as nn
mean_val = np.array([2.86401660e-03, 0.00000000e+00, 3.08146750e-03, 1.17455448e-02,
5.75561597e-03, 6.91365004e-04, 6.64955585e-02... | TrafficFlowClassification/models/dnn.py | MIT | 2,690 | 3a8e77b4244d2faf8ad9095ad0ebdca49bb4c2aa | Python | py | |
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdetection.core import multi_apply, multiclass_nms, distance2bbox, force_fp32
from ..builder import build_loss
from ..registry import HEADS
from ..utils import bias_init_with_prob, Scale, ConvModule
INF = 1e8
@HEADS.register_module
class FCOS... | mmdet/models/anchor_heads/fcos_head.py | Apache-2.0 | 15,876 | d7ba2ca2fa8688f6ccbffcbf0ab102a101dbcbd2 | Python | py | |
import json
import logging
import math
import os
import random
import warnings
from multiprocessing import cpu_count
from pathlib import Path
import numpy as np
from tqdm.auto import tqdm, trange
import pandas as pd
import torch
from simpletransformers.config.global_args import global_args
from simpletransformers.seq... | simpletransformers/seq2seq/seq2seq_model.py | Apache-2.0 | 44,387 | fcdad46c266fc24177fe24a5797f5b3e4a5f3b44 | Python | py | |
import argparse
import os
from math import log10
import sys
import pandas as pd
import torch.optim as optim
import torch.utils.data
import torchvision.utils as utils
from torch.autograd import Variable
from torch.utils.data import DataLoader
from tqdm import tqdm
import pytorch_ssim
from data_utils import TrainDatase... | train.py | MIT | 7,980 | a901e2ae21f448e6fa790963df6e7804688dd33c | Python | py | |
from __future__ import annotations
from typing import Any, Callable, Optional, Tuple, Union, cast
from kit import gcopy, implements, parsable
from kit.misc import str_to_enum
from kit.torch.data import TrainingMode
import numpy as np
import pytorch_lightning as pl
import torch
from torch import Tensor, nn, optim
from ... | conduit/models/self_supervised/dino/lightning.py | MIT | 11,461 | 3416f70586e1ee2f365c5e42fb3eb932776b7acc | Python | py | |
# Owner(s): ["module: onnx"]
import unittest
import torch
import torch.utils.cpp_extension
import onnx
import caffe2.python.onnx.backend as c2
import numpy as np
from test_pytorch_onnx_caffe2 import do_export
from test_pytorch_onnx_onnxruntime import run_model_test
from torch.onnx.symbolic_helper import _unimplemen... | test/onnx/test_custom_ops.py | Intel | 5,227 | 7c1f4c27c0d62e22a08bc5cfd4cffd4a36a80461 | Python | py | |
import torch
import torch.nn as nn
from siam_mask.utils.anchors import Anchors
class SiamMask(nn.Module):
def __init__(self, anchors=None, o_sz=127, g_sz=127):
super(SiamMask, self).__init__()
self.anchors = anchors # anchor_cfg
self.anchor_num = len(self.anchors["ratios"]) * len(self.anc... | siam_mask/models/siammask.py | MIT | 1,723 | 28ab2e3667d7e458947657ffb1f78283bc070b87 | Python | py | |
import torch.nn as nn
from semseg.models.utils import *
class linknet(nn.Module):
def __init__(
self,
feature_scale=4,
n_classes=21,
is_deconv=True,
in_channels=3,
is_batchnorm=True,
):
super(linknet, self).__init__()
self.is_deco... | semseg/models/linknet.py | MIT | 3,553 | 3a8f01be21d5f660c615f073ff48da0697af44b7 | Python | py | |
import logging
import os.path
from PIL import Image as PILImage
from io import BytesIO
from itertools import chain, repeat
from typing import List
import numpy as np
from aim.sdk.num_utils import inst_has_typename
from aim.storage.object import CustomObject
from aim.storage.types import BLOB
logger = logging.getLog... | aim/sdk/objects/image.py | Apache-2.0 | 8,482 | 5f99805780e46acfbc95fbf4dcfe705f27620921 | Python | py | |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
Pytorch modules
some classes are modified from HuggingFace
(https://github.com/huggingface/transformers)
"""
import copy
import json
import logging
from io import open
import torch
from torch import nn
from apex.normalization.fused_layer_norm im... | model/model.py | MIT | 27,086 | 52b5aa7902fdba525ac11b646fc1456982cca392 | Python | py | |
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torch import nn, optim
from torch.nn.functional import relu as Relu
from tqdm import tqdm
# train settings
batch_size = 64
# MNIST Datasets
train_dataset = datasets.MNIST(root='./data/',
train=True,... | main.py | MIT | 2,532 | 5f67a4445e71ac28609d3fbfc7febe9447558af1 | Python | py | |
import numpy as np
import torch
from torch import nn
from ..wdtypes import *
def dense_layer(inp: int, out: int, p: float = 0.0, bn=False):
layers = [nn.Linear(inp, out), nn.LeakyReLU(inplace=True)]
if bn:
layers.append(nn.BatchNorm1d(out))
layers.append(nn.Dropout(p))
return nn.Sequential(*l... | pytorch_widedeep/models/deep_dense.py | MIT | 5,307 | 3a8f881979c538317bc62d277861ced974195f64 | Python | py | |
# Code for "ActionCLIP: ActionCLIP: A New Paradigm for Action Recognition"
# arXiv:
# Mengmeng Wang, Jiazheng Xing, Yong Liu
import os
import clip
import torch.nn as nn
from datasets import Action_DATASETS
from torch.utils.data import DataLoader
from tqdm import tqdm
import wandb
import argparse
import shu... | test.py | MIT | 6,347 | b2ac99f2fb7d0f4eb10d3717629a84941aa8f497 | Python | py | |
# -*- coding: utf-8 -*-
import torch
import numpy as np
import cv2
import vision_transformer
from .ViT_timm import VisionTransformer
from .ViT import ViT
from PIL import Image
from vision_transformer import timm
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
class Cam():
def __init__(... | vision_transformer/cam.py | MIT | 4,983 | 45fc7d5684d2473ebb9e0160fc59db3766219004 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .batchnorm import SynchronizedBatchNorm2d
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm):
super(_ASPPModule, self).__init__()
self.atrous_conv = nn.Conv2d(inplanes,... | src/network/deeplab/aspp.py | MIT | 3,567 | 3a8fa0551b8ac8d8751f7d150a7ec20bcc0ee36e | Python | py | |
"""Accuracy tests."""
from typing import NamedTuple
import pytest
import torch
from torch import Tensor
from conduit.fair.metrics.accuracy_per_sens import AccuracyPerSens
NUM_PROCESSES = 2
NUM_BATCHES = 10
BATCH_SIZE = 32
NUM_CLASSES = 5
EXTRA_DIM = 3
THRESHOLD = 0.5
class Input(NamedTuple):
preds: Tensor
... | tests/fair/metrics/classification/accuracy_per_sens_test.py | MIT | 4,152 | 3a8fa112e8b8ccd8dc7e3c21fd7c8a9d99f4cfeb | Python | py | |
import os, sys
import warnings
from os.path import join as opj
import omegaconf
import numpy as np
import random
import pathlib
import subprocess
import torch
from torch.utils.data import Subset, random_split
### load cfg
def get_configs(yaml_file):
"""
get command line args and configs
Parameters
... | examples/previous_code/utils/setting.py | MIT | 7,157 | 3a8fa9a9009d666dfaaabf25ca33a5866159af3e | Python | py | |
# -*- coding: utf-8 -*-
import numpy as np
import time
import torch
import scipy.optimize as opt
import pywph as pw
#######
# INPUT PARAMETERS
#######
M, N = 512, 512
J = 7
L = 4
dn = 2
norm = "auto" # Normalization
pbc = True # Periodic boundary conditions
device = 0
optim_params = {"maxiter": 100, "gtol"... | examples/synthesis.py | BSD-3-Clause | 3,221 | e614c687beeb1c50c12264f37c0ddc4324fa22f3 | 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 argparse
import torchvision as tv
from transform_finder import build_transform
from utils.converters import PilToNumpy, NumpyToPil
impo... | imagenet_c_bar/make_tiny_imagenet_c_bar.py | MIT | 4,047 | 3a8fcb5dd83ca3c0bbb4206f2183b035386363a3 | Python | py | |
import collections.abc as collections
import functools
import logging
import random
import warnings
from typing import Any, Callable, Dict, Optional, TextIO, Tuple, Type, TypeVar, Union, cast
import torch
__all__ = ["convert_tensor", "apply_to_tensor", "apply_to_type", "to_onehot", "setup_logger", "manual_seed"]
de... | ignite/utils.py | BSD-3-Clause | 9,473 | d7981d80f3033922ed356664273892106715dfee | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.